text stringlengths 8 267k | meta dict |
|---|---|
Q: Javascript - Get Sound Data I'm wondering if any new HTML5 functions or existing JS library would allow me to access information about the sound that's currently playing in an Audio object. For example, I'd like to be able to access an array of ranges the a song is currently playing at (that is, low values appear for deep bass sounds and higher values appear for shriller sounds). I'm not a sound engineer, so I'm not quite sure what the correct terminology is.
A comparable library would be the C++ BASS library (http://www.un4seen.com/), although I certainly don't need the same breadth of functionality.
I did a little more digging around and found this: chromium.googlecode.com/svn/trunk/samples/audio/visualizer-gl.html
It's pretty much what I'm looking for, but I can't figure out how it works. Thoughts?
A: *
*The chromium visualizer uses the Web Audio API.
*Firefox offers the Audio Data API.
These are the two options available at the moment, and they're not compatible with each other. Eventually an agreement will be reached.
If you intend to do something cross-browser, you're condemned to using Flash for now, there is a pretty good library called SoundManager2 that gives you the necessary data. Check out their visualization demos.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: I am using fgets() to read in a line in PHP. But i am getting a wierd result? $size = intval(trim(fgets($fp,4)));
$triangle = range(1,$size);
for($j=0;$j<$size;$j=$j+1)
$triangle[$j] = split(" ",trim(fgets($fp,400)));
This code reads in the number of lines to read, then reads them one by one. Issue is, when first input line ends in space, it reads that space as a new line.
A: you can read full file content by file_get_contents.
<?php
$content= file_get_contents('myfile.txt');
echo $content;
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android - Calculate Distance Using Haversine Formula (Using GPS , Lat and Long) I need some help :) I am assign with a project to come out with the distance / speed and time. I have already come out with the Timer. However, the distance is giving me some problem. The distance does not changed at all from I travel from one place to another.
//GPS
private static Double EARTH_RADIUS = 6371.00; // Radius in Kilometers default
private static final String DEBUG_TAG = "GPS";
private String[] location;
private double[] coordinates;
private double[] gpsOrg;
private double[] gpsEnd;
private LocationManager lm;
private LocationListener locationListener;
private double totalDistanceTravel;
private boolean mPreviewRunning;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waterspill);
/*getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);*/
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
distanceCal=new LocationUtil(EARTH_RADIUS);
totalDistanceTravel=0;
// ---Additional---
//mapView = (MapView) findViewById(R.id.mapview1);
//mc = mapView.getController();
// ----------------
txtTimer = (TextView) findViewById(R.id.Timer);
gpsOnOff = (TextView) findViewById(R.id.gpsOnOff);
disTrav = (TextView) findViewById(R.id.disTrav);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(startButtonClickListener);
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(stopButtonClickListener);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(testButtonClickListener);
startButton.setEnabled(false);
stopButton.setEnabled(false);
getLocation();
}
public void getLocation()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,locationListener);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);
}
private OnClickListener startButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsOrg=coordinates;
totalDistanceTravel=0;
Toast.makeText(getBaseContext(),
"Start Location locked : Lat: " + gpsOrg[0] +
" Lng: " + gpsOrg[1],
Toast.LENGTH_SHORT).show();
if (!isTimerStarted)
{
startTimer();
isTimerStarted = true;
}
stopButton.setEnabled(true);
}
};
private OnClickListener stopButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsEnd=coordinates;
//gpsEnd = new double[2];
//gpsEnd[0]=1.457899;
//gpsEnd[1]=103.828659;
Toast.makeText(getBaseContext(),
"End Location locked : Lat: " + gpsEnd[0] +
" Lng: " + gpsEnd[1],
Toast.LENGTH_SHORT).show();
double d = distFrom(gpsOrg[0],gpsOrg[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
}
};
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return new Float(dist).floatValue();
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
}
startButton.setEnabled(true);
}
private double[] getGPS() {
List<String> providers = lm.getProviders(true);
double[] gps = new double[2];
//Loop over the array backwards, and if you get an accurate location, then break out the loop
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
String s = providers.get(i);
Log.d("LocServ",String.format("provider (%d) is %s",i,s));
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
Log.d("LocServ",String.format("Lat %f, Long %f accuracy=%f",gps[0],gps[1],l.getAccuracy()));
gpsOnOff.setText("On");
}
}
return gps;
}
Is there anything wrong with my codes. Please advice and Thanks a lot for your help :)
A: Test your formula with this: The distance between {-73.995008, 40.752842}, and {-73.994905, 40.752798} should be 0.011532248670891638 km.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Advantages/disadvantages to using struct as a parameter while defining new API The APIs that I am writing are for a Ruby class that inherits from ActiveRecord. I am trying to write static methods to avoid leaking the ActiveRecord instance. All the APIs now need tuple to uniquely identify a database row.
Is it a good idea to have APIs of the form:
API1(abc, def, ....)
API2(abc, def, ....)
and so on
or should I define a struct with fields to help with future changes?
Any other ideas are greatly welcome!
A: Using a struct would be strange in Ruby, a Hash would be normal:
def self.api1(options)
# Look at options[:abc], options[:def], ...
end
And then it could be called using named arguments like this:
C.api1 :abc => 'abc', :def => '...'
Easy to extend, common Ruby practice, and easy to make certain parameters optional.
A: To continue what mu is describing, a common Ruby idiom you'll see it to have a method set itself some default options and then merge into that hash the options that the method received. This way you can be sure that some minimum list of options always exist:
def self.api1(options={})
default_options = { :foo => 'bar', :baz => nil }
options = default_options.merge options
# Now include your code and you can assume that options[:foo] and options[:bar] are there
end
This comes in handy when your method, for example, outputs the value of :baz. Now you don't need to check that it exists first, you can just output it knowing that it would always exist.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing grails "no conversion strategy" error that is not in message.properties Is there a way to change Grails conversion mismatch error to custom message?
I am getting:
Failed to convert property value of type java.lang.String to required
type java.util.Map for property items;nested exception is
java.lang.IllegalStateException: Cannot convert value of type
[java.lang.String] to required type [java.util.Map] for property
items: no matching editors or conversion strategy found
This error type is not in messages.properties. I am getting this if a user tries to inject request parameter which is not a map into my Command Object, they shouldn't be doing this, but that besides the point:
class CartCommand implements Serializable {
Map<Integer, Integer> items =
MapUtils.lazyMap([:], FactoryUtils.constantFactory(''))
}
Thanks
A: Use the following key in your message.properties:
cartCommand.items.typeMismatch.map
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get day of the week from GregorianCalendar I have a date and I need to know the day of the week, so I used a GregorianCalendar object but I get back some dates that are incorrect.
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
What am I doing wrong?
Thanks!
EDIT SOLUTION:
mont--;
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
if(i == 2){
dayOfTheWeek = "Mon";
} else if (i==3){
dayOfTheWeek = "Tue";
} else if (i==4){
dayOfTheWeek = "Wed";
} else if (i==5){
dayOfTheWeek = "Thu";
} else if (i==6){
dayOfTheWeek = "Fri";
} else if (i==7){
dayOfTheWeek = "Sat";
} else if (i==1){
dayOfTheWeek = "Sun";
}
A: Joda-Time
I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:
import org.joda.time.DateTime;
DateTime date = new DateTime(year, month, day, 0, 0, 0);
or
DateTime date = DateTime().now();
Day of week (int):
date.getDayOfWeek();
Day of week (short String) using toString() and DateTimeFormat options:
date.toString("EE");
A: TimeZone timezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(timezone);
calendar.set(year, month, day, hour, minute, second);
String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());//Locale.US);
String dayName=calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());//Locale.US);
A: tl;dr
myGregCal // `GregorianCalendar` is a legacy class, supplanted by the modern `java.time.ZonedDateTime` class.
.toZonedDateTime() // Convert to `ZonedDateTime`.
.getDayOfWeek(). // Extract a `DayOfWeek` enum object, one of seven pre-defined objects, one for each day of the week.
.getDisplayName( // Automatically localize, generating a `String` to represent the name of the day of the week.
TextStyle.SHORT , // Specify how long or abbreviated.
Locale.US // Locale determines the human language and cultural norms used in localization.
) // Returns a `String` object.
Mon
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date for people in a certain region, without time-of-day and without time zone.
.getDayOfWeek() // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Generate a string representing that day-of-week, localized using the human language and cultural norms of a particular locale.
lundi
java.time
Convert the troublesome old legacy java.util.GregorianCalendar object to a modern java.time object by calling new methods added to the old class.
ZonedDateTime zdt = myGregCal.toZonedDateTime();
Get the DayOfWeek enum object for that moment in that time zone.
DayOfWeek dow = zdt.getDayOfWeek();
dow.toString(): WEDNESDAY
Pass these DayOfWeek objects around your code rather than passing integers like 1-7 or strings like "MON". By using the enum objects you make your code more self-documenting, provide type-safety, and ensure a range of valid values.
For presentation to the user, ask the DayOfWeek object to translate the name of the day of the week to a human language defined in a Locale.
String output =
dow.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.CANADA_FRENCH
)
;
mercredi
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
*
*Java SE 8, Java SE 9, Java SE 10, and later
*
*Built-in.
*Part of the standard Java API with a bundled implementation.
*Java 9 adds some minor features and fixes.
*Java SE 6 and Java SE 7
*
*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
*Android
*
*Later versions of Android bundle implementations of the java.time classes.
*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Return string until matched string in Ruby How do you return the portion of a string until the first instance of " #" or " Apt"?
I know I could split the string up into an array based on "#" or "Apt" and then calling .first, but there must be a simpler way.
A: String splitting is definitely easier and more readable than trying to extract the portion of the string using a regex. For the latter case, you would need a capture group to get the first match. It will be the same as string splitting
string.split(/#|Apt/, 2).first
A: I'd write a method to make it clear. Something like this, for example:
class String
def substring_until(substring)
i = index(substring)
return self if i.nil?
i == 0 ? "" : self[0..(i - 1)]
end
end
A: Use String#[] method. Like this:
[
'#foo',
'foo#bar',
'fooAptbar',
'asdfApt'
].map { |str| str[/^(.*)(#|Apt)/, 1] } #=> ["", "foo", "foo", "asdf"]
A: I don't write in ruby all that much, but I'm sure you could use a regular expression along the lines of
^.*(#|Apt)
Or, if you put the string into a tokenizer, you could do something with that, but it'd be tougher considering you are looking for a word and not just a single character.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Wordpress Dynamic menu highlighting if page belongs to specific category I'm looking for a way to dynamically highlight a menu item anytime a user is viewing a page that is assigned to a given taxonomy or category. For example a nav bar at the top with items "Products" and "Strategy". Any page or post that is created and has the category or taxonomy "product" would cause the Products menu item to be highlighted when you are on the page for that product. I'm thinking if I could figure out a way to just apply a class to that item based on the criteria above, that would do it. Any ideas? I'm stumped on this one.
A: I would recommend a front end approach. Here's what I'm thinking:
1) You have 2 or more categories: Products and Strategy ...
2) Each post in Products will have a body class string that contains a class which is probably called products-taxonomy or something like that.
3) With jQuery you can check for products-taxonomy or strategy-taxonomy and highlight the specific menu-item. This can be done easily with jQuery selectors provided that you add a specific class to your products category when you create your menu.
It would be something like this:
add class for products menu item : 'productsMenu'
add class for strategy menu item : 'strategyMenu'
make sure you echo the body_class
var $body = $(body); // better select just once the body
if($body.hasClass('products-taxonomy')) {
// highlighetMenuItem should be your highlighting class
$(".productsMenu").addClass("highlighetMenuItem");
} else if($body.hasClass('strategy-taxonomy')) {
$(".strategyMenu").addClass("highlighetMenuItem");
}
And yeah... you need jQuery on the front end if you want this to work. Or you could use pure javaScript in almost as many lines of code. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.net MVC: Execute Razor from DB String? I was thinking about giving end users the ability to drop Partial Views (controls) into the information being stored in the database. Is there a way to execute a string I get from the database as part of the Razor view?
A: Update (I forgot all about this)
I had asked this question previously (which lead me to create RazorEngine) Pulling a View from a database rather than a file
I know of at least two: RazorEngine, MvcMailer
I have a bias towards RazorEngine as it's one that I've worked on but I have a much simpler one at Github called RazorSharp (though it only supports c#)
These are all pretty easy to use.
RazorEngine:
string result = RazorEngine.Razor.Parse(razorTemplate, new { Name = "World" });
MvcMailer
I haven't used this one so I can't help.
RazorSharp
RazorSharp also supports master pages.
string result = RazorSharp.Razor.Parse(new { Name = "World" },
razorTemplate,
masterTemplate); //master template not required
Neither RazorSharp, nor RazorEngine support any of the Mvc helpers such as Html and Url. Since these libraries are supposed to exist outside of Mvc and thus require more work to get them to work with those helpers. I can't say anything about MvcMailer but I suspect the situation is the same.
Hope these help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Converting a parent child relationship into Json in python I have a list of list like the below. The first column is the parent, second is the child, and the third are node attributes. I need to convert the below to a JSON format like the following.
0 0 "flair" 1000
0 1 "analytics" 1000
1 2 "cluster" 1000
2 3 "AgglomerativeCluster" 1000
2 4 "CommunityStructure" 1000
1 5 "Graph" 1000
5 6 "BetweennessCentrality" 1000
5 7 "LinkDistance"
pc = []
pc.append([0, 0 ,"flair", 1000])
pc.append([0,1, "analytics", 1000])
pc.append([1, 2, "cluster", 1000])
pc.append([2 ,3, "AgglomerativeCluster", 1000])
pc.append([2 ,4, "CommunityStructure" ,1000])
pc.append([1 ,5, "Graph", 1000])
pc.append([5, 6, "BetweennessCentrality", 1000])
pc.append([5, 7, "LinkDistance",1000])
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 3938},
{"name": "CommunityStructure", "size": 3812},
]
},
{
"name": "graph",
"children": [
{"name": "BetweennessCentrality", "size": 3534},
{"name": "LinkDistance", "size": 5731}
]
}
]
}
]
}
A: A little change to your input, for a root node "flair", I use '-1' as its parent id instead of '0'.
import json
pc = []
pc.append([-1, 0 ,"flair", 1000])
pc.append([0,1, "analytics", 1000])
pc.append([1, 2, "cluster", 1000])
pc.append([2 ,3, "AgglomerativeCluster", 1000])
pc.append([2 ,4, "CommunityStructure" ,1000])
pc.append([1 ,5, "Graph", 1000])
pc.append([5, 6, "BetweennessCentrality", 1000])
pc.append([5, 7, "LinkDistance",1000])
def listToDict(input):
root = {}
lookup = {}
for parent_id, id, name, attr in input:
if parent_id == -1:
root['name'] = name;
lookup[id] = root
else:
node = {'name': name}
lookup[parent_id].setdefault('children', []).append(node)
lookup[id] = node
return root
result = listToDict(pc)
print result
print json.dumps(result)
A: Not sure where those 'size' attributes are coming from, they don't appear in the 'pc' list, but assuming they're taken from the 4th item in each list and they should all be 1000 in the output tree, this should work
def make_tree(pc_list):
results = {}
for record in pc_list:
parent_id = record[0]
id = record[1]
if id in results:
node = results[id]
else:
node = results[id] = {}
node['name'] = record[2]
node['size'] = record[3]
if parent_id != id:
if parent_id in results:
parent = results[parent_id]
else:
parent = results[parent_id] = {}
if 'children' in parent:
parent['children'].append(node)
else:
parent['children'] = [node]
# assuming we wanted node id #0 as the top of the tree
return results[0]
pretty printing the output of make_tree(pc) I get
{'children': [{'children': [{'children': [{'name': 'AgglomerativeCluster',
'size': 1000},
{'name': 'CommunityStructure',
'size': 1000}],
'name': 'cluster',
'size': 1000},
{'children': [{'name': 'BetweennessCentrality',
'size': 1000},
{'name': 'LinkDistance',
'size': 1000}],
'name': 'Graph',
'size': 1000}],
'name': 'analytics',
'size': 1000}],
'name': 'flair',
'size': 1000}
which although the ordering of the key display is different, is almost like your sample output (except for the size values)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: initiate class with an argument in class declaration in my object State, i'd like to have object pq. but pq needs to be initialized with a parameter. is there a way to include a class that depends on a parameter into another class?
file.h
class Pq
{
int a;
Pq(ClassB b);
};
class State
{
ClassB b2;
Pq pq(b2);
State(ClassB b3);
};
file.cc
State::State(ClassB b3) : b2(b3) {}
A: You can initialize it in the initializer list, just like you do with b2:
State::State(ClassB b3) : b2(b3), pq(b2) {}
Keep in mind that members are initialized in the order they are declared in the header file, not the order of the initializers in the initializer list.
You need to remove the attempt at initialize it in the header as well:
class Pq
{
int a;
Pq(ClassB b);
};
class State
{
ClassB b2;
Pq pq;
State(ClassB b3);
};
A:
Class State{
public:
State(ClassB& bref):b2(bref),pq(b2){} // Depends on the order you declare objects
// in private/public/protected
private:
ClassB b2;
Pq pq;
};
In the above code you have to maintain that order in the initialization list otherwise you will get what not expected..therefore quite risky
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RoR3: How do I use the generator to generate views? I have this namespace:
namespace :manage do
# Directs /manage/products/* to Manage::ProductsController
resources :instructors
end
and I want to generate views in the appropriate sub folder and the controller.
What are the commands?
A: Just create the controller like this:
$ rails generate controller manage/instructors
create app/controllers/manage/instructors_controller.rb
invoke erb
create app/views/manage/instructors
invoke test_unit
create test/functional/manage/instructors_controller_test.rb
invoke helper
create app/helpers/manage/instructors_helper.rb
invoke test_unit
create test/unit/helpers/manage/instructors_helper_test.rb
As you can see, Rails has created the views folder for you as well. The views itself you need to create in that folder.
(I used Rails 3.0 in this example, but it holds for older and newer versions as well.)
A: I agree with @rdvdijk, but he left out an important note: controller actions can be appended to the end of this command. For example:
rails generate controller manage/instructors home an_action another_action .. etc
And it will generate views for each controller action specified.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Jquery AJAX with WebMethod removes zero from front I have following code. Jquery Ajax calls webmethod . If i pass zipcode "07306" it returns and sets session to "7306" . No idea why it removes zero from front!
function onChangeLocation(){
var newzip =$('#<%= txtNewLocation.ClientID %>').val();
$('#<%= lblDefaultLocation.ClientID %>').html(newzip);
$.ajax({
type: "POST",
url: "/WebMethods.aspx/ChangeLocation",
data: "{newLocation:" + newzip + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
[System.Web.Services.WebMethod()]
public static String ChangeLocation(String newLocation)
{
HttpContext.Current.Session["ClientZipCode"] = newLocation.ToString();
return newLocation.ToString();
}
Can someone please explain why it removes zero from front ?
A: The problem is that JS thinks it an integer changing
$('#<%= lblDefaultLocation.ClientID %>').html(newzip);
to
$('#<%= lblDefaultLocation.ClientID %>').html(newzip + '');
Should fix it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I select a record from one table in a mySQL database, based on the existence of data in a second? Please forgive my ignorance here. SQL is decidedly one of the biggest "gaps" in my education that I'm working on correcting, come October. Here's the scenario:
I have two tables in a DB that I need to access certain data from. One is users, and the other is conversation_log. The basic structure is outlined below:
users:
*
*id (INT)
*name (TXT)
conversation_log
*
*userid (INT) // same value as id in users - actually the only field in this table I want to check
*input (TXT)
*response (TXT)
(note that I'm only listing the structure for the fields that are {or could be} relevant to the current challenge)
What I want to do is return a list of names from the users table that have at least one record in the conversation_log table. Currently, I'm doing this with two separate SQL statements, with the one that checks for records in conversation_log being called hundreds, if not thousands of times, once for each userid, just to see if records exist for that id.
Currently, the two SQL statements are as follows:
select id from users where 1; (gets the list of userid values for the next query)
select id from conversation_log where userid = $userId limit 1; (checks for existing records)
Right now I have 4,000+ users listed in the users table. I'm sure that you can imagine just how long this method takes. I know there's an easier, more efficient way to do this, but being self-taught, this is something that I have yet to learn. Any help would be greatly appreciated.
A: You have to do what is called a 'Join'. This, um, joins the rows of two tables together based on values they have in common.
See if this makes sense to you:
SELECT DISTINCT users.name
FROM users JOIN conversation_log ON users.id = converation_log.userid
Now JOIN by itself is an "inner join", which means that it will only return rows that both tables have in common. In other words, if a specific conversation_log.userid doesn't exist, it won't return any part of the row, user or conversation log, for that userid.
Also, +1 for having a clearly worded question : )
EDIT: I added a "DISTINCT", which means to filter out all of the duplicates. If a user appeared in more than one conversation_log row, and you didn't have DISTINCT, you would get the user's name more than once. This is because JOIN does a cartesian product, or does every possible combination of rows from each table that match your JOIN ON criteria.
A: Something like this:
SELECT *
FROM users
WHERE EXISTS (
SELECT *
FROM conversation_log
WHERE users.id = conversation_log.userid
)
In plain English: select every row from users, such that there is at least one row from conversation_log with the matching userid.
A: What you need to read is JOIN syntax.
SELECT count(*), users.name
FROM users left join conversion_log on users.id = conversation_log.userid
Group by users.name
You could add at the end if you wanted
HAVING count(*) > 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Run IDE, for Java, ON Android 3.1 I am about to purchase a tablet probably a Thrive. I need to know if I can write applications in Java, to use on a regular PC, on a tablet using Android 3.1. I am in school and I write a lot of applications using Java. I need to be able to write code using a tablet running Android 3.1 Honeycomb.
Also if I can do this what IDE can I use?
NOTE: I am not trying to write Android applications in Java. I am trying to write applications in Java (for regular PC) using a IDE from a tablet with Android 3.1 honeycomb.
Basically I want to:
*
*Install Java JDK on Toshiba Thrive
*Install IDE on Toshiba Thrive (such as eclipse, jgrasp, netbeans)
*Run IDE and write code in Java
*Save code to flashdrive
*Use/edit code on my PC
A: Go to Google Play and download AIDE although it is for designing Android Apps on cell phone.
It works on my android tablet and takes Java. With a few tweaks I bet you could make it compile and run pure java. Please cheak it out and let me know. I am working on it right now.
I need portable java development on the go anywhere!!
A: You can't do that on a normal Android tablet, the best you can hope is to use Remote Desktop/TeamViewer/VNC to remotely use a normal PC an do your actual development there. One option you have is to root the tablet and install Ubuntu side-by-side the Android environment, but I'm doubtful that the OpenJDK will be up to the task.
On the third hand, a tablet is a device that is very hostile to text entry, and you wnt to perform an activity that is very text-heavy. Are you on the right track? (not to menttion the question on how to perforn shift-ctrl-f on a tablet)
A: With the latest Asus tablet that runs Android on a quad-core chip, I see this as a possibility in the near future if not now. Essentially, it would be like a merge of iPad and MacBook.
And no AWT/SWing/etc is not a problem for me, since I will be doing server-side development (using Eclipse/tomcat).
Now the question:
How hard is it to port JDK onto Android?
Allen S.
A: You can use DroidDevelop
https://market.android.com/details?id=com.assoft.DroidDevelop
http://en.assoft.ru/droiddevelop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handling multiple grids with heavy data I am developing a website using asp.net 4.0(Browser IE8).My page contains a tabcontainer with 5 tabs .Each tab contains a grid without paging i.e each grid can contain 250 to 300 records. I am loading tabs on demand but once all tabs are loaded. My UI becomes too slow. How do i manage to make my UI faster & smoother ?
A: What do you mean by loading tabs "On Demand"? If it just means that you populate grid data when tab is clicked then it explains your problem. Essentially, ASP.NET data bound control stores their data into view-state, so as you go on loading the grids, your view-state keep increasing and essentially, you have a large page size making page retrieval and post-back slower.
Quick solution will be to disable view-state for all grids and always bind the grid on current tab from actual data store (you may cache the data on server side in session or ASP.NET cache for improved performance). This will make sure that only one grid is populated at a time and there is no-burden on the view-state.
Alternate techniques will involve loading contents for only current tab but it involve arranging contents into user control etc and a bit tricky to get working in post-back scenarios etc.
Relatively simple approach is to use your own control/html to render tabs and each tab is a GET request to a separate page. For example, if you have four tabs then you will have one master page providing common layout including tabs and 4 content pages representing each tab.
If you want to avoid page refresh on tab switch then you may try loading content page using AJAX request.
A: I'm not certain if this will help your issue or not, but one option is to hide the grid contents (style.display='none') when the user switches to another tab. It's worth a shot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sass --watch not compiling I am running Sass from terminal like this:
sass --watch --style expanded css:css/compiled
I have these files:
*
*compiled.scss
*_style.scss
*_forms.scss
compiled.scss @imports the other two files
When I modify _style.scss and save it I get
Change detected to [path to file]
overwrite css/compiled/main.css
but modifying _forms.scss I get
Change detected to [path to file]
But no overwrite?
A: You have not @imported '_forms.scss' properly into 'compiled.scss'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Pass Sqlite Values in a view How to pass sqlite data in a view .I want to display sqlite data in a view controller,with paging enabled.I have a big amount of data in database,that i want to display in many pages.How to do this?
Thanks in advance.
A: You should probably use Table Views, should have googled about this topic, anyways these 2 are pretty useful
http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/
http://blog.objectgraph.com/index.php/2010/04/08/how-to-use-sqlite-with-uitableview-in-iphone-sdk/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript: Most effecient way to define variable to a function call, or if null to a variable? Using ternary operator requires two calls to the function.
var colour = (tryAdventurousColour() != null) ? tryAdventurousColour() : 'black';
Possible to do it in 1 line?
EDIT: Fixed syntax
EDIT: Like this but better
var colour = ( (colour = tryAdventurousColour() ) != null ) ? colour : 'black';
A: Use JavaScript's logical or operator:
var colour = tryAdventurousColour() || 'black';
Your function tryAdventurousColour() will be executed once. If it returns a "truthy" value then that colour variable will be assigned to that value, otherwise colour will be 'black'. This fits your scenario perfectly since null is a "falsy" value.
In more general terms, the expression a || b returns a if it can be converted to true (is "truthy"), otherwise it returns b. Note that non-zero numbers, non-empty strings and objects will all be converted to true. null, undefined, 0, "" will all be converted to false. (I'm sure somebody will correct me if I've left something out.)
A: var colour = (tryAdventurousColour()) ? tryAdventurousColour() : 'black';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails content_for overwrites rather than appends I load my stylesheets and js files in <head> for performance reasons.
My site has multiple components and each template wants to its own extra header files in inside <% yield(:head).
I tested <% content_for :head do %> .. but then I realize it actually overwrites rather than append to a particular section.
What do you guys use?
A: content_for actually appends by default. From the documentation, if you were to do...
<% content_for :navigation do %>
<li><%= link_to 'Home', :action => 'index' %></li>
<% end %>
<%# Add some other content, or use a different template: %>
<% content_for :navigation do %>
<li><%= link_to 'Login', :action => 'login' %></li>
<% end %>
If you used...
<ul><%= content_for :navigation %></ul>
It would output...
<ul>
<li><a href="/">Home</a></li>
<li><a href="/login">Login</a></li>
</ul>
Just tested this locally on a rails 3.1.0 app to make sure this is still the case and it does this fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I resolve a ZenTest-4.6.2 successfully installed & missing gem? I'm loosely going through http://ruby.railstutorial.org/chapters/ and am at the point of preparing to test http://ruby.railstutorial.org/chapters/static-pages#sec:testing_tools . I listed the autotest related gems in my Gemfile and ran bundle install without incident, but when I tried to start the server I got the error Could not find ZenTest-4.6.2 in any of the sources. So I added ZenTest 4.6.2 to my Gemfile and reran bundle install.
Now according to my bash terminal, my bundle is complete including Using ZenTest (4.6.2), but when I try to start my server I'm still getting the error Could not find ZenTest-4.6.2 in any of the sources. So is it installed or is it not installed? And how should I resolve this conflict?
A: It should just say: gem "ZenTest" in your gem file, not the version # as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Scholar with Matlab I would like to fetch some data from Google Scholar automatically via a matlab script. I am mostly interested in data like Google Scholar's Bibtex entries and the forward citation feature. However, it seems that there is no API for Google Scholar, is there a way to automatically fetch bibliographic data from Google Scholar using Matlab? Are there some tools or code already available for this?
A: A word of caution I found while working further on this project.
There is a reason why Google Scholar does not have an API. Using bots to collect from Google Scholar is against the EULA. The basic idea is that any program that tries to interface with Google Scholar cannot do so in a qualitatively different way than an end user. In other words, you can automatically fetch large amounts of data. Although the script in @JustinPeel's answer do not necessarily violate the terms, putting it in a massive loop, would.
Some specific points from this EULA:
You shall not, and shall not allow any third party to: ...
(i) directly or indirectly generate queries, or impressions of or clicks on Results, through any automated, deceptive, fraudulent or other invalid means (including, but not limited to, click spam, robots, macro programs, and Internet agents);
...
(l) "crawl", "spider", index or in any non-transitory manner store or cache information obtained from the Service (including, but not limited to, Results, or any part, copy or derivative thereof);
If you look at the Google Scholar robots.txt then you can also see that no bots of any kind are allowed.
I have heard from some colleagues that you will get in trouble if you try to circumvent this policy, which can result in your lab losing access to Google Scholar.
A: If you really want to use Matlab for this (which I don't really advise), then you can look at some various web scraping examples and there is this code that actually already gets some info from Google Scholar. Basically, just good 'matlab web scraping' and off you go.
I personally would recommend using Python for this because Python is better for general programming IMHO. For instance, this guy has already done a similar thing to what you want with Python. However, if you know Matlab and don't have any interest/time for Python then follow the links in the first paragraph.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Querying large dataset for statistics in SQL Server? Say I have a sample for which 5 million data objects are stored as rows in SQL Server. If I need to run some stats on the data, would it be better to have a table for each sample, or one giant table, where I would select by sample id and then run the stats?
There may eventually be hundreds or even thousands of samples- which seems like one massive table.
But I'm not a SQL Server expert so I can't say whether one would be faster than the other...
Or maybe a better way to deal with such a large data set? I was hoping to use SQL CLR with C# to do my heavy lifting...
A: If you need to deal with such a large dataset, my gut feeling tells me T-SQL and working in sets will be significantly faster than anything you can do in SQL-CLR and a RBAR (row-by-agonizing-row) approach... dealing with large sets of data, summing up and selecting, that's what T-SQL is always been made for and what it's good at.
5 million rows isn't really an awful lot of data - it's a nice size dataset. But if you have the proper indices in place, e.g. on the columns you use in your JOIN conditions, in your WHERE clause and your ORDER BY clause, you should be just fine.
If you need more and more detailed advice - try to post your table structure, explain how you will query that table (what criteria you use for WHERE and ORDER BY) and we should be able to provide some more feedback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Opening another file from Python and terminate script I am trying to figure out the best solution to accomplish this. Basically, I want to open another program from Python (doesn't matter, could be an image, executable, etc). I have tried os.system and subprocess.call however both will not terminate the script after, and will instead wait for a return. I have looked at os.execl, and it seems to close to what I need, but I am not sure if I understand the arg's as I always get exec format errors and invalid arguments. I am not even sure if this is the proper function for what I need. Any help would be appreciated.
I have tried using subprocess.call and subprocess.Popen using something similar to this:
import subprocess
subprocess.Popen("B:\test.txt")
and it ends up with the following error:
WindowsError: [Error 5] Access is denied.
A: Use subprocess.Popen[docs]
Just don't call communicate on the resulting object.
A: os.execlp("start", r"B:\test.txt")
(That's for Windows. On a Unix system running X11, you'd do this:)
os.execlp("xdg-open", r"B:\test.txt")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Null pointer exception with static Map It's 5am and I'm a bit asleep, so that may be it (also I'm relatively new with Java). But I don't see why this code generates Null Exception with this code. The map should be initialized by then, shouldn't it?
private static final Map<String, Integer> CONDS_MAP =
Collections.unmodifiableMap
(
new HashMap<String, Integer>()
{{
put("null", 0);
put("false", 0);
put("true", 1);
put("numElems.lt", 2);
put("NELT", 2);
put("numElems.gt", 3);
put("NEGT", 3);
}}
);
private int getCodeInt(Object code)
{
if (code.getClass() == String.class)
{
return CONDS_MAP.get((String)code); // Null Exception here
}
else
// (... etc etc)
}
Thanks! and sorry it it is too trivial...
A: It is most likely caused by trying to unbox the null returned from a non-existing key.
return CONDS_MAP.get((String)code);
is the same as
return CONDS_MAP.get(code).intValue();
That last intValue will fail if the Map returns null.
A: Yes it has been initialized by then, the nullpointerexception is probably caused by a null key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Devise + omniauth routing problem on Heroku I've been pulling my hair for hours on this one... I have a Devise and omniauth setup that allows users to log in with their Facebook accounts. I am using the following gem versions:
Installing devise (1.4.7)
Installing oauth2 (0.4.1)
Installing oa-oauth (0.2.6)
Installing omniauth (0.2.6)
among others and have the app id and secret in my Devise initializer:
config.omniauth :facebook, 'app_id', 'app_secret',
{:scope => 'email, offline_access', :client_options => {:ssl => {:verify => false}}}
Though I also tried this with no luck:
config.omniauth :facebook, 'app_id', 'app_secret',
# {:scope => 'email, offline_access', :client_options => {:ssl => {:ca_file => '/usr/lib/ssl/certs/ca-certificates.crt'}}}
I have the :omniauthable directive in my user model, and I define my own callback controller in the routes file:
devise_for :users, :controllers => { :omniauth_callbacks => 'user/authentications', :registrations => 'registrations' }
root :to => 'pages#home'
And I also tried adding this to the routes file with no luck:
get '/users/auth/:provider' => 'user/authentications#passthru'
Here is my authentications controller:
class AuthenticationsController < Devise::OmniauthCallbacksController
def index
@authentications = current_user.authentications if current_user
end
def facebook
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
def passthru
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
def destroy
@authentication = current_user.authentications.find(params[:id])
@authentication.destroy
flash[:notice] = "Successfully destroyed authentication."
redirect_to authentications_url
end
end
And my Facebook log in link:
<%= link_to image_tag('/assets/facebook_32.png'), omniauth_authorize_path(resource_name, :facebook)%>
This all works great locally, but if I try to log in with my Facebook account when my app is deployed to Heroku, I get the following in my log and I'm directed to the 404 page:
2011-09-23T03:26:31+00:00 app[web.1]: ActionController::RoutingError (uninitiali
zed constant User::AuthenticationsController):
I tried resetting my database, but that didn't help either.
Here are my routes from Heroku:
new_user_session GET /users/sign_in(.:format) {:action=
>"new", :controller=>"devise/sessions"}
user_session POST /users/sign_in(.:format) {:action=
>"create", :controller=>"devise/sessions"}
destroy_user_session GET /users/sign_out(.:format) {:action=
>"destroy", :controller=>"devise/sessions"}
user_omniauth_callback /users/auth/:action/callback(.:format) {:action=
>/facebook/, :controller=>"user/authentications"}
user_password POST /users/password(.:format) {:action=
>"create", :controller=>"devise/passwords"}
new_user_password GET /users/password/new(.:format) {:action=
>"new", :controller=>"devise/passwords"}
edit_user_password GET /users/password/edit(.:format) {:action=
>"edit", :controller=>"devise/passwords"}
PUT /users/password(.:format) {:action=
>"update", :controller=>"devise/passwords"}
cancel_user_registration GET /users/cancel(.:format) {:action=
>"cancel", :controller=>"registrations"}
user_registration POST /users(.:format) {:action=
>"create", :controller=>"registrations"}
new_user_registration GET /users/sign_up(.:format) {:action=
>"new", :controller=>"registrations"}
edit_user_registration GET /users/edit(.:format) {:action=
>"edit", :controller=>"registrations"}
PUT /users(.:format) {:action=
>"update", :controller=>"registrations"}
DELETE /users(.:format) {:action=
>"destroy", :controller=>"registrations"}
root / {:control
ler=>"pages", :action=>"home"}
Any help is greatly appreciated. Please let me know if you need any other info. I know it's something small, but I feel like I've tried a thousand different things and nothing has worked.
A: I think, your authenicatine line should be using find_or_create.
authentication = Authentication.find_or_create_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
A: I ended up changing
devise_for :users, :controllers => { :omniauth_callbacks => 'user/authentications', :registrations => 'registrations' }
to
devise_for :users, :controllers => { :omniauth_callbacks => 'authentications', :registrations => 'registrations' }
and it started working both locally and on Heroku.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how could i change these code to MVC3 Razor how could i change these code to MVC3 Razor,it script code.
these code i get form http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-5-master-page-templates.html
it's MVC2 Template and i want change it to Razor.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script runat="server">
private object ModelValue {
get {
if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) {
return String.Format(
System.Globalization.CultureInfo.CurrentCulture,
"{0:0.00}", ViewData.ModelMetadata.Model
);
}
return ViewData.TemplateInfo.FormattedModelValue;
}
}
</script>
<%= Html.TextBox("", ModelValue, new { @class = "text-box single-line" }) %>
i changed to Razor as bellow but it can't work:
@{
private object FormattedValue
{
get
{
if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model)
{
return String.Format(System.Globalization.CultureInfo.CurrentCulture,"{0:0.00}",ViewData.ModelMetadata.Model);
}
return ViewData.TemplateInfo.FormattedModelValue;
}
}
}
@Html.Encode(FormattedValue)
A: Create your own function:
http://weblogs.asp.net/hajan/archive/2011/02/05/functions-inside-page-using-razor-view-engine-asp-net-mvc.aspx
just call the function passing it the value in, and return it however you want to format it.
@functions{
public MvcString FormatValue(object valuetoFormat)
{
...logic here ...
return ....
}
}
Calling it is roughly:
@Html.TextBox("", FormatValue(ModelValue), new { @class = "text-box single-line" })
A: I don't think you can specify adhoc properties in Razor. You can, however, create variables.
@{
object FormattedValue;
if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model)
{
FormattedValue = String.Format(System.Globalization.CultureInfo.CurrentCulture,"{0:0.00}",ViewData.ModelMetadata.Model);
}else{
FormattedValue = ViewData.TemplateInfo.FormattedModelValue;
}
}
Hope this works for you?
A: If you use the @{ } tag, the code is inserted inside the method used to generate the output.
You should use @functions { } to define elements you want on class (=page) level.
This would make your code look like:
Read SLaks blog for more information.
@functions {
private object FormattedValue
{
get
{
if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model)
{
return String.Format(System.Globalization.CultureInfo.CurrentCulture,"{0:0.00}",ViewData.ModelMetadata.Model);
}
return ViewData.TemplateInfo.FormattedModelValue;
}
}
}
@Html.Encode(FormattedValue)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expand functionality for rows in Richfaces DataTable I am looking for a way to implement a expand functionality to the rows of a Richfaces DataTable. The user would click a "+" link located in the first column (of each row) of the Datatable and the row would "expand" (meaning new text would be shown between the current row and the next).
I have that working, the only problem is that all the information in the expanded view is displayed in the first column section of that row. What I am trying to do is to show the "expanded" text in the whole row (as if the "expanded" text row is not divided by the columns).
Any suggestions? I'm a bit new at jsf/richfaces, so any sample code would be appreciated.
A: You can do this with the breakBefore attribute on the rich:column component. There is an example of its use on the RF demo page.
It would work for you if you had the last column define the breakBefore attribute. An example:
<rich:dataTable id="mytbl" value="#{mybean.mydata}" var="row">
<rich:column>
<a4j:commandLink reRender="mytbl">
<h:graphicImage value="#{row.toggleImage}"></h:graphicImage>
<a4j:actionparam name="shown" value="#{not row.expand}" assignTo="#{row.expand}"/>
</a4j:commandLink>
</rich:column>
<rich:column>
<f:facet name="header">col 2</f:facet>
<h:outputText value="#{row.col2}"/>
</rich:column>
<rich:column breakBefore="true">
spans all the other columns
</rich:column>
</rich:dataTable>
A: One way for this is you can use the JQuery feature.
Demo link http://jsfiddle.net/BU28E/1/ .
One extra overhead here is you need to check how the rich:dataTable renders as Html and provide the DOM model for jQuery. It is bit tricky to have such feature in richfaces and it needs some complex workarounds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIView & Image Clipping in iPhone? Let said I have a image which the circle in the middle is transparent and I use the drawRect function to draw sqaure like the second image below.
Then what I want to do is to get the alpha layer of the first image, the circle as a path, then apply on the square i draw and clip it and draw like the final image, just want it to draw on the circle path.
Thank in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I access the row in a RowCommand event I am trying to find a DropDown element in the GridView_RowCommand but it says that GridViewCommandEventArgs does not contain a definituon for 'Row'. I need to do this in this event because i am evaluating a GridView Command. See failing code below
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Add")
{
DropDownList Myddl = null;
ClientClass client = new ClientClass();
Myddl = e.Row.FindControl("ddlClients") as DropDownList;
if (Myddl != null)
{
updated = client.InsertUpdateClient(ClientID,
int.Parse(e.CommandArgument.ToString()), departmentID);
}
else
{
Labels.Text = "There was an error updating this client";
}
}
}
A: Something like this:
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
This is assuming what's firing off the RowCommand is a LinkButton. Change that according.
A: In addition to the @Stephen,
if (e.CommandName == "Add")
{
DropDownList Myddl = null;
ClientClass client = new ClientClass();
//Use this if button type is linkbutton
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
//Use this if button type is Button
//GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
Myddl = row.FindControl("ddlClients") as DropDownList;
if (Myddl != null)
{
updated = client.InsertUpdateClient(ClientID,
int.Parse(e.CommandArgument.ToString()), departmentID);
}
else
{
Labels.Text = "There was an error updating this client";
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: real time data updating from form I have a dynamic form that users enter receipt data. I'm trying to clone what they're inputting on a separate div that is designed to look like the receipt they're inputting. I want to display the values of the text and select elements into that separate div.
I was trying to do this in jquery. Does anyone have an example?
edit
The issue is that I don't know how to fetch the div id because it's being generated dynamically.
A: I would suggest using a keyup event. Assuming you set up your input field and divs like so:
<input type="text" id="receipt_no" />
<p>Preview:</p>
<div id="preview"></div>
You could do the following in jQuery:
$('#receipt_no').keyup(functon () {
var preview_text = $(this).val();
$('#preview').html(preview_text);
});
You can make it more complex later on by adding a common function for the receipt_no keyup and other form elements' change events (e.g. a dropdown). You just have to construct the preview_text using all the elements you need for the preview then.
A: Here is a simple sample:
HTML:
<div id="inputDiv">
<textarea></textarea>
<div>
<div id="previewDiv"><div>
js:
$(function(){
$("#inputDiv textarea").keydown(function(){
$("#previewDiv").text($(this).value());
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7523996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Learning Core Data for iOS Development I have been trying to learn iPhone development for a while now. I am now interested in looking at building a iPhone app using Core Data. I built a app using sql lite. The app I created using sql lite basically asks the user for two fields of information "firstname" and "lastname" and then it goes into a UI Table View. The user can then select their name in that list and then it goes to a new view with a label with there name. Really basic app. Im just trying to grasp the ideas on how to make a iOS app.
Any Suggestions on what tutorials I could use to learn core data and then display that information in a new view?
A: Good you decided to learn core data, a powerful alternative to sqlite.. See this Ray Wenderlich tutorial to get first grasp of core data. Then read a descriptive tutorial about core data here..To cap it off, you should read this..
A: Core Data is a great technology, and I use it, but beware that it's pretty complicated so don't get discouraged... An alternative and additional tool you may want to investigate is NSUserDefaults which fills a gap between CD and SQL imho. (Persistent dictionary, basically)
This answer is more of a comment but I can't link as nicely there
A: For core Data I suggest you to refer HeadFirst iPhoneDevelopment Chapter 8.
I think it helps you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can you sort tabs in Visual Studio 2008 by file type? I have been trying (without much luck) to write a macro for Visual Studio 2008 that will sort opened .cpp and .h files into two tab groups, placing headers on the left tab group and .cpp files on the right. I would love to have this feature because of the amount of time I spend moving my tabs around so that I can see both parts of the class that I am working on. I know that there is a non-free add-on for visual studio that allows tab managing, but it conflicts with an add-on that I need to use for work, making a macro my best option so far.
I am sure that this could be applied to other layouts and sorting needs as well if I can get it working. My thinking was to make the sorting happen automatically for me each time I open a document window, so I created a visual basic macro in the environment events section of the Visual Studio Macro IDE. Below is the code that I have so far:
Public Sub keepHeaderAndCxxInDifferentTabs() Handles WindowEvents.WindowCreated
Dim openedFile As String
openedFile = ActiveWindow.Document.FullName
If openedFile.Contains(".h") Then
' if the file being opened is a header file make sure it appears on the left
If DTE.ActiveDocument.ActiveWindow.Left > 600 Then
DTE.ExecuteCommand("Window.MovetoNextTabGroup")
End If
ElseIf openedFile.Contains(".cpp") Then
' if the file being opened is a cpp file make sure it appears on the right
If DTE.ActiveDocument.ActiveWindow.Left < 250 Then
DTE.ExecuteCommand("Window.MovetoNextTabGroup")
End If
Else
' if the file being opened is anything else make sure it appears on the right
If DTE.ActiveDocument.ActiveWindow.Left < 250 Then
DTE.ExecuteCommand("Window.MovetoNextTabGroup")
End If
End If
End Sub
Sadly this macro currently does not do anything. My best guess was that I could use the 'Left' property of the active window to figure out which tab group the new window appeared in and then move the window to the next tab group if it is not where I want it to be. I have tried a range of different values for the 'Left' property but so far none of my tabs move.
Does anyone know what I did wrong or have any suggestions? Thank you in advance for your time.
A: I found a way to do what I wanted using the function below. As long as I have my two vertical tabs setup when I run the macro it puts all headers in the left tab group and all other files in the right tab group. This can be further extended so that when I open any files using any other macros I write it sorts them as well by making a call to it after the macro has run. Sadly this does not work automatically, I am having problems getting it to actually perform the sorting whenever a specific event is triggered (using the environment events section).
'=====================================================================
' Sorts all opened documents putting headers into the left tab group
' and everything else into the right tab group
'=====================================================================
Public Sub SortFilesInTabs()
For i = 1 To DTE.Windows.Count Step 1
If DTE.Windows.Item(i).Document IsNot Nothing Then
If DTE.Windows.Item(i).Document.FullName.Contains(".h") Then
' if the file is a header file make sure it appears on the left
If DTE.Windows.Item(i).Document.ActiveWindow.Left > 600 Then
WriteOutput("moved file " & DTE.Windows.Item(i).Document.FullName & " to left")
DTE.Windows.Item(i).Document.Activate()
DTE.ExecuteCommand("Window.MovetoPreviousTabGroup")
End If
ElseIf DTE.Windows.Item(i).Document.FullName.Contains(".cpp") Then
' if the file is a cpp file make sure it appears on the right
If DTE.Windows.Item(i).Document.ActiveWindow.Left < 250 Then
WriteOutput("moved file " & DTE.Windows.Item(i).Document.FullName & " to right")
DTE.Windows.Item(i).Document.Activate()
DTE.ExecuteCommand("Window.MovetoNextTabGroup")
End If
ElseIf DTE.Windows.Item(i).Document.FullName.Length > 0 Then
' if the file is any other valid document then make sure it appears on the right
If DTE.Windows.Item(i).Document.ActiveWindow.Left < 250 Then
WriteOutput("moved file " & DTE.Windows.Item(i).Document.FullName & " to right")
DTE.Windows.Item(i).Document.Activate()
DTE.ExecuteCommand("Window.MovetoNextTabGroup")
End If
End If
End If
Next i
End Sub
If anyone can improve this further pl
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting a C# (Windows application) into commandline application? I am looking to convert a C# (Windows platform application) into a commandline version.
The scenario is: I have implemented a C# (Windows application) in VS 2010. The output of this application is to generate a txt (log) file (in simple explanation).
Now the case is, there is one other application which need to use my this C# application, by calling my C# application from the command line at the run time.
My question is, how is it possible to convert an already existing C# application into commandline application, so that this C# application can be called from the calling (other) program? There is one input parameter which need to be passed on the commandline to my C# application. And then this C# application will process the data according to input parameter and then generate the output log(txt) file.
Added explanation
I am really impressed by the solutions here. Just a bit more expertise is required from readers. I want one application only to work as both commandline application as well Windows-application (forget to mention it before, sorry!), depending on the number of input parameter pass to the application. From this point of view, I have two options to implement it,
1) Make separate functions for both applications (commandline and windows-forms). Call them according to the input parameter pass. In each function implement the complete functionality of each application without disturbing (or going into the code of other application). Also I will be able to re-use 2 main functions, already built in windows-form application into my commandline application after some editing.
Disadvantage: This will make the code size nearly 50% more than case 2.
2) The second idea is same as describe by one of the expert here, to use the same application/functions for commandline as that of already built windows-form application. The only way to distinguish is to look at the input parameter pass, and decide accordingly whether to show the GUI interface or just use the commandline input (and do processing).
Disadvantage: This case will make the code bit messy and difficult to maintain/implement due to extra adding of check for number of input parameter decisions.
Which strategy should I follow for implementation?
A: Sure - just:
*
*Create a new VS2010 command-line project
*You'll now have a "main ()" (or, in MS-Land, "_tmain()") function instead of a root class.
*Cut and paste the relevant code into "main()" (or into a function called by main (), or into a class created from main() - your choice).
*Do a search-and-destroy mission to find anyplace where you're doing GUI input, and substitute command line parameters instead.
*Parse your command line.
Voila! Done!
A: You want to get value from command line is not a good reason to convert winform app to console app. You may use,
string[] args = Environment.GetCommandLineArgs();
However you can change application type by opening project properties (right click on project name) and change the Output type.
A: You don't have to convert it. Your application can stay as a Windows application. You simply need to handle command line arguments.
To get the command line arguments from ANYWHERE in the application, just use Environment.GetCommandLineArgs();
A: Just don't show the GUI if you get paramater passed in, as when called from the other program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need some way to store functions in a list, and then call them This list, has to hold functions, they might be from different namespaces and even methods of instanced classes.
This list will then be iterated and all the functions and methods called. It would be nice if they could contain arguments also.
I was thinking on using a std::vector, but I suspect that I am far from correct in that guess.
What approach do you recommend me? All help is welcome.
A: You could use std::function and std::bind if your compiler already supports it.
#include <functional>
#include <vector>
void x(int) {}
void y() {}
class Z {
public:
void z() {}
};
int main(int argc, char *argv[])
{
typedef std::function<void ()> VoidFunc;
typedef std::vector<VoidFunc> FuncVector;
FuncVector functions;
functions.push_back(std::bind(&x, 1));
functions.push_back(&y);
Z z1;
functions.push_back(std::bind(&Z::z, z1));
for(FuncVector::iterator i = functions.begin(); i != functions.end(); i++) {
(*i)();
}
return 0;
}
A: If you don't want to use an existing solution such as boost::function, you will need to create a base class that represents a function, and then derived classes that wrap various sources of functions. For example:
#include <iostream>
#include <list>
using std::cout;
using std::list;
struct Function {
virtual ~Function() { }
virtual void operator()() = 0;
};
struct PlainFunction : Function {
PlainFunction(void (*function_ptr_arg)()) : function_ptr(function_ptr_arg) { }
virtual void operator()() { (*function_ptr)(); }
void (*function_ptr)();
};
template <typename T>
struct MethodFunction : Function {
MethodFunction(T &obj_arg,void (T::*method_ptr_arg)())
: obj(obj_arg), method_ptr(method_ptr_arg)
{
}
virtual void operator()() { (obj.*method_ptr)(); }
T &obj;
void (T::*method_ptr)();
};
void f()
{
cout << "Called f()\n";
}
struct A {
void f() { cout << "Called A::f()\n"; }
};
int main(int argc,char **argv)
{
list<Function *> functions;
functions.push_back(new PlainFunction(f));
A a;
functions.push_back(new MethodFunction<A>(a,&A::f));
list<Function *>::iterator i = functions.begin();
for (;i!=functions.end();++i) {
(*(*i))();
}
while (!functions.empty()) {
Function *last_ptr = functions.back();
functions.pop_back();
delete last_ptr;
}
}
A: Have all of your functions implement the Command Pattern.
Your list becomes a
std::list<Command>
As you iterate over the list, you invoke the Execute() method of each list item.
For example, say you have a simple Command interface called Commander:
class Commander
{
public:
virtual ~Commander;
virtual void Execute();//= 0;
};
And you have three objects that you want to put in your list: A Greyhound, a Gyrefalcon, and a Girlfriend. Wrap each in a Commander object that calls the object's function of interest. The Greyhound runs:
class RunGreyhound: public Commander
{
public:
void Execute()
{
mGreyhound->Run();
}
private:
Greyhound* mGreyhound;
};
The Gyrefalcon flies:
class RunGyrefalcon: public Commander
{
public:
void Execute()
{
mGyrefalcon->Fly( mGyrefalcon->Prey() );
}
private:
Gyrefalcon* mGyrefalcon;
};
And the Girlfriend squawks:
class RunGirlfriend: public Commander
{
public:
void Execute()
{
mGirlfriend->Squawk( mGirlfriend->MyJunk(), mGirlfriend->Mytrun() );
}
private:
Girlfriend* mGirlfriend;
};
Stuff the Commander objects in your list. Now you can iterate over them and invoke each element's Execute() method:
std::list<Commander> cmdlist;
RunGreyhound dog;
cmdlist.push_back( dog );
RunGyrefalcon bird;
cmdlist.push_back( bird );
RunGirlfriend gurl;
cmdlist.push_back( gurl );
for ( std::list<Commander>::iterator rit = cmdlist.begin(); rit != cmdlist.end(); ++rit )
{
rit->Execute();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Getting started with tabs in Rails app I was researching here on SO how to implement a tabbed interface in my Rails app. For example, I like how Ryan Bates uses it in his Railscast overview page.
I want to mimic that in my Rails app so that a User's profile has a navigation in it with two or three links. Clicking either link loads information using AJAX (I'm guessing). Then the URL shows /profiles/1/view?info or /profiles/1/view?otherdata
I came across this question, with the following solution:
I would make the contents of each tab be called in by a separate ajax request. This would give you the following benefits
*
*Now each tab can easily be a different view/controller
*You only need to load the contents for a tab when it is used; you won't be processing code/downloading html for tabs that the user doesn't use.
The problem is I'm new to Rails and have no idea how to do this. Can anyone point me to some resources that help explain how to set this up? I'd be tabbing between profile data and messages to the user.
Any help would be much appreciated.
A: As you're new to Rails I'd suggest breaking up your goal into 2 sections: first, get the tabs working with simple content, then add the AJAX.
Step 1 - Getting the tabs working
Have a look at the JQuery UI tabs demos: http://jqueryui.com/demos/tabs/
The code looks something like this:
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque.</p>
</div>
</div>
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
Step 2 - Getting the AJAX working
Check out: http://jqueryui.com/demos/tabs/#ajax
A: Even it may be hip to use AJAX today, why not do the Simplest Thing That Could Possibly Work? If have done in the past something like the following:
Adding tabs to the UI by code like the following (notation is HAML, sorry for that). As a result, you get a list of links that link to the controllers index action. This code is part of the file layouts/_header.html.haml.
%ul.sideul
- ["page", "notice", "contact"].each do |thing|
- curr = controller.controller_name.singularize == thing
- cl = curr ? 'current' : 'normal'
%li.normal= link_to(thing.humanize, {:controller => controller, :action => "index"}, {:class => cl })
Add then the CSS to your application that this is shown as tabs. There you will need the information if a li is current or normal.
Every time you click then on the tab, the index action of that controller is called, and after that, the index page is shown.
Your file layouts/application.html.haml should have the following content (at least). I have skipped what is not necessary for the example. The template is taken from html5-boilerplate for Rails.
%body{ :class => "#{controller.controller_name}" }
#columns
%header#side
= render "layouts/header"
#main{ :role => 'main' }
%h1= yield(:title)
= render "layouts/flashes"
= yield
= render "layouts/javascripts"
The relevant parts for this solution is:
*
*= render "layouts/header": Renders the list of tabs inside of #columns > header#side
*= yield: Renders whatever is in the view for the action of the controller. In our case first the index page, may be later the edit or show page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: windows authentication using ajax I want to create an internal website, preferably in asp.net, that uses ajax calls for performing all operations.
The requirements are that the site should use windows domain authentication (to act as a single-sign-on solution) for verifying which user is sending the request. What is the best way to accomplish this in a secure fashion? I am open to a solution using https or cookies or anything else feasible.
( I would prefer regular ajax using jquery since I havent used asp.net ajax but if that solves some issues more easily, then let me know)
The current way I am doing this (not through ajax) is disabling anonymous access in iis and then getting the logged in username from asp.net, but this requires the site to perform postbacks, etc which i want to avoid.
A: An Ajax request is not different from any other HTTP request when it comes to authentication.
Your user will most likely be authenticated when they access the index of your site. Any subsequent request, Ajax or not, will be authenticated. There is nothing special to do, and your jQuery code will look just like what it normally looks.
A: You should absolutely:
*
*Use an https connection to transmit username and password
*Authenticate on the server side, with asp.net
*Leverage the asp.net session to as great an extent as possible.
If you're not familiar with ASP.Net ... well, consider this a good opportunity to learn :)
jQuery is great, but it's just a tool. In this case, it's probably not the best tool for this particular job.
IMHO...
A: Windows authentication is checked on every request.
How this is checked depends which authentication method /provider is enabled and supported on the server (kerberos, ntlm, custom, etc)
Credentials are automatically sent over under certain rules (I believe intranet trusted for IE, I dont recall what else outside of that).
Firefox will prompt you if I recall every time.
Check out:
http://www.winserverkb.com/Uwe/Forum.aspx/iis-security/5707/IIS-6-0-Windows-Authentication-401-Every-Request
The important thing to note is the browser and server will take care of this and prompt the user when necessary.
Also to note is I highly highly suggest ALL traffic is under an SSL connection at this point to prevent sniffing and credential stealing/token stealking (such as is extremely easy for basic auth)
You can enable this protection inside of IIS and use all file permissions or you can control this in your web applications web.config by enabling windows authentication. How this is accomplished though depends on your server config (kerberos support, etc)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to integrate barcode scanner directly on my app? Does anyone here knows how to to integrate barcode scanning directly into an application without having the separate ZXing application installed?
A: The complete source code to Barcode Scanner is here: http://code.google.com/p/zxing
As a developer of the library, I can tell you that two things happen in 95% of cases where someone tries to integrate our source code into their app:
*
*They find it's quite a bit of work to adapt the code and integrate and maintain the scanning in their own app, and they use the Intent API
*They copy and paste our code and try to make "their own" app this way
I can tell you we do not want developers to copy and paste our source code. And unless you're an experienced Android dev, you will have trouble re-inventing a scanning app on your own
Bottom line: save yourself the trouble and integrate via Intent: http://code.google.com/p/zxing/wiki/ScanningViaIntent
A: try to use the Google Chart tool api its very simple, i have a function that i wrote a while back:
function get_QR_code($content = null,$size = null,$ImgTag = true){
if ($size == null){
$size = '150x150';
}
if ($ImgTag){
echo '<img src="http://chart.apis.google.com/chart?cht=qr&chs='.$size.'&choe=UTF-8&chld=H&chl='.$content .'">';
}else{
return 'http://chart.apis.google.com/chart?cht=qr&chs='.$size.'&choe=UTF-8&chld=H&chl='.$content;
}
}
<?php get_QR_code('Hello form Google API'); ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Drawing/coloring application - flood fill algorithm/clipping region I have to develop a coloring application. Basically the user is presented with an image. An outline of a character maybe and the user can fill it using different colors. I've looked at a few options but I can't seem to find a good one.
Could someone tell me how to fill the bitmap image.
Is there any sample code I can use? or an open source project?
It has to be done in
A: Look for some good Java Image processing Libraries like the ones listed here https://stackoverflow.com/questions/4078479/what-android-3rd-party-libraries-are-there . Its not an Android question but more about Image processing
A: The Wikipedia entry on Flood Fill has the classical algorithm in pseudo-code, a few variants and optimizations and links to source code in several languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change NSScrollView font from XCode 4 Interface Builder? Does anyone know how to change font in NSScrollView using XCode 4 Interface Builder?
Thanks for the help.
PS: This is for Mac OS development. The font panel for iPhone ScrollView can be seen in Attributes Inspector (as pointed by Khrisna below), but not for MacOS development.
A: NSScrollView class is composed of NSClipView and NSScroller classes. I guess we NSScrollView does not have a property through which we can change the FONT of the text to be written.
We change the font for the text in either UITextField or UILabel. So, when use use these in the ScrollView, we can change their font as:
1. PRogrammatically:
myTextFied.font = [UIFont fontWithName:<#(NSString *)#> size:<#(CGFloat)#>];
or
myTextFied.font = [UIFont fontNamesForFamilyName:<#(NSString *)#>];
2. Using Interface Builder:
You can set your font in the Attributes Inspector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the items inside an array in Object Oriented PHP? I have the following variable available inside a view:
$recent_posts
It is an array so I performed a foreach loop on it and var dumped the result like so:
<? foreach($recent_posts as $post): ?>
<pre><?= var_dump($post) ?></pre>
<? endforeach ?>
This is the output I received from the vardump:
Array
(
[obj] => models\Tag Object
(
[large_image:protected] =>
[small_image:protected] =>
[_obj_id] => 13493
[_validator] =>
[_values:protected] => Array
(
)
[_dirty_values:protected] => Array
(
)
[_type:protected] =>
[_properties:protected] => Array
(
)
[_is_loaded:protected] =>
[_is_static:protected] =>
)
)
How can I retrieve the values for each post. For example how can I get the large_image for a post? I tried this (without knowing what the heck I'm doing) and not surprisingly it didn't work:
<?= $post->large_image ?>
A: large_image is protected, you cannot access protected members out side of the class (this context).
You have two options, add a getter function for large_image or make it public.
getter is a function that exposes private or protected member, for example
public function get_large_image(){
return $this->large_image;
}
A: Since $post->large_image is a protected property, you are not allowed to access it outside of the class (or derived classes). I presume there might be a getter method by which you will be able to retrieve the value though (something like get_large_image() perhaps).
To determine what methods are available on the object, either view the source code of the accompanying class, or use reflection:
$refl = new ReflectionClass( $post );
var_dump( $refl->getMethods() );
If there's no method available to get the value, I would not advise you to alter the class, by making the property public (it's been made protected for a reason I presume), or alter the class at all, if it is not your own.
Rather, I would suggest, if possible, you extend the class and create a getter method for the value:
<?php
class MyTag
extends Tag
{
// I would personally prefer camelCase: getLargeImage
// but this might be more in line with the signature of the original class
public function get_large_image()
{
return $this->large_image;
}
}
Of course, this will get tricky soon, if you don't have the means to control the instantiation of the objects.
A: $post['obj']->large_image should do it.
That property is protected so you may not have access unless you are in the class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problems with xmlhttprequest status 302 I am trying to get real path in link megaupload but always but this dont work.
function getRealURL(){
var st = new String("");
var req = new XMLHttpRequest();
req.open("GET","http://www.megaupload.com/?d=6CKP1MVJ",true);
req.send(null);
req.send(null);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 302){
//SUCESSO
st = req.responseText;
}
}
};//funcao
element.getElementById("id").setAttribute("value", st);
}
i need this link:
Redirect to: http://www534.megaupload.com/files/c2c36829bc392692525f5b7b3d9d81dd/Coldplay - Warning Sign.mp3
insted of this:
http://www.megaupload.com/?d=6CKP1MVJ
A: XMLHttpRequest follows the redirect automatically by default so you don't see the 302 response. You need to set nsIHttpChannel.redirectionLimit property to zero to prevent it:
req.open("GET","http://www.megaupload.com/?d=6CKP1MVJ",true);
req.channel.QueryInterface(Components.interfaces.nsIHttpChannel).redirectionLimit = 0;
req.send(null);
Not that the link you use here redirects anywhere but this is the general approach. Btw, instead of looking at the response text for redirects you should look at req.getResponseHeader("Location").
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to specify distance metric while for kmeans in R? I'm doing kmeans clustering in R with two requirements:
*
*I need to specify my own distance function, now it's Pearson Coefficient.
*I want to do the clustering that uses average of group members as centroids, rather some actual member.
The reason for this requirement is that I think using average as centroid makes more sense than using an actual member since the members are always not near the real centroid. Please correct me if I'm wrong about this.
First I tried the kmeans function in stat package, but this function doesn't allow custom distance method.
Then I found pam function in cluster package. The pam function does allow custom distance metric by taking a dist object as parameter, but it seems to me that by doing this it takes actual members as centroids, which is not what I expect. Since I don't think it can do all the distance computation with just a distance matrix.
So is there some easy way in R to do the kmeans clustering that satisfies both my requirements ?
A: Check the flexclust package:
The main function kcca implements a general framework for
k-centroids cluster analysis supporting arbitrary distance measures
and centroid computation.
The package also includes a function distCor:
R> flexclust::distCor
function (x, centers)
{
z <- matrix(0, nrow(x), ncol = nrow(centers))
for (k in 1:nrow(centers)) {
z[, k] <- 1 - .Internal(cor(t(x), centers[k, ], 1, 0))
}
z
}
<environment: namespace:flexclust>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Mutliple domains same application, feedback please After watching the F8 keynote my company wants to use the options with the new open graph beta.
The situation:
The company is devided in 2 different sites, a record label and a artist management site.
Both sites have the same artists, but have different publish options.
The artist site publish event dates and locations to the graph API and the record label publishes if somebody listens or buys a track.
All the artist have their own domains too and will need to have all the options of the above sites, but then only for the artist itself.
Explaining the setup as mentioned above, do I need to create a app for each site to add the functionality, even though they are basically all the same?? Is there a way to use 1 app on all domains?
A: You can use one app which hosts all the metadata pages and then redirects users when they click through the links.
I would denote one of your sites to be canonical and use it primarily. Only redirect if it doesn't have the content.
A: Another option would be to migrate your sites so they live under subdomains of the root domain. Facebook authentication and open graph supports using a single application across all subdomains of a root domain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby on Rails nested resource routing error I have a user, comment, and route model as shown:
class User < ActiveRecord::Base
has_many :routes, :dependent => :destroy
has_many :comments, :dependent => :destroy
end
class Route < ActiveRecord::Base
belongs_to :user
end
class Comment < ActiveRecord::Base
belongs_to :user
end
I have the routes.rb file nesting comments and routes within user as shown:
MyApp::Application.routes.draw do
resources :users do
resources :comments
resources :routes
end
When I run 'rake routes', the route to the Routes_controller index appears as so:
user_routes GET /users/:user_id/routes(.:format) {:action =>"index", :controller=>"routes"}
Yet for some reason when a user is signing in, I get a routing error saying that the routes controller cannot be found. This happens when the system is posting a new session in the session controller. I know that it attempts to sign in the user, but fails on the redirect. Any suggestions?
class SessionsController < ApplicationController
...
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
@title = "Sign in"
render 'new'
else
sign_in user
redirect_to user_routes_path
end
end
...
end
For some reason, the stack trace wasn't displayed when I redirect to user_routes_path, so I have it direct to root_path and the same thing happens. Here is the trace for that:
app/views/layouts/_header.html.erb:3:in
`_app_views_layouts__header_html_erb___917786942_46449696_315190'
app/views/layouts/application.html.erb:11:in
`_app_views_layouts_application_html_erb__423035099_46500948_0'
A: I will give it a try, after reading Fernandez: The rails 3 way about redirect_to.
When you look at the output from rake routes, you have the output:
user_routes GET /users/:user_id/routes(.:format) {:action =>"index", :controller=>"routes"}
The methods you may use to that route are:
*
*user_routes_url: Full URL (with protocol and everything)
*user_routes_path: Relative URL to the host
But your user_routes tells you another thing: the URL has to contain a user_id, and this user_id has to come from somewhere. So to call the different url and path methods, you have to look at the arguments:
*
*users_path: no argument, shows all users
*user_path(@user): one argument, because the information about the user is needed. Could be the user, or the user_id
*`user_routes_path(@user): needs the user, so that all routes (index view) for one user could be shown.
So include in you source code in the controller:
...
else
sign_in user
redirect_to user_routes_path(user)
end
...
I don't understand the error message you have appended, but I think you should first correct the path call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My Textfield UITableViewCell and my textfieldShouldReturn are not seeing eye to eye After selecting a cell and writing something in it, I would like to hit the return/next button on the keyboard and simply move to the next cell, that's what I am trying to achieve. But after placing a breakpoint on my method textfieldShouldReturn, I find that it does not get visited, even though I pressed on the return/next key. Can someone explain why?
Thank you.
A: What do you mean by cell. It will only call when you have UITextField in the cell and also set delegate to self.
UITextField *txt=[[UITextField alloc]initWithFrame:CellFrame];
text.tag=indexPath.row;
txt.delegate=self;
[cell.contentView addSubview:txt];
then it will definitely call textFieldShouldReturn method. on return click
A: @interface WordListTableController : UITableViewController <UITextFieldDelegate>
{
}
@end
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
UITextField *FirstField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 130, 25)];
FirstField.delegate = self;
[FirstField setTag:indexPath.row];
FirstField.returnKeyType = UIReturnKeyNext;
[cell.contentView addSubview:FirstField];
[FirstField release];
return cell;
}
// Handle any actions, after the return/next/done button is pressed
- (BOOL)textfieldShouldReturn:(UITextField *)textfield
{
[textfield resignFirstResponder];
return NO;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Websphere 7 form-based authentication ignored when classloader order PARENT_LAST I have a very simple web-application that integrates spring security with j2ee declarative security.
The important parts of the web.xml are shown here:
<security-role>
<role-name>ROLE_USER</role-name>
</security-role>
<security-role>
<role-name>ROLE_SUPERVISOR</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>All Resources</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ROLE_USER</role-name>
<role-name>ROLE_SUPERVISOR</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/accessdenied.html</form-error-page>
</form-login-config>
</login-config>
This works exactly as expected in Tomcat 6.0.33 and Glassfish 3.1.1. When I migrated the same app to Websphere 7.0.0.17, I noticed that I had to reverse the classloader order marking it as PARENT_LAST (because WAS embeds a really old version of commons-logging which breaks the webapp).
The behavior I expect is for WAS to redirect to the form-login-page when I request a resource in the webapp.
The behavior I'm seeing is that instead of websphere protecting the secured resources by presenting the login form, it proceeds directly to the "Access Denied" supplied by spring security from within the app.
I've also tried BASIC instead of FORM as the auth-method, and the results are the same.
Any ideas as to what I might be doing wrong?
EDIT: Disabling Spring Security causes the declarative security to work as expected.
This sort of leads to the conclusion that if I want the built-in LoginFilter to fire first, I'd have to explicitly declare it in my web.xml --giving me a dependency on WAS :O(
EDIT: I also discovered that WAS fires the filters declared in the app before applying declarative security; it happens this way regardless of the classloader order.
Notes: I have administrative security enabled, and properly mapped user roles, etc. I verified this using the "DefaultApp" that comes with websphere, the "snoop" servlet is protected, and the challenge seems to work as normal in that app.
A: Since you say the webapp is really simple, I'd go in a whole other direction: eliminating commons-logging from your dependencies and rely on the one from WAS. JCL is quite tough to root out from Websphere (see, for example, other such problem I tried to help with: Explanation of class loading in an EAR for non-requested but dependent class). The popular hint is to switch to PARENT_LAST, but considerable number of people report it does not work for them.
Go through your dependencies and see what relies of JCL; if you use "nodep" jars (self-contained with all depencencies packed), change them to single jars. Maven is a great helper for this, if you don't use it, it's down to manual work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to give file level rights with SVN server I am currently using SVN for Source Control (Visual SVN server + tortoise SVN) and we are starting a new project in a large team.
I was wondering how to give commit rights on specific files or folder to a particular user.
We have given responsibilities for different modules to different developers, and management was wondering if it is possible to restrict a developer to commit to only his module.
I saw that a comment to this answer mentions that it is possible with Visual SVN, but I haven't been able to do so.
A: Subversion provides you the option to use path based authorization. That means, you may configure it that users have read, read-write or no access rights to read and write files in a specific directory. This is done on a per-repository base.
The following resources will help you find your way:
*
*VisualSVN Server: Understand Access Rights
*Path based Authorization in Subversion
The first one is very concrete and tells you the rules in the context of VisualSVN Server, the second one is more abstract, but gives you complete background and explanation (and some discussion why restricting developers is no good idea at all).
One final remark: Are you sure that you will never ever need the right to change code in other modules? Refactoring, errors that hinder yourself to do the job, ...?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I change the full background color of the console window in C#? In C#, the console has properties that can be used to change the background color of the console, and the foreground (text) color of the console.
Console.BackgroundColor // the background color
Console.ForegroundColor // the foreground/text color
The issue is that background color applies only where text is written, not to free space.
Console.BackgroundColor = ConsoleColor.White; // background color is white
Console.ForegroundColor = ConsoleColor.Blue; // text color is blue
Now, with the above code, it does indeed turn the text blue, but it only turns the background of the text white, instead of the entire console window's background.
Here's an example of what I mean:
As you can see, the white background only displays behind the text, and does not change the color of the entire console window.
How do I change the color of the entire console window?
A: Pardon the shameless self-promotion, but I've created a small plugin (available on NuGet) that allows you to add any (if supported by your terminal) color to your console output, without the limitations of the classic solutions.
It works by extending the String object, and the syntax is very simple:
"colorize me".Pastel("#1E90FF");
A: You need to clear the console window AFTER setting the colors but BEFORE you write the text...
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.Green;
Console.Clear();
Console.WriteLine("Hello World");
Console.ReadLine();
A: The running console controls the colors. You're essentially only changing the output of your application's color properties.
It's simple for changing the overall background color:
Click on the 'C:\' icon
Select Properties and choose the Colors tab.
Now if you're wanting to do this programmatically, you'll want to launch you're own window:
CMD /T:F[n color index]
Color Value
Black 0
Blue 1
Green 2
Aqua 3
Red 4
Purple 5
Greenish Yellow 6
Light Gray 7
Gray 8
Light Blue 9
Light Green A
Light Aqua B
Light Red C
Light Purple D
Light Yellow E
Bright White F
Or if you're using PowerShell, refer to this TechNet article: http://technet.microsoft.com/en-us/library/ee156814.aspx
A: internal class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.Clear();
Array marks = Enum.GetValues(typeof(Mark));
foreach (var mark in marks)
{
Console.WriteLine(mark);
Console.BackgroundColor = ConsoleColor.Yellow;
}
}
}
A: This will work for you put it after your first open brace
{
system("cls");
system("color f3");
}
You can change the colors by number up to 7 I think example f1,f2,f3,f4... .
A: Console.ForegroundColor = ConsoleColor.White;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Windows Form code not executing? Ok, I've got a weird one here. I'm trying to make a basic tile engine using a windows form, but some of my code is just...not happening. I'll post the chunks in question.
private void MapEditor_Load(object sender, EventArgs e)
{
LoadImageList();
FixScrollBarScales();
cboCodeValues.Items.Clear();
cboCodeValues.Items.Add("ENEMY");
cboCodeValues.Items.Add("CHEST");
cboCodeValues.Items.Add("NPC");
for (int x = 0; x < 100; x++)
cboMapNumber.Items.Add(x.ToString().PadLeft(3, '0'));
cboMapNumber.SelectedIndex = 0;
TileMap.EditorMode = true;
backgroundToolStripMenuItem.Checked = true;
}
This should be called when the form loads, right? The code dives into LoadImageList(), which contains:
private void LoadImageList()
{
string filepath = Application.StartupPath +
@"\Content\Textures\IndoorTileSet.png";
Bitmap tileSheet = new Bitmap(filepath);
int tilecount = 0;
for(int y = 0; y < tileSheet.Height / TileMap.TileHeight; y++)
{
for(int x = 0; x < tileSheet.Width / TileMap.TileWidth; x++)
{
Bitmap newBitmap = tileSheet.Clone(
new System.Drawing.Rectangle(
x * TileMap.TileWidth,
y * TileMap.TileHeight,
TileMap.TileWidth,
TileMap.TileHeight),
System.Drawing.Imaging.PixelFormat.DontCare);
imgListTiles.Images.Add(newBitmap);
string itemName = "";
if(tilecount == 0)
itemName = "Empty";
if(tilecount == 1)
itemName = "Floor";
listTiles.Items.Add(new ListViewItem(itemName, tilecount++));
}
}
}
The bitmap loads correctly, but then the entire MapEditor_Load method just stops working. tileCount seems to be a local variable in the debugger, and its value is 0, but the debugger never executes the breakpoint on the line which it is assigned. I have absolutely no idea why it would do this, and it's driving me nuts. Any help?
Oh, I put the bitmap load in a try/catch block just to see if it was handling an exception in a weird way, but I had no luck. It's not throwing an exception. I began having this problem immediately after replacing my IndoorTileSet with an updated version. I've tried a clean rebuild, with no success.
I read something about a person having a similar problem, who wound up having to declare something as an Instance of a class, but the post wasn't detailed enough for me to know if that's where I'm going wrong, or what I might have to declare as an Instance for it to work...or what an Instance even means, really.
A: I'm not sure about the code in LoadImageList() method but I suggest you to use BackgroundWorker or Control.Invoke to make your application more responsive.
A: Try this :
Bitmap tileSheet = (Bitmap)Bitmap.FromFile(filepath);
A: The problem is, superficially, that my Bitmap code is throwing an FileNotFound exception, which means I've got a bad filepath. I can handle that. The issue of the program not actually throwing exceptions, and seeming to ignore code, is an issue with 64-bit operating systems not being able to handle exception calls in all instances. The details, and a link to a hotfix to solve the issue, can be found at this site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel - VBA Question. Need to access data from all excel files in a directory without opening the files So I have a "master" excel file that I need to populate with data from excel files in a directory. I just need to access each file and copy one line from the second sheet in each workbook and paste that into my master file without opening the excel files.
I'm not an expert at this but I can handle some intermediate macros. The most important thing I need is to be able to access each file one by one without opening them. I really need this so any help is appreciated! Thanks!
Edit...
So I've been trying to use the dir function to run through the directory with a loop, but I don't know how to move on from the first file. I saw this on a site, but for me the loop won't stop and it only accesses the first file in the directory.
Folder = "\\Drcs8570168\shasad\Test"
wbname = Dir(Folder & "\" & "*.xls")
Do While wbname <> ""
i = i + 1
ReDim Preserve wblist(1 To i)
wblist(i) = wbname
wbname = Dir(FolderName & "\" & "*.xls")
How does wbname move down the list of files?
A: You dont have to open the files (ADO may be an option, as is creating links with code, or using ExecuteExcel4Macro) but typically opening files with code is the most flexible and easiest approach.
*
*Copy a range from a closed workbook (ADO)
*ExecuteExcel4Macro
*Links method
But why don't you want to open the files - is this really a hard constraint?
My code in Macro to loop through all sheets that are placed between two named sheets and copy their data to a consolidated file pulls all data from all sheets in each workbook in a folder together (by opening the files in the background).
It could easily be tailored to just row X of sheet 2 if you are happy with this process
A: I just want to point out: You don't strictly need VBA to get values from a closed workbook. You can use a formula such as:
='C:\MyPath\[MyBook.xls]Sheet1'!$A$3
You can implement this approach in VBA as well:
Dim rngDestinationCell As Range
Dim rngSourceCell As Range
Dim xlsPath As String
Dim xlsFilename As String
Dim sourceSheetName As String
Set rngDestinationCell = Cells(3,1) ' or Range("A3")
Set rngSourceCell = Cells(3,1)
xlsPath = "C:\MyPath"
xlsFilename = "MyBook.xls"
sourceSheetName = "Sheet1"
rngDestinationCell.Formula = "=" _
& "'" & xlsPath & "\[" & xlsFilename & "]" & sourceSheetName & "'!" _
& rngSourceCell.Address
The other answers present fine solutions as well, perhaps more elegant than this.
A: brettdj and paulsm4 answers are giving much information but I still wanted to add my 2 cents.
As iDevlop answered in this thread ( Copy data from another Workbook through VBA ), you can also use GetInfoFromClosedFile().
A: Some bits from my class-wrapper for Excel:
Dim wb As Excel.Workbook
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
xlApp.DisplayAlerts = False ''# prevents dialog boxes
xlApp.ScreenUpdating = False ''# prevents showing up
xlApp.EnableEvents = False ''# prevents all internal events even being fired
''# start your "reading from the files"-loop here
Set wb = xlApp.Workbooks.Add(sFilename) '' better than open, because it can read from files that are in use
''# read the cells you need...
''# [....]
wb.Close SaveChanges:=False ''# clean up workbook
''# end your "reading from the files"-loop here
''# after your're done with all files, properly clean up:
xlApp.Quit
Set xlApp = Nothing
Good luck!
A: At the start of your macro add
Application.ScreenUpdating = false
then at the end
Application.ScreenUpdating = True
and you won't see any files open as the macro performs its function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should the custom error set to off to be able to simply log errors? I implemented a simple error logging as a test in a MVC website using the following code:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
using (StreamWriter sw = File.AppendText(Server.MapPath("\\log.txt")))
{
sw.WriteLine(string.Format("Time:{0}\n{1} \n\n\n", DateTime.Now, ex.ToString()));
}
}
The problem i am facing is that logging is not writing to the file if the customerror in the website web.config is not Off <customErrors mode="Off"></customErrors>
But I think this will let the website users see the yellow screen of death if an error happened, is there a way to log the errors the way I am doing but without setting the custom errors to off?
A: You will get these Yellow Screen of Dead because you are not handling the exceptions correctly. If you are logging all of the exceptions, then you have (most likely) one method that will receive all of the exceptions. Check this out so that you could better trap errors at Page Level, Application Level or in the Web.Config file.
Take a look at this if you want to see Microsoft's Best Practices for Handling Exceptions.
Good Luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flash Player embedded in .NET WinForms app cannot load HTTPS content with self-signed certificate I have a Flash Player ActiveX control embedded in a .NET WinForms application and am trying to load a SWF into the FP control over an HTTPS url. In development I'm using a self-signed certificate and it seems that in this scenario I can't get FP to accept the certificate and allow the HTTPS communications.
When I try to load the swf over https directly, I don't see the swf and when I right-click on the control I see "Movie not loaded".
I can load the swf over http and then try to make Flash Remoting calls over https. I don't expect this to work by default but I added a crossdomain.xml file to allow insecure communications. The crossdomain.xml file is in the root of the server but is not loaded. I added an explicit call to loadPolicyFile with the full https url and the crossdomain.xml file is still not loaded. The local IIS logs don't show any request for the file at all, nothing in the HTTPERR file, and Flash's policyfiles.txt log says
Warning: Failed to load policy file from https://localhost/crossdomain.xml
If I host the swf in a browser, then the browser prompts to accept the certificate and everything works fine. I've accepted the certificate in IE and Firefox.
I also tried calling DisableLocalSecurity() on the FP ActiveX control but it had no effect. I didn't really expect it to since I'm not actually loading the swf locally, it's loaded from a url.
Can anyone confirm if the self-signed cert really is the problem? Is there a way to get FP to accept the certificate? Any way to bypass the http/https restriction (this is a locally installed app so I can change any local config files we need)?
A: Turns out Flash Player itself doesn't support HTTPS in standalone or embedded in a desktop application. It does support HTTPS in a browser but then it's using the browser for https calls.
HTTPS support in Flash Player embedded in Desktop apps is a new feature in Flash Player 11.
http://kb2.adobe.com/cps/916/cpsid_91694.html
New Features in Flash Player 11
TLS Secure Sockets Support (new for Flash Player) — Enables secure communications for client/server applications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C - 'char **' differs in levels of indirection from 'char (*)[6]' Can someone please explain to me what's wrong with the following, and more importantly why?
int main( int argc, char *argv[] )
{
char array[] = "array";
char **test;
test = &array;
*test[0] = 'Z';
printf( "%s\n", array );
return 0;
}
EDIT
My example above was based on a function like this that was crashing:
void apple( char **pp )
{
*pp = malloc( 123 );
*pp[0] = 'a'; // technically this is correct but in bad form
*pp[1] = 'b'; // incorrect but no crash
*pp[2] = '\0'; // incorrect and crash
}
As pointed out to me by Vaughn Cato although *pp[0] = 'a'; does not crash it is in bad form. The correct form is the parenthesis
void apple( char **pp )
{
*pp = malloc( 123 );
(*pp)[0] = 'a'; // correct
(*pp)[1] = 'b'; // correct
(*pp)[2] = '\0'; // correct
}
Also as another poster MK pointed out the FAQ covers the difference between arrays and pointers:
http://www.lysator.liu.se/c/c-faq/c-2.html
A: This would be the way to do what you seem to be trying to do:
int main( int argc, char *argv[] )
{
char array[] = "array";
char (*test)[6];
test = &array;
(*test)[0] = 'Z';
printf( "%s\n", array );
return 0;
}
test is a pointer to an array, and an array is different from a pointer, even though C makes it easy to use one like the other in my cases.
If you wanted to avoid having to specify a specific sized array, you could use a different approach:
int main( int argc, char *argv[] )
{
char array[] = "array";
char *test;
test = array; // same as test = &array[0];
test[0] = 'Z';
printf( "%s\n", array );
return 0;
}
A: test = &array
is wrong because test is of type char** and &array is a char(*)[6] and is a different type from char**
An array isn't the same type as char* although C will implicitly convert between an array type and a char* in some contexts, but this isn't one of them. Basically the expectation that char* is the same as the type of an array (e.g: char[6]) is wrong and therefore the expectation that taking the address of an array will result in a char** is also wrong.
A: char **test; is a pointer to a pointer, but if you're going to take the address of an entire array then it needs to be a pointer to entire array i.e char (*test)[6];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How to define implicit data templates in Metro XAML? I am trying to create a DataTemplate for mapping a simple data type with a corresponding view as follows:
<DataTemplate DataType="{x:Type src:Person}">
<TextBox Text="{Binding Name}"/>
</DataTemplate>
I get a compiler error indicating that the DataType property is not recognized or accessible. Am I missing something here? Is there new syntax for doing this or is the feature missing? Are there alternative solutions for implicit templates?
For reference, here is the full code with the DataTemplate qualified using a x:Key attribute (which works):
<UserControl x:Class="Metro_App.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:src="clr-namespace:Metro_App"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1366">
<UserControl.Resources>
<DataTemplate x:Key="PersonTemplate">
<TextBlock Text="{Binding Name}" Foreground="White" FontSize="72"/>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<ContentControl Content="{Binding MyPerson}" ContentTemplate="{StaticResource PersonTemplate}"/>
</Grid>
</UserControl>
A: With WinRT, the syntax for mapping your CLR namespaces to XAML are different. You should change you mapping from:
xmlns:src="clr-namespace:Metro_App"
to
xmlns:src="using:Metro_App"
For further information on moving from Silverlight to WinRT, see the series of blog posts by Morten Nielsen, or the article I wrote about creating a cross platform Silverlight / WinRT application.
However ... if you look at the API documentation for DataTemplate you will find that there is not DataType property. Within WinRT there is implicit styling, but not implicit data templating.
A: Silverlight doesn't have DataTemplate.DataType, and I suspect that Windows XAML framework inherited that limitation. You might have to use DataTemplateSelector instead.
Interestingly enough, it does have DataTemplateKey class, but instantiating it from XAML does not work.
A: Have you define namespace?
xmlns:src="clr-namespace:WpfApplicationNamespace"
<Window x:Class="WpfApplicationNamespace.MainWindow"
xmlns:src="clr-namespace:WpfApplicationNamespace"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type src:Persone}"/>
</Window.Resources>
<Grid>
<StackPanel Orientation="Vertical">
<Button Content="fffff" Click="Button_Click" />
</StackPanel>
</Grid>
</Window>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: how to submit combo box value with out form using javascript? I need to submit combo box value with out form. When I click on any value of combo that suppose to submit automatically using javascript. I am using PHP in backend.
<select name="select" id="select" style="width:50px;">
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="All">All</option>
</select>
A: Here a js part:
function getinfo() {
var aList = document.getElementById("select");
var val = aList.options[aList.selectedIndex].value;
// document.write("<p>Here what you select: "+val+"</p>");
// here you can send `val` to the server using... are you using any js library?
}
And you need to change your select declaration:
<select name="select" id="select" style="width:50px;" onchange="getinfo()">
--------------------
</select>
OK, how to send val to the server is another question... If you are using jQuery - you can use jQuery.ajax(...) or any helper like jQuery.get(...). If you are vanilla-js user you can use XMLHttpRequest way and if you use any other lib - just check this lib's documentation to get helped about sending data to the server.
A: You can use the methods below.
1) Use Session or Cookie to send external data
2) Send a POST request using XMLHttpRequest in javascript.Checkout the link here.
3)You can use cURL function to send HTTP POST request. Please go through the link here.
A: Some comments:
*
*The select element should always be inside a form. But you don't need to expose the form on the page--you do not need to include a submit input element.
*You can use Javascript (JS) to submit the form after the user has changed the value of the select.
*Or you can use JS with Ajax to submit the form asynchronously in the background--the user will not be aware that the data had been submitted and the page will not reload or "flash"
What would you like to do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing CK editor filder I created a asp.net web application and then I downloaded ckeditor. And I extracted my application directory this editor folder. And I added dll of ckeditor to reference of my application. I registered in my web page.
<add tagPrefix="CKEditor" assembly="CKEditor.NET" namespace="CKEditor.NET"/>
I can use ck editor as well. But when I put ckeditor to child folder, I didn't use ckeditor.
root
MyDefault.aspx
MyEditor
ckeditor folder
I want to use like this. How could I do that.
A: I used ckeditor in my website...
I set it rootforlder/js/ckeditor(folder)
I add below tag in page where I used ckeditor.
<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
I used ckeditor control like below...
<CKEditor:CKEditorControl ID="ckService" runat="server" Height="200px" Width="400px" BasePath="~/js/ckeditor/"></CKEditor:CKEditorControl>
I hope this will help you... please, let me know.. if you want any help regarding it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parsing JSON into Java from Klout API I am making a web application that returns the Klout Scores details of Twitter followers. The work flow is as follow :
*
*From Twitter API, get twitter_id of the followers . eg: 48,000 ids of Sachin Tendulkar followers.
*get twitter info(screen name,twitter_name,location) for twitter_id received from step 1.
*from Klout API , get Klout Scores in JSON format and then parsing JSON into Java.
*from Klout API ,get Klout Topics in JSON format and then parsing JSON into Java.
*Insert Klout and Twitter data into Database.
I am facing problem in parsing JSON into Java. Please suggest solutions.
Thanks in advance .
Komal
A: Take a look at the Setting up a Klout application section of the Direct Media Tips and Tricks book. It explains how to use the dmt-klout library to get the information you are looking for.
If you want to rewrite the library, you can look into the source code. The dmt-klout library depends on the json.org classes to parse the JSON response. For instance:
public User(JSONObject json) {
nick = json.getString("nick");
id = new UserId(json.getString("kloutId"));
JSONObject scores = json.getJSONObject("score");
bucket = scores.getString("bucket");
score = scores.getDouble("score");
JSONObject scoreDeltas = json.getJSONObject("scoreDeltas");
dayChange = scoreDeltas.getDouble("dayChange");
weekChange = scoreDeltas.getDouble("weekChange");
monthChange = scoreDeltas.getDouble("monthChange");
}
In this case json is a JSONObject created using the String that is returned when querying for a user. This User class is also used for the influence query:
public Influence(JSONObject json) {
parseInfluence(json.getJSONArray("myInfluencers"), myInfluencers);
parseInfluence(json.getJSONArray("myInfluencees"), myInfluencees);
}
private void parseInfluence(JSONArray array, List<User> list) {
int count = array.length();
for (int i = 0; i < count; i++) {
list.add(new User(
array.getJSONObject(i).getJSONObject("entity")
.getJSONObject("payload")));
}
}
Retrieving topics is done in a slightly different way:
public List<Topic> getTopics(UserId id) throws IOException {
List<Topic> topics = new ArrayList<Topic>();
JSONArray array = new JSONArray(KloutRequests.sendRequest(String.format(
KloutRequests.TOPICS_FROM_KLOUT_ID, getUserId(id).getId(), apiKey)));
int n = array.length();
for (int i = 0; i < n; i++) {
topics.add(new Topic(array.getJSONObject(i)));
}
return topics;
}
The constructor of the Topic class looks like this:
public Topic(JSONObject json) {
id = json.getLong("id");
name = json.getString("name");
displayName = json.getString("displayName");
slug = json.getString("slug");
displayType = json.getString("displayType");
imageUrl = json.getString("imageUrl");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I implement a Timer on this MVC setup? Using Java Spring, I have a page which pulls a random auction listing from its database, and refreshes this action every time the user refreshes the browser.
Instead, I want to make it show the same randomly chosen auction for all users, switching to a new random one every hour. ("Here is this hour's featured auction!")
Here is how my current flow works:
*
*Data.xml pulls in random auction from db.
*DAO created from sql import
*public List created from DAO, does a few special things here with the data.
*List from that List created in page controller, added to a MVC map for use on front end.
Kind of running out of time here, so I'm just going to create a kind of stop valve on this, so it only gets the data once every hour instead of on request.
Not asking for code here, but a strategy. Should I go with a CronTrigger? And where should the job be?
(Thanks :) )
A: Sounds like new Spring caching support might be helpful: set cache time to live to 1 hour with condition (or clear it manually with any scheduler).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "self.navigationItem.rightBarButtonItem" Not working I have the following code taken straight from the NavBar sample code from Apple. I put this in the viewDidLoad method for a view in my app that is being presented modally, and it wont work.
UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"AddTitle", @"")
style:UIBarButtonItemStyleBordered
target:self
action:@selector(addAction:)] autorelease];
self.navigationItem.rightBarButtonItem = addButton;
Any Suggestions?
A: Okay explained solution:
presentModalViewController:animated: presents a viewController modally, which does not have a UINavigationBar, so you can do some things:
*
*Add a UINavigationBar in your viewController's nib and add the "Add" button there and everything you need to setup.
*You can use pushViewController:animated: to show the viewController modally which will be on the navigation stack and have the UINavigationBar for you to add your button
*If your first viewController is not a UINavigationController, using pushViewController:animated: won't solve it, so you can present a UINavigationController modally with your viewController as the rootViewController:
YourViewController *viewController =[[[YourViewController alloc] initWithNibName:@"YourViewController" bundle:nil] autorelease];
UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];
[self.navigationController presentModalViewController:navController animated:YES];
Hope any of this helps
A: You need to use these lines of code on the page where you present the other view.
sceondController *obj=[[[sceondController alloc] initWithNibName:@"sceondController" bundle:nil] autorelease];
UINavigationController *navController=[[[UINavigationController alloc] initWithRootViewController:obj] autorelease];
[self.navigationController presentModalViewController:navController animated:NO];
and in second view use same code which you are using for making navigation button.
May be it resolves your problem.
A: I assume your view controller is actually a UINavigationController and everything else is in place. In which case I would change two things.
*
*I wouldn't autorelease the UIBarButtonItem. That tends to be unreliable with view controllers so add the button to your list of things to dealloc at cleanup
*I would use the setter function to set the button. Here is my code that works in my navigation controller
clearAllButton = [[UIBarButtonItem alloc] initWithTitle:@"Clear All" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonPressed:)];
[[self navigationItem] setRightBarButtonItem:clearAllButton];
A: Run your app in real device. In iOS6 it is not working on simulator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do i make database object more efficient by reusing I am confused on how to handle the logic of reusing the database object and configuration variables or constants that stands global for the application.
the way i have been doing till now is, i created a config.php file in Config directory and declare all the config elements for example my typical config.php file would look like this.
#Start Session
session_start();
#Start Output Buffering
ob_start();
#Set Default TimeZone
date_default_timezone_set('Asia/Kolkata');
#Define Time Constant
define('DATE', date("d-F-Y/H:ia"));
#Define Paths
define('CLASSES',$_SERVER['DOCUMENT_ROOT'].'/resources/library/classes/');
define('MODELS',$_SERVER['DOCUMENT_ROOT'].'/resources/library/models/');
define('LOGS',$_SERVER['DOCUMENT_ROOT'].'/resources/logs/');
#Define Connection Constant
define('HOST','localhost');
define('USERNAME','username');
define('PASSWORD','password');
define('DATABASE','dbname');
try
{
#Connection String.
$dbh = new PDO('mysql:host='.HOST.';dbname='.DATABASE,USERNAME,PASSWORD);
#Set Error Mode to ERRMODE_EXCEPTION.
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
#Print Errors.
echo $e->getMessage();
#Log Errors into a file
file_put_contents(LOGS.'Connection-log.txt', DATE.PHP_EOL.$e->getMessage().PHP_EOL.PHP_EOL, FILE_APPEND);
}
#Autoload Classes.
function __autoload($class) {
require_once CLASSES.'class.'.strtolower($class).'.php';
}
and in index.php file i would include this file once and re-use it in every object.
my index.php typically consist of controllers like this.
if(isset($_GET['users'])) {
require_once(MODELS.'users/users.php');
} else if(isset($_GET['categories'])) {
require_once(MODELS.'categories/categories.php');
} else if(isset($_GET['search'])) {
require_once(MODELS.'search/search.php');
}
and in Models i would instantiate the object i want and use it for example in users/users.php i would instantiate it like this
$user = new User($dbh);
all is working fine but the problem is for each and every class i have to pass the database handle object through constructor and re-use it in the class which is kind of ugly for me. and this approach creates a problem for me if i want to use class which contains static methods and properties that holds the Application settings that is to be retrieved from database. my requirement is such that.
I want to create a static method using singleton pattern that will hold the database object that is to be used across the application without the need to pass the the $dbh object each and everytime through constructor for each and every class. and i am very much confused on how should i deal with this.
thank you
A: I have a similar design pattern where I connect and store the connection in a global.
You do not need to pass the database variable to every class as it is a global.
You can use it anywhere like this:
$GLOBALS['dbh'];
To hide this I have actually created a function named get_db_connection() which first checks if there is a valid connection in the $GLOBALS array and then returns it. Also if there is no valid connection there, it creates a new connection stores it in the $GLOBALS and returns it.
It has the added benifit that I do need to instantiate the connection manually anywhere, it is automatically created on the first call to get_db_connection and is available everywhere subsequently.
The get_db_connection function looks something like this:
function get_db_connection(){
if(isset($GLOBALS['db_conn']) && get_class($GLOBALS['db_conn']) == 'PDO'){
return $GLOBALS['db_conn'];
}else{
$conn = new PDO(/* parameters */);
$GLOBALS['db_conn'] = &$conn;
return $conn;
}
}
defence in favour of global
I consider this to be an excusable usage of globals for following reasons:
*
*The variable $dbh is already a global as it is not inside a function
or a class.
*You are not accessing the global directly anywhere in
your program, but only through a single function get_db_connection
so the problem that anyone can change the value of the global is not
here.
*The only way around this is by using a Singleton, which may be
unnecessary for such a simple problem.
Of these I consider the 2nd reason to be most concrete.
A: here is what i came up with finally.
class DB {
protected static $_dbh;
const HOST = 'localhost';
const DATABASE = 'dbname';
const USERNAME = 'usname';
const PASSWORD = 'passwo';
private function __construct() { }
public static function get_db_connection() {
if(!isset(self::$_dbh)) {
self::$_dbh = new PDO('mysql:host='.self::HOST.';dbname='.self::DATABASE,self::USERNAME,self::PASSWORD);
self::$_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$_dbh;
}
}
Applying singleton pattern and with static method call i can easily access the database object without passing the database object through class constructor.
To call the database object within or outside the class scope all i have to do is call a single line of code.
DB::get_db_connection();
this sounds more feasible isn't it? :)
A: You could try something like this:
function cnn() {
static $pdo;
if(!isset($pdo)) {
$pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_TIMEOUT, 30);
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return $pdo;
} else {
return $pdo;
}
}
After that, you can call any queries you want:
echo cnn()->query('SELECT firstname FROM user WHERE id=4;')->fetch(PDO::FETCH_COLUMN)
Second query (object is reused)
echo cnn()->query('SELECT title FROM news WHERE id=516;')->fetch(PDO::FETCH_COLUMN)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No error message in Haskell Just out of curiosity, I made a simple script to check speed and memory efficiency of constructing a list in Haskell:
wasteMem :: Int -> [Int]
wasteMem 0 = [199]
wasteMem x = (12432483483467856487256348746328761:wasteMem (x-1))
main = do
putStrLn("hello")
putStrLn(show (wasteMem 10000000000000000000000000000000000))
The strange thing is, when I tried this, it didn't run out of memory or stack space, it only prints [199], the same as running wasteMem 0. It doesn't even print an error message... why? Entering this large number in ghci just prints the number, so I don't think it's a rounding or reading error.
A: Adding to Thomas' answer, if you really want to waste space, you have to perform an operation on the list, which needs the whole list in memory at once. One such operation is sorting:
print . sort . wasteMem $ (2^16)
Also note that it's almost impossible to estimate the run-time memory usage of your list. If you want a more predictable memory benchmark, create an unboxed array instead of a list. This also doesn't require any complicated operation to ensure that everything stays in memory. Indexing a single element in an array already makes sure that the array is in memory at least once.
A: Your program is using a number greater than maxBound :: Int32. This means it will behave differently on different platforms. For GHC x86_64 Int is 64 bits (32 bits otherwise, but the Haskell report only promises 29 bits). This means your absurdly large value (1x10^34) is represented as 4003012203950112768 for me and zero for you 32-bit folks:
GHCI> 10000000000000000000000000000000000 :: Int
4003012203950112768
GHCI> 10000000000000000000000000000000000 :: Data.Int.Int32
0
This could be made platform independent by either using a fixed-size type (ex: from Data.Word or Data.Int) or using Integer.
All that said, this is a poorly conceived test to begin with. Haskell is lazy, so the amount of memory consumed by wastedMem n for any value n is minimal - it's just a thunk. Once you try to show this result it will grab elements off the list one at a time - first generating "[12432483483467856487256348746328761, and leaving the rest of the list as a thunk. The first value can be garbage collected before the second value is even considered (a constant-space program).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex to accept at least one alpha char and numeric char I was trying out a regex to "partial match" (any place in the string):
abcd1234 1a2b
I searched for a regex and found this:
/^(?=.*\d)(?=.*[a-zA-Z])$/
But it accepts only alphanumeric; abcd123!@#$ is not matched.
How can this be fixed?
A: How about this?
/^.*[a-zA-Z].*\d.*|.*\d.*[a-zA-Z].*$/
This should match either:
*
*an alphabetic character somewhere, followed by a numeric character somewhere, with any number of other types of characters on either side or between them; or
*the other way around (numeric followed by alphabetic)
A: If I understood you correctly, this is what you want:
/^.*[a-zA-z].*\d.*/
/*
'2344' => false
'abcd' => false
'a1cd' => true
'abc3' => true
'ab@3' => true
'a_*3' => true
'2_!b' => false
*/
A: The following will allow the alpha and the numeric to appear in either order:
/^.*((\d.*[a-zA-Z])|([a-zA-Z].*\d)).*$/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Picture Messages To C++ program I'm currently thinking of setting up a picture message import project. Something like this:
Client Mobile Device [picture message] -> our Server Device
Server Device [picture && number -> Server Computer
However I don't know if there's a possible way to do this. I could set up a google voice account and use something like this in order to retrieve messages, however this doesn't allow picture messages...
So I was thinking of perhaps making an android or iPhone application to redirect picture messages. Though I don't know if this is possible. If it is, how would I go about gathering the messages? The networking is simple enough, however I'm not familiar with the android system, nor the message system of the iPhone.
On the other hand, I could make a simple email server to receive messages from the cell phone provider's email system.
Is any of the above viable? The image as well as the origin number are both needed.
A: This sounds like a typical client/server application actually, except the commands sent to the server contain binary data.
There are many ways to do this, and many protocols you can use. Email (gmail) is just one example.
What I would do is use HTTP to post binary messages to your web server. This is cool because it manages authentication, data transfer, etc, are all available.
Here's a short example: Secure HTTP Post in Android
Just add authentication on top of that and you're in business!
You would have to do some web server development too.
I hope this helps.
Emmanuel
A: Ok I think this is possible. I'm not sure how it works but I'll do my best.
First you have to be notified when an SMS is received by listening to SMS_RECEIVED events. BroadcastReceiver + SMS_RECEIVED
Second, you have to read the SMS attachment as explained here: Get attachment from unread MMS messages
Does this help?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Proper Android game threads I have been looking at a lot of tutorials and blogs about Android game development and I have a question regarding the best way to implement threads.
Some examples, like Lunar Lander, has an inherited SurfaceView class (LunarView) with another class inside (LunarThread) that seems to handle the updates and drawing to the SurfaceView.
Other examples I found on the net have a very basic thread that has a run() loop and calls update and draw methods that are coded in the inherited SurfaceView class. The update/draw methods in the SurfaceView class also calls update/draw methods in other classes for objects that are used in the game.
Each seem to work, but I am not sure which is the best way to proceed. I also can't get past having a class within a class for some reason. Is that normal?
Thanks for your help!
A: I think its not the best practice. LunarLander is created as a sample project to give some idea of how to use SurfaceView. But again if you keep the calling thread in another class still it will be weird. Since that class only bound to SurfaceView class. I have done development with LunaLander type implementation and it has given me good results.
I THINK the way you do it doesn't matter in the compile and run level, it's only matters at the level where other people understanding your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove text field if value in datasource is empty? If I am creating a Jasper report template file in the iReports designer, is it possible to prevent a static text field from displaying if a field in its datasource is empty?
I know that I can use a certain amount of JavaScript to manipulate data in the report. Is it possible to perhaps hide an element if a field value is NULL or empty?
A:
Is it possible to perhaps hide an element if a field value is NULL or
empty?
Yes, it is possible.
1. Using "Print When Expression" property for static and text fields
Sample for hiding NULL or "empty" string value:
<staticText>
<reportElement x="52" y="16" width="100" height="20">
<printWhenExpression><![CDATA[$F{field1} != null && $F{field1}.trim().length()>0]]></printWhenExpression>
</reportElement>
<textElement/>
<text><![CDATA[Static text]]></text>
</staticText>
<textField>
<reportElement x="170" y="15" width="100" height="20">
<printWhenExpression><![CDATA[$F{field2} != null && $F{field2}.trim().length()>0]]></printWhenExpression>
</reportElement>
<textElement/>
<textFieldExpression><![CDATA[$F{field2}]]></textFieldExpression>
</textField>
2. Using "Blank When Null" property for text fields
Sample for hiding text field with NULL value:
<textField isBlankWhenNull="true">
<reportElement x="340" y="15" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{field3}]]></textFieldExpression>
</textField>
3. Using "No Data" band for empty datasource - no data returns
If datasource is empty you can use "No Data" band with static fields you needs. For using this band you must set "When No Data" report's property to "No Data Section".
Sample:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport .. whenNoDataType="NoDataSection" ..>
...
<noData>
<band height="50">
<staticText>
<reportElement x="236" y="18" width="100" height="20"/>
<textElement/>
<text><![CDATA[No data]]></text>
</staticText>
</band>
</noData>
</jasperReport>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does Iterator ties into Collection Interface I am new to Java.
Java has Collection interface
public interface Collection<E> extends Iterable<E>
{ // a lot of other stuff.
Iterator<E> iterator(); }
What I don't understand is how does Iterator Interface is tying into Collection Interface ? When I look at the Collection Interface, I see that it has a method that returns Iterator. When Iterator for Collection is created, where does JVM looks to create an object that IS-An Iterator ?
Thanks !
A: The JVM doesn't do it; the code that ultimately implements the abstract iterator() method just creates an instance of an appropriate class and returns it. For example, in the class ArrayList(), which implements List which extends Collection, there is a method that implements iterator() by returning an instance of a class that understand how ArrayList is implemented internally. This Iterator class is private to the java.util package -- normally you'll never see its name.
A: Ok so this is all pretty advanced java stuff and it will be pretty tough to explain in one go here but I will do my best.
BACKGROUND: If you don't know about those funny <E> things, you should do a bit of looking into Java Generics. Also, if you don't already, you really need to know what an interface is. One really basic way to think of it is as a promised bit of functionality a class promises to provide.
Now to answer your question: There are three interfaces in the above code snippet, and if you want to create your own collection class you will need to provide implementations of all three:
The first is Collection. This is a simple concept that maps to the real world, it is literally a "collection" of objects. I think you get this...
The next one is Iterable this defines a singe type of behavior that all collections need to provide: the ability to traverse all of the elements of a collection, while accessing them one by one ie "iterate" over them. But it doesn't stop there. As you pointed out the Iterable functionality is provided by objects that implement the last interface:
Iterator: objects that implement this interface, actually know how to traverse the elements of a collection class, they hide all the details of how its actually done from thier clients and proved a few clean easy methods for actually doing it like hasNext() which checks to see if there are more things in the collection to visit and next() which actually visits the next thing.
phew...
A: The code for the iterator() method determines which concrete implementation of Iterator to return.
All non-abstract classes that implement the Collection interface are required to provide an implementation for the iterator() method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to convert a texture to the ETC1 format for android Im an openGL es newbie, and am trying to figure out how to lower texture usage in my app. Im aware of ETC1 and the various other compressed texture formats but am having difficulty figuring out how i can convert my JPGs to ETC1 while the app is loading. I found ETC1Util which can generate during runtime, but this wouldnt really be helpful since my textures will never change. I would also really like to keep my app using api level 7 (ETC1Util was introduced in 8)
A: ImageTec's PVRTexTool allows you to convert your JPEG to PVR files with the compression of your choice (PVRTC or ETC1 basically). The site is full of interesting things and code around textures (eg. it's easy to make a .pvr loader).
It's also not too hard to use the provided PVRTexLib to write an offline tool that can process your JPEG files and include the tool in your build process (say you still have png/jpeg files in your project for convenience and having rules in your makefiles to generate compressed .pvr texture at build time).
A few weeks ago I've started a small gdk-pixbuf loader using PVRTExLib, might help:
https://github.com/media-explorer/gdk-pixbuf-texture-tool
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to format getdate into YYYYMMDDHHmmSS In SQL Server how do I format getdate() output into YYYYMMDDHHmmSS where HH is 24 hour format?
I've got the YYYYMMDD done with
select CONVERT(varchar,GETDATE(),112)
but that is as far as I got.
Thanks.
A: Close but not exactly what you are asking for:
select CONVERT(varchar, GETDATE(), 126)
e.g.
2011-09-23T12:18:24.837
(yyyy-mm-ddThh:mi:ss.mmm (no spaces), ISO8601 without timezone)
Ref: CAST and CONVERT
There is no way to specify a custom format with CONVERT(). The other option is to perform string manipulation to create in the format you desire.
A: Try this:
select CONVERT(varchar, GETDATE(), 120)
e.g.
2011-09-23 12:18:24
(yyyy-mm-dd hh:mi:ss (24h) ,ODBC canonical).
Hth.
A: Just for anyone searching for this functionality that has SQL Server 2012 you can use the FORMAT function:
SELECT FORMAT ( GETDATE(), 'yyyyMMddHHmmss') AS 'Custom DateTime'
This allows any .NET format strings making it a useful new addition.
A: select replace(
replace(
replace(convert(varchar(19), getdate(), 126),
'-',''),
'T',''),
':','')
A: Another option!
SELECT CONVERT(nvarchar(8), GETDATE(),112) +
CONVERT(nvarchar(2),DATEPART(HH,GETDATE())) +
CONVERT(nvarchar(2),DATEPART(MI,GETDATE())) +
CONVERT(nvarchar(2),DATEPART(SS,GETDATE()));
A: converting datetime that way requires more than one call to convert. Best use for this is in a function that returns a varchar.
select CONVERT(varchar,GETDATE(),112) --YYYYMMDD
select CONVERT(varchar,GETDATE(),108) --HH:MM:SS
Put them together like so inside the function
DECLARE @result as varchar(20)
set @result = CONVERT(varchar,GETDATE(),112) + ' ' + CONVERT(varchar,GETDATE(),108)
print @result
20131220 13:15:50
As Thinhbk posted you can use select CONVERT(varchar,getdate(),20) or select CONVERT(varchar,getdate(),120) to get quite close to what you want.
A: select CONVERT(nvarchar(8),getdate(),112) +
case when Len(CONVERT(nvarchar(2),DATEPART(HH,getdate()))) =1 then '0' + CONVERT(nvarchar(2),DATEPART(HH,getdate())) else CONVERT(nvarchar(2),DATEPART(HH,getdate())) end +
case when Len( CONVERT(nvarchar(2),DATEPART(MI,getdate())) ) =1 then '0' + CONVERT(nvarchar(2),DATEPART(MI,getdate())) else CONVERT(nvarchar(2),DATEPART(MI,getdate())) end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Finding a particular Set of SubSets of a PowerSet in an efficient way I'm trying to find an efficient way to grab a Set of Subsets of a PowerSet.
For example, this works when the set sizes are small:
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
Set<Integer> set2 = new HashSet<Integer>();
set2.add(3);
Set<Set<Integer>> sets = MyUtils.powerSet(set); //size - 8 SubSets
Set<Set<Integer>> badSets = MyUtils.powerSet(set2); //size - 2 SubSets
//my set of subsets of the powerset
sets.removeAll(badSets) //size - 6 SubSets
However when more elements are added to these sets this does not become practical. Is there another way to do this?
Just friendly reminder of what a PowerSet is:
PowerSet of {a,b,c}:
P(S) = { {}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c} }
A: If one set is subset of another one (A,B sizes m,n) after removing P(B) from P(A) you have 2n - 2m element, also if B is not a subset of A, again you can assume B'=A intersection with B and again we have similar relation, so numbers are big in all.
for example assume A-B has one element, |P(A)-P(B)| = 2n - 2(n-1) = 2(n-1), for example for n = 40 you can't iterate over all items.
anyway, one way is as bellow:
have a counter of size n in base 2, first set m+1 bit as 1 and all others as 0 then print result, and each time increase counter (by one) and print result upto rich to 2n - 1. which is O(2n - 2m).
A: Try another way:
let call set3 = set - set2;
Then Powerset(set) - Poserset(set2) = Powerset(set3) x (Powerset(set)- {});
where x here is Descartes multiple of 2 set.
if set3 has x element, set2 has y element, then with this approach, it's complexity around 2^(x+y), while if try to remove it directly, the complexity is around 2^(x + 2Y).
Hth.
A: Sounds like a job for zero suppressed decision diagrams. They support set-subtraction and creating a powerset of a range of numbers is trivial in ZDD's (and in fact the resulting ZDD has very few nodes). That means that the asymmetric difference will also run fast, because it's on two small ZDD's and it depends only on the size of the ZDD's in nodes, not the size in number of sets they contain. I don't know what you're going to do with it next, but whatever it is, you could always enumerate all sets in the ZDD and put them in an other datastructure.
A: For subtracting one power set from another, deducted power set computataion is redundant. Here is the way to go:
public static <T>void removePowerSet(
Collection <? extends Collection <T>> powerSet,
Collection <T> removedComponents){
Iterator <? extends Collection <T>> powerSetIter = powerSet.iterator();
while (powerSetIter.hasNext()) {
Collection <T> powerSetSubset = powerSetIter.next();
if (removedComponents.containsAll(powerSetSubset)) {
powerSetIter.remove();
}
}
}
This algorithm performs in a polynomial time - O(n2) for a HashSet
Now you can call removePowerSet(sets, set2) or removePowerSet(sets, Arrays.asList(3)) to get the result in your example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: iOS: Crash when keyboard is used...? Pretty simple bug:
Pressing any key on my Mac's keyboard causes an "EXC_BAD_ACCESS" error to occur when running an app on the simulator. Unless I'm entering data into a text field that is, where it works fine.
-
Not sure if this is a bug in my app, or somewhere else. If by some chance, someone was using a bluetooth keyboard with my app, then I don't exactly want it crashing willy nilly... small chance I know, but I'd still rather fix it if it's a bug. I've enabled zombies - doesn't tell me anything about where the crash is occurring, and the app still crashes.
Any thoughts or answers are much appreciated, thanks :)
A: Turning off "Auto-Correction" in the simulator keyboard settings fixed this issue for me.
Screenshot of Keyboard Settings in Simulator:
Seems there are still bugs with the simulator.
A: This bug is usually attributed to trying to access an instance that has already been released. Check your instances, anything that you allocated, released, and then you are trying to access. It may not even be connected to the keyboard, but maybe a delegate method. Post some code so we can have a better idea of it. For example, the code for the view controller that is running at the time of the crash.
A: Try to run your app with "Guard Malloc" on. You find this setting when you go to
Manage Scheme -> Run app (on the left side) -> diagnostic (on the top
lashes) -> under Memeory management.
This will show you the crash point where it happens and you should be able to find the reason much more easily
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get recently authenticated user? I am working with MVC 3 and I have just implemented a wrapper for the FormsAuthenticationService.
Something similar to the following.
public void SignIn(string username, bool createPersistantCookie)
{
if (string.IsNullOrEmpty(username))
throw new ArgumentException("Value Cannot be null or empty", "username");
FormsAuthentication.SetAuthCookie(username, createPersistantCookie);
}
Reluctantly, I have gotten this to work, but now I am not quite sure how to get the information that I have stored.
Once the user is in my system, how can I now safely retrieve this information if I need to grab their UserID out of the database?
A: Based on the additional information provided, you want to store additional data with the FormsAuthentication ticket. To do so, you need first create a custom FormsAuthentication ticket:
Storing Data
Grab the current HttpContext (not worrying about testability)
var httpContext = HttpContext.Current;
Determine when the ticket should expire:
var expires = isPersistent
? DateTime.Now.Add(FormsAuthentication.Timeout)
: NoPersistenceExpiryDate; // NoPersistenceExpiryDate = DateTime.MinValue
Create a new FormsAuthentication ticket to hold your custom data.
var authenticationTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
isPersistent,
"My Custom Data String"); //Limit to about 1200 bytes max
Create your HTTP cookie
new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authenticationTicket))
{
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain,
Secure = FormsAuthentication.RequireSSL,
Expires = expires,
HttpOnly = true
};
And finally add to the response
httpContext.Response.Cookies.Add(cookie);
Retrieving Data
Then you can retrieve your data on subsequent requests by parsing the stored authentication ticket...
Again, grab current HttpContext
var httpContext = HttpContext.Current
Check to see if the request has been authenticated (call in Application_AuthenticateRequest or OnAuthorize)
if (!httpContext.Request.IsAuthenticated)
return false;
Check to see if you have a FormsAuthentication ticket available and that it has not expired:
var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie == null)
return false;
Retrieve the FormsAuthentication ticket:
var authenticationTicket = FormsAuthentication.Decrypt(formsCookie.Value);
if (authenticationTicket.Expired)
return false;
And finally retrieve your data:
var data = authenticationTicket.UserData;
A: You haven't actually stored a user id in the database. All the code that you've written does is store an authentication cookie on the users computer, either as a session cookie (not persistent) or as a persistent one.
When your page refreshes, it will get the cookie automatically, decode it, and populate the IPrincipal object which you access from the User.Current property of your controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python performance vs PHP I am an experienced PHP developer, and I would want to know what of both languages is better for web development.
I understand that there are a lot of factors to evaluate; but focusing in execution time, in your own experience making connections to a MySQL server, parsing and concatenating strings, and making several echoes (or prints), what language would you recommend me?
I cite this specific situations because are common for me, and I don´t calculate fibonacci sequences neither prime numbers, like are showed in several benchmarks.
A: Even if things aren't specifically integer comparison or string comparison problems, looking at those computations is a decent indication of how the language will perform in more complex tasks. Keep in mind, though, that web development isn't all about computation speed. Unless you're doing some fancy backend data processing (in which case PHP is really not appropriate) when it comes to things like generating pages: it's still often worth the small sacrifice in terms of speed/memory to make it much, much easier to develop.
Also: Python+MySql is kind of a pain, in my experience. It can be done. But it's not nearly as nice.
Which is faster, python webpages or php webpages? <- lots of stuff here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Static fields and methods
Possible Duplicate:
Java: where do static fields live within the memory?
Java uses the heap to save objects and instance variables and the stack for storing methods and local variable. I want to know where static feilds and methods are stored.
static fields --
static methods --
A: Your question itself contains an error: methods themselves aren't stored anywhere that you have access to; there is a special "method space" where loaded code goes. Static fields are stored inside class definitions, which are stored in a special heap area called "PermGen space"; static methods, like normal methods, aren't stored in normal Java storage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What does windows error 0 "ERROR_SUCCESS" mean? I've written a python program which read a stdout of another process by the pipe redirection.
However, the program sucks in this line:
print "[Input Thread] ", self.inputPipe.readline(ii)
The error is IOError: [Errno 0] Error
I found the explanation of windows errno 0. It makes confused because it defined as:
The operation completed successfully.
Why does an operation completed successfully lead to an error?
A: The name can trick you but ERROR_SUCCESS actually means there was no error.
From https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx:
ERROR_SUCCESS
0 (0x0)
The operation completed successfully.
A: I know this is kind of old but having spent a fair amount of time trying to find a complete answer without success. So I figured I'd share what I've figured out.
The complete answer of how this happens, is when the pInvoke method you called "fails" but not because of an error.
huh you think
For example lets say you need to unhook a windows hook, but it gets called twice due to a bit of spaghetti or a paranoid level of defensive programming in your object architecture.
// hook assigned earlier
// now we call our clean up code
if (NativeMethods.UnhookWindowsHookEx(HookHandle) == 0)
{
// method succeeds normally so we do not get here
Log.ReportWin32Error("Error removing hook", Marshal.GetLastWin32Error());
}
// other code runs, but the hook is never reattached,
// due to paranoid defensive program you call your clean up code twice
if (NativeMethods.UnhookWindowsHookEx(HookHandle) == 0)
{
// pInvoke method failed (return zero) because there was no hook to remove
// however there was no error, the hook was already gone thus ERROR_SUCCESS (0)
// is our last error
Log.ReportWin32Error("Error removing hook", Marshal.GetLastWin32Error());
}
A: The windows API can be tricky. Most likely, the error number was not properly retrieved by the second program you mentioned. It was either overwritten or not pulled in at all; so it defaulted to 0.
You didn't say what the other program was; but for example, in .net, it is easy to omit the 'SetLastError' flag when declaring your external calls.
[DllImport('kernel32.dll', SetLastError = true)]
https://www.medo64.com/2013/03/error-the-operation-completed-successfully/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: WiX: How to schedule the InstallUISequence I am working on a installer. It is very simple; I just to write some key into the Windows Registry. But before doing this, I have to check some conditions, so I make four dialogs:
*
*Welcome;
*Check that connection to the Internet is available
*Check that the database is accessible
*Write the registry and show finish information.
And I schedule the InstallUISequence like below.
<InstallUISequence>
<Show Dialog="Welcome"
After="ExecuteAction"/>
</InstallUISequence>
And I use the "next" and "pre" to navigate the other dialogs. It works, but the welcome dialog do not show immediately. Half a minute after the prepare dialog and during this half a minute, it has no progress dialog - it seems the install has finished.
In view of this, I change the schedule like this in the Welcome dialog:
<InstallUISequence>
<Show Dialog="Welcome"
before="ExecuteAction"/>
</InstallUISequence>
And in the writeRegistry dialog:
<InstallUISequence>
<Show Dialog="writeRegistry"
After="ExecuteAction"/>
</InstallUISequence>
I want to do the ExecuteAction (write the registry) before showing the dialog writeRegistry. But it seems that there is nothing has been written into the registry.
What is the problem here and how can it be fixed?
A: ExecuteAction handles InstallExecuteSequence. So when this action starts, the installation is performed.
All your dialogs should be scheduled before ExecuteAction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to track an "app opened" metric for Android? I'm integrating with Mixpanel, which lets you track arbitrary events for your app. I want to track how often the Android app is opened.
Is there a central place where I can put code that runs every time the app is opened, regardless of activity?
A: You can track if it was started from the launcher by tracking Intent parameters in your Main Activity.
Or if you want to track how many times this screen was started, u could put your tracking code inside onStart of your activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Why is there a gap when I alignTop?
Why is there space between the top of the text and the top of the image??
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="9dp"
android:background="#FFF">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="9dp">
<ImageView
android:id="@+id/img_user"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="9dp"
android:background="#000" />
<TextView
android:id="@+id/username"
android:layout_toRightOf="@id/img_user"
android:layout_alignTop="@id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#333"
android:textStyle="bold"
android:textSize="12dp"
android:gravity="top"
android:text="Username" />
<TextView
android:id="@+id/timestamp"
android:layout_toRightOf="@id/img_user"
android:layout_alignBottom="@id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#999"
android:textSize="10dp"
android:gravity="bottom"
android:text="2h"/>
</RelativeLayout>
A: This is an inherent part of TextView. Try using margins, and consider wrapping extra layouts around to give you room to move things.
A: You have set a margin field in the linear layout and then again in the relative layout.
android:layout_margin="9dp"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why can't I make my URLs rewrite in my htaccess file? I've been messing with this for the last hour... visiting about 20 different Google tuts and I can't seem make my site rewrite the url in any way. I've even just tried changing .php to .html and I'm not having any luck.
Here's one of my many fails:
RewriteEngine on
RewriteRule viewItem(.*)\.htm$ /viewItem.php?id=$1
For this above one, I'm just trying to change my viewItem.php page to viewItem.html
My ultimate goal is to change hxxp://mydomain.com/viewItem.php?id=900 (as one example of an id) to hxxp://mydomain.com/details/
I'm then going to append the title on the end. I can do the append in php but being a newb to .htaccess, I'm apparently missing something glaringly obvious.
Any ideas?
Thanks much.
A: Did you miss the 'l' of 'html'?
RewriteRule viewItem(.*)\.html?$ /viewItem.php?id=$1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automatic Staging with Git I have a git repository and it is doing something I've never seen before and haven't found a solution anywhere. I initialized with git init and added everything with git add * and went on my way now when I try to commit after editing any number of files none are staged for commit so I have to do git add -A which then stages them all for a commit. Is there a way to skip the git add -A step? I have used git with Xcode a lot and never have had to move them from not staged to staged while in the terminal.
Is there a paradigm to the git staging area I am missing? How are you supposed to use it?
A: You do have to add your changes to the commit, but you can just use:
git commit -a
To add your changes AND commit or
git commit -am 'commit message'
Which is how i usually roll.
Manually adding your changes lets you not commit everything if you dont want to, which I'm sure you can tell is useful sometimes.
A: Add an alias which will do the add and the commit for you and start using the alias. If you are on Windows, I would have suggested TortoiseGit, which abstracts out the index.
A: In case of git you don't need to add files. Git keeps a track of all the files that have been added by you till till now. You only need to add if you are adding a new file that is not there in your git remote repo.
For files that have been modified, you can use git commit -am "message"
git commit -am "message" will automatically commit all the changed files.
After a commit you need to push the data to remote using git push command.
Hope this resolves your problem!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: php regular expression matches and replacement again.
I'm trying to go through a database table and replace all instances of old BBCode (ie: [i:fs8d979]) and replace it with simple BBCode ([i]). However, I'm getting very confusing results.
$root_path = './';
include($root_path.'includes/common.php');
$posts = array();
$sql = 'SELECT post_id, post_text FROM posts';
$db->query($sql);
while($row = $db->fetch_assoc())
{
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
}
foreach($posts as $post)
{
$regex = "/\[(\D)(\:[a-zA-Z0-9_]{1,})\]/";
if(preg_match($regex, $post['text'], $matches))
{
$string = preg_replace('/'.$matches[2].'/', '', $post['text']);
$sql = 'UPDATE posts SET post_text = "'.$string.'" WHERE post_id = '.$post['id'];
$db->query($sql);
echo $post['id'].'--Matched and replaced<br />';
}
else
{
echo $post['id'].'--No Match<br />';
}
}
echo 'done';
when i run this script, I get output like this:
1302--No Match
--No Match
1303--No Match
--No Match
17305--No Match
--Matched and replaced
5532--No Match
--No Match
17304--No Match
--No Match
1310--No Match
--No Match
it would appear that the script is attempting to do everything twice, and I'm not sure why. The database fields are not getting updated either.
I've echoed everything out for debugging purposes, and all variables are set and everything looks like it should be working properly.
Any suggestions?
A: At the point in the code:
while($row = $db->fetch_assoc())
{
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
}
You are creating two entries in the array, one with the id, followed by the text.
I think you want:
while($row = $db->fetch_assoc())
{
$posts[] = array('id' => $row['post_id'], 'text' => $row['post_text']);
}
It would explain why each one is happening twice and nothing is changing.
The debug was showing the wrong value too:
echo $post['id'].'--Matched and replaced<br />';
and the output was
--Matched and replaced which showed no post id.
A: First: the lines
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
are adding two elements to the $posts array. That is why you are getting two outputs per post.
Second: I don't think the colon : is a special character - it doesn't need to be escaped. So it should look like:
$regex = "/\[(\D)(:[a-zA-Z0-9_]+)\]/";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to update the JSF sessionscoped managed bean if i access it? As title.
The problem is the attribute in the bean is fixed after init().
I want to update the count attribute when ever i access #{managedBean.xyz} method in JSF
I want to stick with the sessionscoped instead of view/request because it saves some time for the Object re-creation.
I don't want to do the attribute update manually in every xyz function. thanks
A: If I understand you correctly, you want to invoke a bean method on every view which involves the bean?
Add <f:event type="preRenderView"> to those views.
<f:event type="preRenderView" listener="#{managedBean.countUp}" />
with
public void countUp() {
count++;
}
It will be invoked only once on every request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problems with Kohana Logs For some reason I cannot get kohana to log my custom errors. Here is the code:
$log = new Log;
$log->add(Log::ERROR, 'There was a conflic with the username and/or email. UUID: '.$user['uuid'].' username: '.$user['username'].' email: '.$user['email']);
Thanks in advance for any help.
A: The simplest way would be to use Kohana's built-in logger since it's already setup:
Kohana::$log->add(Log::ERROR, "your debug info")->write();
Otherwise, if you want to use a custom one, make sure you assign a writer to it - it can be file, database, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exposing the return of method into a property How can i expose the return of my method in to a class property?
public class BIContactLib: ContactLib
{
//Expose it here.. to replace the code below
public IEnumerable<BIContactLib> GetContactLibs
{
get { return (BIContactLib) GetAll}
set { ; }
}
}
public class BIContactLibService : IBIRequirement, IDisposable
{
private ClientContext context = new ClientContext();
//The return of the method here is the one I would like to expose
public IEnumerable<BIContactLib> GetAll()
{
var contactslib = context.ContactLibs;
return contactslib.ToList();
}
}
The reason behind this, is I want to create a view model with have the list of contacts library... heres my view model by the way..
public class PersonInformation
{
public BIPerson Person { get; set; }
public BIAddress Address { get; set; }
//This is where i want to use it
public IEnumerable<BIContactLib> GetAll { get; set; }
}
Or any other way to do this?
Best regards,
A: How about something like this
public IEnumerable<BIContactLib> GetContactLibs
{
get {
BiContractLib lib = new BiContractLib();
return lib.GetAll();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sending larger object to WCF results in 400 Bad Request I have a unit test that sends a moderately large object to a WCF service. If I pass null for that parameter, everything works fine. When I send a populated object, I get an HTTP 400 response.
WCF tracing shows this error:
The maximum message size quota for incoming messages (65536) has been
exceeded.
However, I have cranked up the size configuration parameters in app.config for the unit test project as follows:
<basicHttpBinding>
<binding name="BasicHttpBinding_IMyAppService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="200000000" maxBufferPoolSize="200000000" maxReceivedMessageSize="200000000"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/>
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
What am I missing in my configuration to raise the allowed message size above the 65536 seen in the error message?
UPDATE:
The web.config file for the web service host also sets the maxReceivedMessageSize to a large value (I think):
<binding name="basicHttpBindingConfig" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm"/>
</security>
</binding>
A: If I understand your question correctly, you increased the size for 'maxReceivedMessageSize' in the unit test's app.config. Actually you should make this change in the app.config/web.config of the web service which you are calling from your unit test code. If you host your web service in IIS, then it will be web.config. If you host it in windows service, then you need to make the change in the app.config (which gets moved to your .exe.config file in your bin folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can we add a inside an tag? Is it a proper method to use a <span> tag inside an <h1> tag?
<h1>
<span class="boardit">Portfolio</span>
</h1>
I know we can write it in this way...and am also following the below syntax in my own website..
<h1 class="boardit">
<span>Portfolio</span>
</h1>
However, I Just wanted to know the cleaner form of html..
A: Yes you can. It can be used to format a part of a h1 block:
<h1>Page <span class="highlight">Title</span></h1>
If the style applies to the entire h1 block, I do this:
<h1 class="highlight">Page Title</h1>
A: Yes, it's typically fine to use a span inside of an h1. span is an inline element, so it's typically okay to use it inside anything (that allows elements inside it!)
And there's not really a cleaner way to do it sometimes, say if you want to style only part of the h1.
On the other hand... don't do it if it's not necessary, as it is a little ugly : )
A: Yes you can.
HTML4 has this to say:
<!ENTITY % heading "H1|H2|H3|H4|H5|H6">
<!--
There are six levels of headings from H1 (the most important)
to H6 (the least important).
-->
<!ELEMENT (%heading;) - - (%inline;)* -- heading -->
And %inline; is:
<!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">
And %special; includes <span>.
The current HTML has this to say:
Content contents
Phrasing content
And Phrasing content includes <span>.
A: Yes that's fine, but why not
<h1 class="boardit">
Portfolio
</h1>
If thats all you're doing?
A: Yes, you can. The span displays inline, so it should not affect the styling of the H1.
A: Yes, we can use span tag with header tags and there is nothing wrong in it. Indeed this is widely used for styling header tags, specially for coloring a particular word or letter.
A: Yes, we can use span tag with header tags and there is nothing wrong in it. Indeed this is widely used for styling header tags, specially for coloring a particular word or letter.
A: <h1 style="display:inline;">Bold text goes here</h1>
<span style="display:inline;">normal text goes here</span>
Think in above lines - Worked for me - use display:inline prop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "109"
} |
Q: set my state with collection_select with pluginaweek/state_machine How do I create a collecton_select drop down to set the state of a resource in a form?
right now I have
<%= f.collection_select :state, Ticket.state.all, :event, :state_name_humanize, :prompt => true %>
(could pluginaweek make a 'getting started with state_machine' tutorial, I am really hot on using it, but I am a nube . . .)
A: From the example a collection select should look like this: <%= f.collection_select :access_state_event, @user.access_state_transitions, :event, :human_event, :include_blank => "don't change" %>
Would also like to see a simple example/tutorial for active record
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't Link up UIButton with File's Owner in XCode I started my intrepid journey into learning objective-c for ios, and got as far as trying to build my view in the interface builder, when I realized that I can't link up the buttons I'm creating to my File's Owner. I have made sure that my File's owner has my view controller selected, and have tried restarting xcode and the interface builder. Here's the contents of both my .h and .m files:
My CalculatorViewController.h file:
#import <UIKit/UIKit.h>
#import "CalculatorBrain.h"
@interface CalculatorViewController : UIViewController {
IBOutlet UILabel *display;
CalculatorBrain *brain;
}
- (IBAction):digitPressed:(UIButton *)sender;
- (IBAction):operationPressed:(UIButton *)sender;
@end
And the CalculatorViewController.m file:
#import "CalculatorViewController.h"
@implementation CalculatorViewController
- (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.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
In short, every time I click on a button in my Interface Builder View, hold CTRL, and drag the blue line over to "File's Owner," nothing happens. In the tutorial I'm watching (The Stanford Fall 2010 IOS tutorials, lesson 2 - if that helps) shows File's Owner highlighting and working like a champ. Any help would be much appreciated. Thanks!
A: Invalid definition of IBActions. (Extra colon)
Change
- (IBAction):digitPressed:(UIButton *)sender;
- (IBAction):operationPressed:(UIButton *)sender;
To
- (IBAction) digitPressed:(UIButton *)sender;
- (IBAction) operationPressed:(UIButton *)sender;
A: So you want to link up your button with an IBAction? Did I get this correct? You need to right click on the button, select the event (usually Touch Up Inside) and then drag (from the circle to the right of the event) to the Owner. Now if you want to hook something up to an IBOutlet (usually you do this with UITextField etc.) you will drag the File Owner over to the control and select the outlet from the popup.
A: #import "CalculatorViewController.h"
@implementation CalculatorViewController
- (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.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (IBAction):digitPressed:(UIButton *)sender{
}
- (IBAction):operationPressed:(UIButton *)sender{
}
- (void)dealloc {
[super dealloc];
}
@end
A: There should be no colon after - (IBAction)
A: 2 things:
There can't be any colon after - (IBAction)
Add this line to your code.
//.h file
IBOutlet UIButton *yourButtonName;
@property (nonatomic, retain)IBOutlet UIButton *yourButtonName;
/.m file
@synthesize yourButtonName;
Now drag it and you will done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does sql server compact still limit to 4gb I saw in forums that the limit for an SQL Server compact database is 4gb. Does anyone know if this limit has been increased yet, sql server express was recently expanded to 10GB..
Can anyone point me to the official source for this limit?
A: The limit for a SQL Server Compact database is 4GB.
Refs:
*
*Will the SQL Compact 4.0 limited to 4GB?
*Microsoft SQL Server Compact 4.0
*Wiki: SQL Server Compact
Surprisingly, it's not on this page listing differences between SQL Server Compact 3.5, compared with SQL Server.
Here are the maximum size limitations for several database objects defined in Microsoft SQL Server Compact 3.5 databases
Update (thanks @ErikEJ): Here is the corresponding page for SQL Server Compact 4.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Are there any legitimate reasons to hide static methods?
Possible Duplicate:
Why doesn't Java allow overriding of static methods?
Is there any legitimate reason why one would want a derived class to override hide a static method of the base class?
A: Terminology aside, static methods in Java do have a kind of overriding relation, implied by binary compatibility section 13.4.12. If T extends S, S declared m(), T.m() can refer to a method in T or S, depending on if m() is declared in T; and it's ok to add or remove m() from T, without breaking any code calling T.m(). (This implies JVM invokestatic instruction does a sort of dynamic method lookup up the super class chain)
However, this is nothing but trouble. It is really dangerous if the meaning of T.m() silently changes because now it's pointing to a different method. (Instance methods shall inherit contracts so that's not a problem; there's no such understanding in static methods.)
So this "feature" should never be used; the language shouldn't have enabled it to begin with.
The good practice: If we call T.m(), m() must be declared in T; and it should never be removed from T without removing all T.m() first.
A: Static methods cannot be overriden
In order to override a method, the method must first be inherited. If the method is not inherited there is no chance for overriding. Therefore, you can never override a private method as they are not inherited.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What is more useful when optimising for Eclipse PDT or PyDev - launcher.XXMaxPermSize or Xms,Xmx? I use Eclipse with PDT. Most optimization solutions mention increasing the Xms and Xmx values to enable Eclipse to handle more Java objects. I am curious about XXMaxPermSize. Increasing its value increased the memory the java process used.
For a non-Java IDE usage, which of these three (or all three) should be increased? My eclipse.ini file contents are as below:
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.100.v20110505
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
Update: The following is the updated eclipse.ini I am using.
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.100.v20110505
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
/usr/lib/jvm/java-6-openjdk/jre/bin/java
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms512m
-Xmx1024m
-XX:MaxPermSize=256m
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
A: For PDT or other non-Java development the size of these variables should be largely irrelevant as long as Eclipse itself is running fine (maybe regardless of that).
From the ini documentation page:
--launcher.XXMaxPermSize (Executable) If specified, and the executable detects that the VM being used is a Sun VM, then the
launcher will automatically add the -XX:MaxPermSize= vm
argument. The executable is not capable of detecting Sun VMs on all
platforms.
This blog post is also helpful, specifically mentioning the Xms Xmx are separate from PermGen space, the syntax requirement that args must be on separate lines (as you have above), and:
The best way to know if your command line arguments actually has been
passed in correctly is to go to Help/About [Product Name] and click
“Configuration Details” and check that the property “eclipse.vmargs”
contain the values you expected.
Finally, this page mentions which errors might be seen if the settings are too low:
1) Java.lang.OutOfMemoryError: Java heap space (The Xmx variable)
2) Java.lang.OutOfMemoryError: PermGen space (The XXMaxPermSize variable)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PreferenceActivity with TextItems I'd like to use PreferenceActivity for my games settings. But I'd like to add to that list, so that after the settings items in the list, there would be just text items like "MyGame, version 0.1" or clickable text item "Rate my app" etc.
What's the "correct" or most straighforward way of doing this? I know I can specify a custom layout xml with ListView in it and populate that with the preferences but I'd like to have my custom (clickable) text items in that ListView too, or atleast appear like they were in that list.
A: What I tried to tell was that I needed what is shown as "Costum Preference" [sic] in this picture:
(source: kaloer.com)
You can create it just by using
<Preference
android:title="Custom Preference"
android:summary="This works almost like a button"
android:key="customPref" />
This example I found from: http://www.kaloer.com/android-preferences
A: To put all setting to below XML file after that file use in the activity all setting are display in list.
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:example="http://schemas.android.com/apk/res/com.uks.android.frsad.common">
<EditTextPreference android:title="Server URL"
android:dialogTitle="Server URL Path" android:dialogMessage="Path of Web Server"
android:key="server_url_path" android:summary="Sets the Server URL Path for WebService." />
</PreferenceScreen>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Slicing objects in Python/Django question I want to retrieve the 13 latest objects, which shows this in my shell:
>>> last_13_issues = Issue.objects.order_by('-id').order_by('-pub_date')[:13]
>>> print last_13_issues
[<Issue: X-Men v2 #18>, <Issue: Uncanny X-Men #543>, **<Issue: Herc #7>**, <Issue: X-Men: Schism #4>, <Issue: X-Men v2 #17>, <Issue: X-Men First Class: The High Hand #1>, <Issue: Astonishing X-Men #41>, <Issue: X-Men v2 #16>, <Issue: Generation Hope #10>, <Issue: X-Men: Schism #3>, <Issue: Uncanny X-Men #542>, <Issue: X-Men: Schism #2>, <Issue: New Mutants v3 #28>]
Note Herc #7, which is marked with ** **.
In my template, I have a slider that shows the 3 latest objects, and then the rest of the objects not in a slider. So, I did this:
latest_appearances = Issue.objects.order_by('-id').order_by('-pub_date')[:3]
more_latest_appearances = Issue.objects.order_by('-id').order_by('-pub_date')[4:14]
latest_appearances shows this:
[<Issue: X-Men v2 #18>, <Issue: X-Men: Schism #4>, <Issue: Uncanny X-Men #543>]
more_latest_appearances shows this:
[<Issue: X-Men v2 #17>, <Issue: X-Men First Class: The High Hand #1>, <Issue: X-Men v2 #16>, <Issue: Astonishing X-Men #41>, <Issue: X-Men: Schism #3>, <Issue: Uncanny X-Men #542>, <Issue: Generation Hope #10>, <Issue: X-Men: Schism #2>, <Issue: New Mutants v3 #28>, <Issue: Secret Avengers #15>]
Notice that Herc #7 is gone. Now, since I have it ordered by -pub_date, 4 of the issues in last_13_issues have the same pub_date, so what can I do to fix this? I have made sure that 3 issues show the same pub_date, but that's obviously no help for when I have 4 issues with the same pub_date.
Ordering the issues only by id is no help either because sometimes I go back and add older issues, so sometimes issues with the highest id are not actually the latest issues.
Ok, odd. Case closed. I slice in the template, instead, and it works...which is weird that it doesn't work in the views. But if anyone can figure out why, kudos to you!
A: Use [3:] instead of [4:] for your more_latest_appearances.
End index is non-inclusive for slicing:
>>> "abcdef"[:3]
'abc'
>>> "abcdef"[4:]
'ef'
>>> "abcdef"[3:]
'def'
In order to clarify things more, I'd suggest rewriting your code a little to look like this:
appearances = Issue.objects.order_by('-id').order_by('-pub_date')
latest_appearances = appearances[:3]
more_latest_appearances = appearances[3:14]
This way, you only do a single query and then split the results up, rather than doing separate queries which might return the results in differing order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to extend jQuery's ajax This is rather a syntax question I am going to explain it jQuery's ajax functionality.
Let's say I want to control dataType of all ajax request according to url. For example url's with parameter &parseJSON=true should have a dataType of 'JSON' automatically.
For example:
$.myajax({url:'http://example.com&parseJSON=true'})
should be equivalent to
$.ajax({url:'http://example.com&parseJSON=true', dataType: 'JSON'})
Basically, I need to check for URL and add dataType parameter if needed.
Thanks
A: I think you can do this with a prefilter:
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
// Modify options
if ( !options.dataType && /parseJSON=true/.test(options.url) ) {
return "json";
}
});
I don't have an environment to test this at the moment.
Edit: Just to clarify, you would use ajax requests just like you do now, with $.get, $.post, and $.ajax, you just don't have to supply a dataType anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Managing changes in class structure to be consistent with mongodb collection We are using mongodb with c#. We are trying to figure out a way to keep our collection consistent seamlessly. Right now, if a developer make any changes to the class structure(add a field or change data type or changing the property within a nested class) he/she has to change the mongo collection manually.
Its a pain as our project is growing and the developers working on the project keeps increasing. Was wondering whether someone already have figured out a way to manage this issue.
*
*Research
*
*I found a similar question. however, couldn't find the solution.
*Found a way to find all properties Finding the properties; however, datatype and nested documents becomes an issue.
A: If you want to migrate gradually as records are accessed you need to follow a few simple rules:
1) If you add a field it had better be nullable or have a default value specified.
2) Never rename fields, never change field types
- Instead always add new fields, add migration code, remove the old fields only when all documents have been migrated over.
For prototyping with MongoDB and C# I build a dynamic wrapper ... that lets you specify your objects using only interfaces (no classes needed), and it lets you dynamically add new interfaces to an existing object. Not ready for production use but for prototyping it saves a lot of effort and makes migration really easy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Installing pymake? There dont seem to be any instructions on how to build this sucker. Downloaded from http://benjamin.smedbergs.us/pymake/
The usual files are not in the top directory - make.py and mkparse.py. neither of them seem to do much.. seems like it needs a makefile, but there isn't one in any part of the distro..
> python make.py build
make.py[0]: Entering directory '/Users/ron/lib/pymake-default'
No makefile found
any hints?
A: pymake is a make utility, and running make.py looks for a Makefile (that you've created, for your own project). There's no build step specifically required for pymake itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Problem with jquery .submit() and variables I am not sure what to do and why it is not working it is my first attempt at something like this.
Here is a fiddle of it http://jsfiddle.net/ProjectV1/LVPtN/
You will notice in javascript I have a var error which is by default false.
If there is an error it is true.
I have displayed the value of error next to each input on my form.
If the variable error is false it should submit the form and false it shouldn't.
The problem arises when an error occurs, and is then corrected the form will not submit.
Look at the fiddle. The form directs to google just for testing.
A: I think, the issue is with the error being inside the function which will be called on blur. And when the function call is done, it goes undefined. The deal is that the variable should be global. You will need to put this above the $(document).ready() This should work:
var error = false;
$('#joinForm input').blur(function() {
var id = $(this).attr('id');
var val = $(this).val();
if (id == 'email') {
$('#emailMsg').hide();
if (val == '') {
error = true;
$('#' + id).after('<div id="emailMsg" class="error">' + error + '</div>');
}
else {
$('#' + id).after('<div id="emailMsg" class="success">' + error + '</div>');
}
}
if (id == 'cemail') {
$('#cemailMsg').hide();
}
if (id == 'password') {
$('#passwordMsg').hide();
if (val == '') {
error = true;
$('#' + id).after('<div id="passwordMsg" class="error">' + error + '</div>');
}
else {
$('#' + id).after('<div id="passwordMsg" class="success">' + error + '</div>');
}
}
if (id == 'cpassword') {
$('#cpasswordMsg').hide();
}
if (id == 'username') {
$('#usernameMsg').hide();
if (val == '') {
error = true;
$('#' + id).after('<div id="usernameMsg" class="error">' + error + '</div>');
}
else {
$('#' + id).after('<div id="usernameMsg" class="success">' + error + '</div>');
}
}
$('#joinForm').submit(function(){
if (error == true) {
return false;
}
else {
return true;
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Proper way to refer to "this" view callback handlers (success or error) after save in Backbone JS I am trying to refer to the view element via $(this.el) within a success or error callback on a Backbone model.
Example:
From within SomeViewClass (which extends Backbone.View),
@model.save({}, {
success: (model, response) ->
($ this.el).removeClass("editing")
})
However, I'm stuck at the fact that "this" doesn't refer to the SomeViewClass instance. Any ideas?
A: Since you're using CoffeeScript, you can use a fat arrow (=>) to bind the current value of this to your function:
@model.save({}, {
success: (model, response) =>
($ this.el).removeClass("editing")
})
If you were working in plain JavaScript, you'd usually use the standard var self = this; trick:
var self = this;
model.save({ }, {
success: function(model, response) {
$(self.el).removeClass("editing");
}
});
Or, since you're using backbone.js (which requires underscore.js), you could use _.bind to build your bound function.
If your callback was bigger or you wanted to use the same callback in multiple places, then _.bindAll would be an option. You'd have to make the callback a named method though; but, if the callback was large you'd probably want to un-inline it anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jquery change & validation We have a jquery autocomplete input box:
<input name="suburb" id="suburb-agency" autocomplete="off" class="text" type="text" value="">
This drops down, and when they choose an option, another select box is updated depending on what was chosen:
<select class="text" name="state" id="state-agency">
<option value="notselected">Please select your state...</option>
<option value="Apple">Apple</option>
<option value="Pear">Pear</option>
</select>
Say for example they choose Pear in the #suburb-agency autocomplete, Pear is then selected automatically in #state-agency
That works perfectly.
The only problem I am having is jquery validation, when Pear is selected and the #state-agency box is changed, the validation doesn't show, although it does if I manually select an option from the drop down box.
Here is my jquery:
/* STATE VALIDATION */
$("#state-agency").change(function () {
var state = $('#state-agency').val();
if (state == "notselected"){
$('#state-agency').css({"border-color":"#3399ff"});
$('#state-err').html("You must choose which state you work in.").removeClass("success_msg").addClass("error_msg");
return false;
}else{
$('#state-agency').css({"border-color":"#1f6d21"});
$('#state-err').html("Thanks for choosing your state!").removeClass("error_msg").addClass("success_msg");
}
});
How can I modify this so it shows the success message if it is selected from the autocomplete? and not just manually? I'm guessing I need to change from a change function?
Edit (our autocomplete code which updates the dropdown box as requested)
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split(term).pop();
}
$( "#suburb-agency" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "http://www.site.com/folder/script.php", {
term : extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
if (ui.item) {
$('#state-agency').val(ui.item.state);
}
else {
$('#state-agency').val('');
}
}
});
});
A: If you are using jQuery validation, to perform validation of input element after you updated it, you need to call
$(selector).valid()
A: I've found a fix for this, I needed to use trigger() on the relevent IDs in the autocomplete JS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to sort the array that contains dates in iphone sdk I have an array that contains date strings like
"9/15/2011 12:00:00 AM", "10/15/2011 12:00:00 AM", "11/16/2011 12:00:00 AM"
How can I sort this array in descending order?
The order should be, sort by year first, then, month, then date and then time.
Please share your ideas.
Thank you
A: Sorting NSDates while they are in NSString format is almost not possible, except if they are in the format "YYYYMMddHHmmss" which you can sort as sorting strings. Refer @Daniel R Hicks answer.
Convert the string into NSDate while you parse and add the dates from web service.
NSString *dateStr = ...
NSDateFormatter *df = ;[NSDateFormatter alloc] init];
[df setDateFormat:@"M/dd/YYYY hh:mm:ss a"];
[datesArray addObject:[df dateFromString:dateStr]];
And the sorting,
[datesArray sortUsingSelector:@selector(compare:)];
And the original answer is here!
A: try belowed listed code. it will give sort date in ascending order.
NSMutableArray *arraydate=[[NSMutableArray alloc] init];
[arraydate addObject:@"22/7/2010"];
[arraydate addObject:@"1/1/1988"];
[arraydate addObject:@"22/7/1966"];
[arraydate addObject:@"22/7/2000"];
[arraydate addObject:@"1/7/2010"];
[arraydate sortUsingSelector:@selector(compare:)];
NSLog(@"array=%@",[arraydate description]);
A: If they're already strings you can either convert them to NSDates (and hence to NSTimeIntervals) and sort those, or effectively rearrange the digits to YYMMDDHHmmss, where HH has been converted to 00-23 representation.
Either can be done by using a sortUsingFunction call.
A: static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
NSArray *sortArray = [iArray sortedArrayUsingComparator:^(id string1, id string2) {
NSRange string1Range = NSMakeRange(0, [string1 length]);
//if([string2 isEqualToString:@"#"])
//return -1;
return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
}];
return sortArray;
A: There is a method for comparing two dates.
int interval = [date1 compare:date2];
if (interval == 1)
{
NSLog(@"Right hand side date is earlier");
}
else if (interval == -1)
{
NSLog(@"Left hand side date is earlier");
}
else
{
NSLog(@"Both Dates are equal");
}
you can use this method but make sure that your date1 and date2 are NSDate objects and after comparing them you can use bubble sorting method along with it to sort the array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7524240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.