text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Custom Registrations Controller for Devise not Overriding Create Action I have been fighting with this for days now. I have created my own Registrations Controller to allow for an amdin to create and delete users. I have left the :registerable module in my devise configuration, as I also want to users to be able to edit their profiles. I have tried taking that module out just to see if it would solve my issue. The problem that I have, is that when I create a new user as an admin, it still signs that user in, despite having my own create action. I have tried everything that I can think of to get beyond this and I am stuck.
My Registrations Controller:
class RegistrationsController < Devise::RegistrationsController
load_and_authorize_resource
def new
super
end
def create
resource.build
if resource.save
redirect_to users_path
else
clean_up_passwords(resource)
render_with_scope :new
end
end
end
Application Controller: => note, after_sign_up_path_for was overriden here as a test to see if that would work
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = exception.message
redirect_to projects_url
end
protected
def stored_location_for(resource)
nil
end
def after_sign_in_path_for(resource)
projects_url
end
def after_sign_up_path_for(resource)
users_path
end
end
Routes File:
DeviseTest::Application.routes.draw do
devise_for :users, :controller => { :registrations => "registrations"}
devise_scope :user do
get '/login' => 'devise/sessions#new'
get '/logout' => 'devise/sessions#destroy'
end
resources :users, :controller => "users"
resources :projects
root :to => 'home#index'
end
And my Users Controller for admin view
class UsersController < ApplicationController
load_and_authorize_resource
# GET /users
# GET /users.xml
def index
@users = User.excludes( :id => current_user.id )
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end
# DELETE /users/1
# DELETE /users/1.xml
def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to(users_url) }
format.xml { head :ok }
end
end
end
Rake Routes Output:
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 DELETE /users/sign_out(.:format) {:action=>"destroy", :controller=>"devise/sessions"}
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=>"devise/registrations"}
user_registration POST /users(.:format) {:action=>"create", :controller=>"devise/registrations"}
new_user_registration GET /users/sign_up(.:format) {:action=>"new", :controller=>"devise/registrations"}
edit_user_registration GET /users/edit(.:format) {:action=>"edit", :controller=>"devise/registrations"}
PUT /users(.:format) {:action=>"update", :controller=>"devise/registrations"}
DELETE /users(.:format) {:action=>"destroy", :controller=>"devise/registrations"}
login GET /login(.:format) {:controller=>"devise/sessions", :action=>"new"}
logout GET /logout(.:format) {:controller=>"devise/sessions", :action=>"destroy"}
users GET /users(.:format) {:action=>"index", :controller=>"users"}
POST /users(.:format) {:action=>"create", :controller=>"users"}
new_user GET /users/new(.:format) {:action=>"new", :controller=>"users"}
edit_user GET /users/:id/edit(.:format) {:action=>"edit", :controller=>"users"}
user GET /users/:id(.:format) {:action=>"show", :controller=>"users"}
PUT /users/:id(.:format) {:action=>"update", :controller=>"users"}
DELETE /users/:id(.:format) {:action=>"destroy", :controller=>"users"}
projects GET /projects(.:format) {:action=>"index", :controller=>"projects"}
POST /projects(.:format) {:action=>"create", :controller=>"projects"}
new_project GET /projects/new(.:format) {:action=>"new", :controller=>"projects"}
edit_project GET /projects/:id/edit(.:format) {:action=>"edit", :controller=>"projects"}
project GET /projects/:id(.:format) {:action=>"show", :controller=>"projects"}
PUT /projects/:id(.:format) {:action=>"update", :controller=>"projects"}
DELETE /projects/:id(.:format) {:action=>"destroy", :controller=>"projects"}
root /(.:format) {:controller=>"home", :action=>"index"}
Everything else works as expected, I just cannot get the created user to not be signed in. It's not a huge issue for creating one user, but if I need to create 3 or 4, it's a huge p.i.t.a to have to signout, signin, every single time.
Any help on this is greatly appreciated.
A: On the third line of your routes.rb file, I think you mean :controllers => …, not :controller => …. You're missing an 's'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: zombie.js browser.fire not working with Backbone.Events The browser.fire method does not seem to trigger event handlers attached through Backbone.Events. (it works fine for other cases such as clicking anchor tags/buttons)
See this gist for a test case on documentClouds site:
https://gist.github.com/1256944
If the first thing you do when going to the url is click the 'Open' button you get an alert, but also the 'overlay' class is added to the body element - this is what im checking for.
You can see from the test that when using browser.fire 'click', that the prompt isn't shown, and the overlay class is not seen.
However, when triggering the click event using jQuery's click() method (via browser.evaluate), then the overlay class is seen...
A: In your backbone view, you should add the el property. Specify an element upon which the events should be bound. For example:
dc.ui.Toolbar = Backbone.View.extend({
id : 'toolbar',
el : "body",
events : {
'click #open_viewers' : '_clickOpenViewers',
'click #size_toggle' : '_toggleSize'
},
_clickOpenViewers : function() {
this.openViewers();
},
openViewers : function(checkEdit, suffix, afterLoad) {
if (!Documents.selectedCount) return dc.ui.Dialog.alert('Please select a document to open.');
var continuation = function(docs) {
_.each(docs, function(doc){
var win = doc.openAppropriateVersion(suffix);
if (afterLoad) {
win.DV || (win.DV = {});
win.DV.afterLoad = afterLoad;
}
});
};
checkEdit ? this.edit(continuation) : continuation(Documents.selected());
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: why a "char*" can point to a "const char*"? the following code can be compiled correctly on both VC or gcc:
char *str = "I am a const!";
str[2] = 'n';
however, obviously there is a run-time-error. Since "I am a const!" is a const char*, why the compiler doesn't give an error or even a warning ??
Besides, if I define char a[] = "I am const!", all the elements in a can be modified, why this time the string literals become nonconst ?
A: As far as C is concerned, that string literal is not const, it's a char[14] which you assign to a char*, which is perfectly fine.
However, C does say that changing a string literal is undefined behavior.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Where is parseRoutesNoCheck in Yesod I started to learn Haskell language and Yesod web framework.
When I tried to use "parseRoutesNoCheck" for mkYesod, however, the compiler could not match the return type (Resource) of parseRoutesNoCheck.
$ ghc simple_yesod.hs
[1 of 1] Compiling Main ( simple_yesod.hs, simple_yesod.o )
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Loading package bytestring-0.9.1.10 ... linking ... done.
Loading package array-0.3.0.2 ... linking ... done.
Loading package containers-0.4.0.0 ... linking ... done.
Loading package deepseq-1.1.0.2 ... linking ... done.
Loading package text-0.11.0.6 ... linking ... done.
Loading package path-pieces-0.0.0 ... linking ... done.
Loading package pretty-1.0.1.2 ... linking ... done.
Loading package template-haskell ... linking ... done.
Loading package web-routes-quasi-0.7.1 ... linking ... done.
simple_yesod.hs:9:36:
Couldn't match expected type `yesod-core-0.9.2:Yesod.Internal.RouteParsing.Resource'
with actual type `Resource'
In the return type of a call of `Resource'
In the expression:
Resource "PageR" [StaticPiece "page", SinglePiece "String"] ["GET"]
In the second argument of `mkYesod', namely
`[Resource
"PageR" [StaticPiece "page", SinglePiece "String"] ["GET"],
Resource
"UserR" [StaticPiece "user", SinglePiece "String"] ["GET"]]'
It seems that I'm using wrong parseRoutesNoCheck, but where is the correct Module?
simple_yesod.hs is below.
{-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-}
import Yesod
import Web.Routes.Quasi.Parse
import qualified Text.Blaze.Html5 as H
data Test = Test {
}
mkYesod "Test" [parseRoutesNoCheck|
/page/#String PageR GET
/user/#String UserR GET
|]
instance Yesod Test where
approot _ = ""
defaultLayout widget = do
content <- widgetToPageContent widget
hamletToRepHtml [hamlet|
\<!DOCTYPE html>
<html>
<head>
<title>#{pageTitle content}
<body>
<ul id="navbar">
<div id="content">
\^{pageBody content}
|]
getUserR :: String -> Handler RepHtml
getUserR userName = defaultLayout
(do
setTitle $ H.toHtml $ "Hello " ++ userName
addHamlet $ html userName
)
where
html page = [hamlet|
<h1>User: #{userName}
<p>This page is for user: #{userName}
|]
getPageR :: String -> Handler RepHtml
getPageR pageName = defaultLayout
(do
setTitle $ H.toHtml $ "Article: " ++ pageName
addHamlet $ html pageName
)
where
html page = [hamlet|
<h1>Page: #{pageName}
<p>This page is for page: #{pageName}
|]
main :: IO ()
main = do
warpDebug 3000 $ Test
I'm using Glasgow Haskell Compiler, Version 7.0.3 and yesod-core-0.9.2.
A: You should simply use parseRoutes rather than parseRoutesNoCheck. Also you might want to add a module Main where and remove import Web.Routes.Quasi.Parse since the Yesod module already exports parseRoutes.
Here is the complete code with the modifications I mentioned.
{-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-}
module Main where
import Yesod
import qualified Text.Blaze.Html5 as H
data Test = Test {
}
mkYesod "Test" [parseRoutes|
/page/#String PageR GET
/user/#String UserR GET
|]
instance Yesod Test where
approot _ = ""
defaultLayout widget = do
content <- widgetToPageContent widget
hamletToRepHtml [hamlet|
\<!DOCTYPE html>
<html>
<head>
<title>#{pageTitle content}
<body>
<ul id="navbar">
<div id="content">
\^{pageBody content}
|]
getUserR :: String -> Handler RepHtml
getUserR userName = defaultLayout
(do
setTitle $ H.toHtml $ "Hello " ++ userName
addHamlet $ html userName
)
where
html page = [hamlet|
<h1>User: #{userName}
<p>This page is for user: #{userName}
|]
getPageR :: String -> Handler RepHtml
getPageR pageName = defaultLayout
(do
setTitle $ H.toHtml $ "Article: " ++ pageName
addHamlet $ html pageName
)
where
html page = [hamlet|
<h1>Page: #{pageName}
A good idea is to try to copy existing examples when you're in the learning phase of Yesod (and everything else for that matter). Code snippets are often found in the Yesod book or in github repos, one can learn from those sources.
Edit: I lack a complete answer. Apperently nowadays the parseRoutes and family lies in "Yesod.Dispatch" which only is reexporting from the hidden module Yesod.Internal.RouteParsing. parseRoutesNoCheck is defined in Yesod.Internal.RouteParsing but never exposed, since you probably always want checking of non-overlapping routes.
I hope this clarifies a bit more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Grammars - RegEx I am trying to construct a regular expression that the total number of a's is divisible by 3 no matter how they are distributed. aabaabbaba. This is What i came up with:
b*ab*ab*
Now, someone told me i could do it this way
(b*ab*ab*)*
Why would i need to enclose it and why is the outside kleene star needed?
Wouldnt the outside kleene distribute among all the a's and b's inside the parenthesis? if thats the case then what would a double kleene mean?
A: For the number of 'a's to be divisible by three, you'll need three 'a's in your expression. So the correct expression is:
(b*ab*ab*ab*)*
This expression is saying 'a' three times, with possible 'b's in the middle. The last star says repeat (the whole parenthesized expression) as necessary.
A: The outer * repeats the entire sequence zero or more times.
In other words, zero or more substrings that match b*ab*ab*.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails, dynamic emails sent do different email address on staging server So for static email in the system, I have a staging environment config setup which works well.
With dynamic emails, I have this code in my mailer.rb file.
if RAILS_ENV == 'staging'
recipients STAGING_TEST_EMAIL
else
recipients request[:email]
end
This works, I just wanted to know if there was a tidier or better way to do this or if this is OK in terms of best practice.
A: One option, is to modify the staging servers mailing gem..
IE...
def email.press_send
recipients STAGING_TEST_EMAIL
end
My personal favorite...
is to talk to the sys admin and arrange for email sent from the staging, test, box directly into a file, so then you can view it.
ie, all email sent out is sent to this user "test_email", who has this .forward "| cat >> /tmp/new_mail.txt"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the date format of a string Is there a way (an elegant way that is) to extract a date format from a string containing a date so that it may be converted into an NSDate via NSDateFormatter?
i.e
string = @"2011-1-10";
format = [extractor extractFormat:string];// format would = yyyy-dd-mm
[formatter setDateFormatter:format];
NSDate * date = [formatter dateFromString:string];
A: If that is the only information you have then it is impossible. For example, "10-10-10".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Masking signal when global variables are being updated I am aware that i can mask a signal from being raised when handler is executing (by using sa_mask). However, i would like to know how to mask a signal when i am updating some global variables.
Also, i would like to know how to mask a signal when a particular user defined function is executing.
Is it possible to do these 2 things?
Any help will be appreciated
Thanks
A: You can call "signal()" any time you want; either to a) set the signal handler to some custom code, or b) clear it by setting the handler argument to NULL.
sigaction(), of course, gives you even finer-grained control. You can call sigaction whenever you wish (for example, before updating your global variables), too.
This link might help:
http://www.linuxjournal.com/article/6483
A: It's possible to block signals with sigblock(). Signals blocked will be queued and released when the signal is unblocked.
HOWEVER - this is super expensive. You have to do a syscall to block and a syscall to unblock. This can be quite slow if you do it often. So there are some alternative approaches:
*
*If you're on linux, use signalfd. You can block all signals once and redirect them to a file descriptor, then handle them whenever it's safe to do so.
*Otherwise (or if async signal handling is important), you can defer signals in userspace. Before entering your critical section, set a volatile flag. In your signal handler, check for this flag; if you see it, write() to a pipe the signal number and immediately return. In your signal handler, check back for a signal on this pipe, and re-raise the signal at that point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ExpandableListAdapter add/delete group I need to be able to create and delete groups in my expandableListAdapter dynamically. I have looked through all that I can find and am stuck. I do not need specific code, but just to be pointed in the right direction.
A: First, we need some data structures (keep a reference to them for later use).
headerData = new ArrayList<HashMap<String, String>>();
childData = new ArrayList<ArrayList<HashMap<String, Object>>>();
headerData is the list of groups - HashMap is used since each group can have multiple display values, each of which is mapped onto the layout by key.
childData is the list of items belonging to each group. Its a list of lists, each containing HashMaps - similar to the groups, each child can have multiple display values which are mapped by key.
We supply these datastructures to our ExpandableListAdapter on creation. We're also telling the adapter how the display values should be mapped; in this example both groups and children have two display values, keys "name" and "fields" which are mapped onto text1 and text2 in the supplied layouts.
adapter = new SimpleExpandableListAdapter( SearchLogs.this,
headerData, R.layout.customlayout_group,
new String[] { "name", "fields" }, new int[] { R.id.text1, R.id.text2 },
childData, R.layout.customlayout_child,
new String[] { "name", "fields" }, new int[] { R.id.text1, R.id.text2 } );
setListAdapter(adapter); // assuming you are using ExpandableListActivity
Up to this point we have an empty ExpandableList. We can populate it dynamically (using an AsyncTask for example) by creating HashMaps that supply values for keys we are using and then adding them to our lists.
For example, to add a group with a couple children we might ...
HashMap<String, String> group = new HashMap<String, String>();
group.put("name", "whatever...");
group.put("fields", "...");
ArrayList<HashMap<String, Object>> groupChildren = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> child1 = new HashMap<String, Object>();
child1.put("name", "child name");
child1.put("fields", "...");
HashMap<String, Object> child2 = new HashMap<String, Object>();
child2.put("name", "another child");
groupChildren.add(child1);
groupChildren.add(child2);
headerData.add(group);
childData.add(groupChildren);
Each HashMap in headerData corresponds (by order) to an ArrayList in childData, which contains additional HashMaps that define the actual children. SO even if you are adding an empty group, remember to add a corresponding (empty) ArrayList to childData.
We just added a group to the end of the list - we can just as easily insert as long as we are mindful to insert into the same position in both headerData and childData. Removing groups is the same - be certain to remove from the same position of both headerData and childData.
Finally, notify the adapter that the data has changed, which will cause the List to refresh. If using an AsyncTask, this must be done outside of doInBackground (use onProgressUpdate in this case).
adapter.notifyDataSetChanged();
I hope this helps you move in the right direction. ExpandableList, in terms of how data is stored, is definitely one of the more complicated Android views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Thottle PHP script from json Facebook api feed I have a script that runs in the background over facebook api using json_decode however it is bogging down my server to the point where i cannot connect. I am having it loop over all the tags in side my own personal photo album. Is there a way i can limit the connections/decodes/etc so that my server does not die?
A: Run it on a separate server, and then feed the data into your database.
You may want to look at php-resque (YMMV), I haven't used php and resque...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get an ID from database into the ListView I learn work with Android. I started to create a project with Contacts.
I insert contacts into the SQLite database and then I put them from the database and show them in ListView. Thats OK. But I would like to click on an item in the List and then to edit the item. Therefore I need to get somehow the ID of the item and work with it...I do not know if it is clear...As you can see, in the function onItemClick() , there is running a new activity ...and in the new activity, I need the ID of the item in order to work with it.
public class ContactList extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seznam_kontaktu2);
SQLInsert info = new SQLInsert(this);
info.open();
ArrayList<String> data = info.getDataArrayList(); //It returns Array of "Lastname, Name" which is shown in the List
info.close();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
});
}
A: One option that has worked for me is to create a custom ArrayAdapter class along with a custom AdapterItem class. We store the id on our AdapterItem, and return it using our custom ArrayAdapter.
MyAdapterItem might look something like ...
public class MyAdapterItem implements Comparable
{
public String name;
public long rowId;
public MyAdapterItem()
{
rowId = -1L;
name = "";
}
public MyAdapterItem(long _rowId, String _name)
{
rowId = _rowId;
name = _name;
}
public int compareTo( Object o )
{
return toString().compareTo(o.toString());
}
public String toString()
{
return name;
}
}
Our custom ArrayAdapter, MyAdapter, then overrides getItemId(). It reads and returns the stored row id (making the assumption it is working with elements of MyAdapterItem). The other methods on ArrayAdapter will continue to work with our custom class - the toString method is used by the list for display purposes, and by providing a compareTo method the list knows how to sort the values.
public class MyAdapter<MyAdapterItem> extends ArrayAdapter
{
public MyAdapter(Context context, int resourceId)
{
super(context, resourceId);
}
@Override
public long getItemId( int position )
{
MyAdapterItem item = (MyAdapterItem)this.getItem(position);
return item.rowId;
}
}
Back in your Activity's onCreate the OnItemClickListener now provides the correct row id in the "id" parameter.
What is not shown is the new implementation of info.getDataArrayList() - it must be modified to create new MyAdapterItem objects instead of simple Strings.
ArrayList<MyAdapterItem> data = info.getDataArrayList();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter( new MyAdapter<MyAdapterItem>(this, android.R.layout.simple_list_item_1, data) );
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
// do whatever - the value in "id" is supplied by getRowId on our adapter
}
});
Also, if you attach a context menu to your ListView, the MenuItem objects passed into your Activity's onContextItemSelected method will also return the correct row id.
@Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long rowId = info.id;
// do something with the id
}
A: public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
hi i dont know what are the column names of your application.but for example id is your primary key identifier then move cursor to arg2 postion and get the value of _id and then pass it to startActivity and it will work.first thing apply SQLiteOpenHelper class its easy for use then apply this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to debug error: *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] I have a simple UITableviewController that used to work fine and now something has broken it..
It presents a simple form that allows me to add a simple 3-field record to a core-data managed object.
When I add a record, it should return to the table and display the contents. I can see that it is writing the record to the database but the table is empty and the error below appears. I can keep adding records by clicking on my "Add" button but each time I save the new record and return to the table, it is empty.
The complete error I see is this..
*** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:5678
2011-10-01 22:48:11.860 Gradetrack[59617:207] Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath: with userInfo (null)
If I stop the simulator and restart it, I can see from my NSLog statements that it has discovered the right number of records from the database and has tried to load the table but at this point, I get this similar error and the stack trace below.
2011-10-01 23:08:50.332 Gradetrack[59795:207] >>> Enumber of courses entered thus far: 4
2011-10-01 23:08:50.334 Gradetrack[59795:207] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:5678
2011-10-01 23:08:50.337 Gradetrack[59795:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** Call stack at first throw:
(
0 CoreFoundation 0x00fd05a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x01124313 objc_exception_throw + 44
2 CoreFoundation 0x00f88ef8 +[NSException raise:format:arguments:] + 136
3 Foundation 0x000e43bb -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
4 UIKit 0x0035ec91 -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 883
5 UIKit 0x003544cc -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
6 UIKit 0x003698cc -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
7 UIKit 0x0036190c -[UITableView layoutSubviews] + 242
8 QuartzCore 0x01f70a5a -[CALayer layoutSublayers] + 181
9 QuartzCore 0x01f72ddc CALayerLayoutIfNeeded + 220
10 QuartzCore 0x01f180b4 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
11 QuartzCore 0x01f19294 _ZN2CA11Transaction6commitEv + 292
12 UIKit 0x002eb9c9 -[UIApplication _reportAppLaunchFinished] + 39
13 UIKit 0x002ebe83 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 690
14 UIKit 0x002f6617 -[UIApplication handleEvent:withNewEvent:] + 1533
15 UIKit 0x002eeabf -[UIApplication sendEvent:] + 71
16 UIKit 0x002f3f2e _UIApplicationHandleEvent + 7576
17 GraphicsServices 0x01928992 PurpleEventCallback + 1550
18 CoreFoundation 0x00fb1944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
19 CoreFoundation 0x00f11cf7 __CFRunLoopDoSource1 + 215
20 CoreFoundation 0x00f0ef83 __CFRunLoopRun + 979
21 CoreFoundation 0x00f0e840 CFRunLoopRunSpecific + 208
22 CoreFoundation 0x00f0e761 CFRunLoopRunInMode + 97
23 UIKit 0x002eb7d2 -[UIApplication _run] + 623
24 UIKit 0x002f7c93 UIApplicationMain + 1160
25 Gradetrack 0x00002034 main + 102
26 Gradetrack 0x00001fc5 start + 53
Based on NSLog statements, this is the last subroutine executed.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
NSLog(@">>> Enteringg %s [Line %d] ", __PRETTY_FUNCTION__, __LINE__);
id <NSFetchedResultsSectionInfo> sectionInfo =
[[_fetchedResultsController sections] objectAtIndex:section];
NSLog(@">>> Enumber of courses entered thus far: %d ", [sectionInfo numberOfObjects]);
return [sectionInfo numberOfObjects];
}
Note: the output from the Number of courses entered thus far... was 4, which was correct.
Here is where I return cells back to the UITableViewController
- (UITableViewCell *)tableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
NSLog(@">>> Entering %s [Line %d] ", __PRETTY_FUNCTION__, __LINE__);
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
[tableView setAllowsSelectionDuringEditing:NO];
[self configureCell:cell atIndexPath:indexPath];
// load the cell with an appropriate image
NSString *path = [[NSBundle mainBundle] pathForResource:@"studentprofile" ofType:@"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
return cell;
}
Based on these errors and my stack trace, can anyone point me in the right direction?
Many thanks,
Phil
A: Ok, sorry, SNAFU alert.
I'm not sure how this occurred but if you notice in my function declaration for "cellForRowAtIndexPath"... it just has atIndexPath instead of cellForRowAtIndexPath. I must have done some sort of ill advised global search and replace and it wrecked my project.
Working now. Thanks.
Question - why would the code compile without error or warning - Wow - this took way too long to find.
A: Based upon UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:, it looks like you might have forgotten to set a cell identifier upon instantiation:
cell = ((DetailCell *)[tableView dequeueReusableCellWithIdentifier:DetailCellIdentifier]);
if (! cell)
{
// build the cell here
}
If not, where in the code is the error being caused?
A: I just ran into the same issue, but I carelessly declared:
<UITableViewDelegate, UITableViewDelegate>
rather than correctly:
<UITableViewDelegate, UITableViewDataSource>
Joe
*update - I have also noticed in xCode 4.3 the template generated when you create a new UITableViewController Class is missing a key item in cellForRowAtIndexPath. That is:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
A: In my case, iOS 5.0 ~ 6.0 with storyboard should have same cell identifier between the method
(- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath) and **storyboard file**.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell"; ... }
If you used @"Cell" for cell identifier, should use the name at the Identifier of corresponding tableViewCell in attributes inspector of storyboard file.
When you make a subclass of UITableView file, the default code uses @"Cell", but not storyboard, blank. So need to pay attention.
A: One of the very common reason for this error is that in the nib file, the top level UI view must be of type UITableViewCell and if that is not the case, it throws this assertion error.
A: I got this exception when I accidentally deleted return cell in tableView:cellForRowAtIndexPath:. This exception is raised when no cell is created or returned.
A: I just wrestled with this assert for a few hours. I was trying to add a UIButton as a subview in the cell that was also in the nib. Apparently "Autolayout" doesn't like this, so after un-checking the option in my nib, I no longer receive the crash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How can I implement a publish/subscribe system (server-push) with AKKA in Java? As I'm getting familiar with http://akka.io/, I can't figure out how to do server-push.
After a client connects to a server, how can the server push messages to the client? For example, if a client subscribed to receive stock quotes from a quote server. Or if the server routes chat messages from one chat client to another.
WRONG IDEA: I realize that the client can pass a message to the server with the client's IP/port and then the server can initiate a new connection back to the client and push messages. This won't work, since the client could be behind firewall. The server needs to send messages back to the client over the socket connection that the client initiated.
The AKKA documentation isn't helpful, and my google searches have not been fruitful.
Anyone figure out how to do this?
A: A handful of solutions, if you'd like to make your life more difficult but oh so geeky.
Well, I've been thinking for a bit on how finagle and akka will intertwine. There's some overlap, but my feeling is that while Akka is much richer for writing application logic, as a service glue/communications layer it's lacking, in part because of the need to work everything into the actor model. I see finagle as node.js on steroids (or at least with static typing :) More specifically, finagle looks to be a great framework for handling layer 5 to low layer 7.
If finagle gains any traction, I would think apis around web sockets will grow to mirror what was done with socket.io for node.js, but it looks to be straightforward. I'm looking for an excuse to do this myself :)
Anyway, if you were careful about how you adapted to the actor model, you could stay entirely in Scala.
But as Viktor suggested you should think about using websockets (which I'm 99% sure that Lift would help you with), Comet if going over http. More generally webhooks is a nice style for pub sub on the web, though obviously even that will require the firewalls to accept incoming connections.
Personally I've been wishing for a couple years that Mark Nottingham's brilliantly elegant Cache Channels to do pub sub just using http to become a standard, but one could create a decent approximation if you controlled both client and server code.
A: Akka 2.0 will support reusing the inbound channel for outbound messages, which will give you what you request, until then you'll need to either accept that it doesn't work well with firewalls or just use another transport, Comet, WebSockets or perhaps Camel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: make a frame with components visible only when needed in android Well what i wanted to do was create an initial layout which will have a toggle button and on clicking the toggle but it should make a frame visible which will have a few buttons or textviews.
Does anybody know how to do this in Android 2.2??
A: If you're developing for Android 3.0+, look into fragments.
A: You can use the visibility attribute on a view to control whether it is visible or not. Here's a small example that should do what you're looking for.
The main Activity:
public class DynamicLayoutTestActivity extends Activity {
private ToggleButton toggleButton;
private View possiblyHiddenView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
possiblyHiddenView = (View) findViewById(R.id.possiblyHiddenView);
toggleButton.setOnCheckedChangeListener(toggleButtonOnCheckedChangeListener);
}
private final CompoundButton.OnCheckedChangeListener toggleButtonOnCheckedChangeListener
= new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
possiblyHiddenView.setVisibility(View.VISIBLE);
} else {
possiblyHiddenView.setVisibility(View.INVISIBLE);
}
}
};
}
The layout file, main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textOff="Show"
android:textOn="Hide" />
<LinearLayout
android:id="@+id/possiblyHiddenView"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
>
<TextView
android:text="Stuff that could be hidden."
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
If you don't want the hidden view to take up any space, use visibility gone instead of invisible.
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what is the fastest CSS display Property for Animating DOM element it seem that
display: block
cause less reflow then
display: table
also is there any css property that could be set to make sur that changing one dom element won't affect the layout of some other element and thus causing extra repaint or reflow.
A: You can use visibility: visible; and visibility: hidden;. As the element still takes up space while it's hidden, the impact on the layout is minimal when you show/hide it.
A: Adding position:absolute to the element would take the element completely out of the flow of the page, therefore causing no reflow for other elements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Wix Boolean Property Values Don't Work I have the following property:
<Property Id="UPDATEDB">1</Property>
A checkbox in the UI bound to that property:
<Control Id="updateDatabase" Type="CheckBox" CheckBoxValue="1" Height="15" Width="95" X="20" Y="74" Text="Update Database" Property="UPDATEDB" />
And a Custom Action which does something based on the value of this property
<CustomAction Id="RunDbMigration" Directory="INSTALLDIR" Return="check"
ExeCommand='[DBMIGRATIONDIR]\DbMigration.exe' />
<InstallExecuteSequence>
<Custom Action="RunDbMigration" After="InstallFinalize">UPDATEDB=1 AND NOT Installed</Custom>
</InstallExecuteSequence>
If I try to pass a value of 0 for UPDATEDB from the command line:
msiexec /i "Setup.msi" /l* UPDATEDB=0
or
msiexec /i "Setup.msi" /l* UPDATEDB="0"
the value of the checkbox is checked anyway. That said, the 0 passed in seems to be respected and the RunDbMigration action is not run...
What's going on here? Why is this such rocket science?
A: As others have mentioned, Checkboxes are not boolean in a 1/0 sense, they're boolean in a null/not-null sense.
To unset from the command line - you would want to use something like
msiexec /i "Setup.msi" /l* UPDATEDB=""
Chances are that your condition is looking specifically for the value of 1 before executing your custom action, which is why your CA isn't being run.
A: Installer properties are either set to a value or they are not set. Internally the value is just a string, so "0", "1", "true" and "false" are the same.
A checkbox control is checked when its property is set to a value (doesn't matter what) and unchecked when its property is empty.
This command line sets the property and checks the checkbox:
msiexec /i "Setup.msi" /l* UPDATEDB="0"
This command line doesn't set the property, so the checkbox is not checked:
msiexec /i "Setup.msi" /l*
A: The problem is the CheckBoxValue="1". You find the solution for your question here: http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/How-to-conditionally-check-uncheck-a-checkbox-td5539262.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Process a directory of images in XCode Is there a way to read in and process a large directory of images in such a way that I can process one image at a time, and then once one is done, it will retrieve the next image from the directory, until it's gone through the whole directory?
I have a large folder of jpeg files, and I want to import them one at a time, alphabetically, analyze them, get an output, and then move on to the next file in the folder. Any help is much appreciated.
Sorry for the lack of eloquence. I've been going at this for about 10 hours straight at this point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How To Remove "Ctrl + Backspace" Special Character? I have a server written in C++, and when receiving a chat string, I'd like to remove weird special characters like the one created by Ctrl + Backspace (though not other symbols like :)]>_ etc.)
I'm using Boost, too.
edit: Why'd this get -1'd? It's a legit question.
A: Sounds like isprint might help. It returns true for any printable character, ie. not for control characters and whitespaces. For a list of what is considered printable and what not, take a look at this table.
A: I haven't used it, and this probably isn't the best way to do it, but have you considered trying the boost regex library (i.e., regex_replace)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to run .py file in browser using python webserver i have running a python webserver by using this simple script -
from http.server import SimpleHTTPRequestHandler as RH
from socketserver import TCPServer
ServerName='localhost'
OnPort=8000
print ("Server is running at Port 8000")
TCPServer((ServerName, OnPort), RH).serve_forever()
it is running good and run my index.html file but it is not run .py file in browser when i type --
http://localhost:8000/myfile.py
it just show my python codes as it is i write in file ,it is not execute the code please help me to run my python file (.py) in browser by using this webserver only ,i don't want to use any framework or another webserver.
Is there any way to make a virtual host in this python server like apache.
if possible please suggest me that how to do this and any configuration file need to be configured or not.
thanx...
A: The problem is that SimpleHTTPRequestHandler only serves files out of a directory, it does not execute them. You must override the do_GET method if you want it to execute code.
A: You might want to check out CGIHTTPRequestHandler instead. I very briefly played with it on a linux based system and the CGI criteria was for a file to be executable and have the correct shabang. I'm not sure if this would work on Windows though ( if that is even a relevant concern )
With your example code you would only need to change RH to
import CGIHTTPServer.CGIHTTPRequestHandler as RH
Alternatively the 3rd party library Twisted has a concept of .rpy files that are mostly plain Python logic. http://twistedmatrix.com/trac/wiki/TwistedWeb
Note:
Just verified that the CGIHTTPRequestHandler works. Caveats is that all python files must be in a cgi-bin subdir, they must have a valid shabang, must be executable, and must provide valid CGI output.
Personally having written C++ CGI scripts in the 90's, the CGI route seems like the path to maddness... so check out Twisted, CherryPy, or Django ( those three mostly cover the Python web spectrum of possibilities )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to connect Cakephp 1.3 with MS SQLServer 2008? I can't connect to MSSQL Server. I've been researching for 2 days, yet I can't find any useful resources. This is the error I'm getting:
URL rewriting is not properly configured on your server.
Help me configure my database. I don't / can't use URL rewriting:
Your tmp directory is writable.
The FileEngine is being used for caching. To change the config edit APP/config/core.php
Your database configuration file is present.
Here's my database config file:
class DATABASE_CONFIG {
var $default = array(
'driver' => 'mssql',
'persistent' => false,
'host' => 'Charmae-PC\Charmae',
'login' => 'sa',
'password' => 'pass',
'database' => 'obbm',
'prefix' => '',
'port' => '',
);
}
What should I do?
A: You need to configure your database with cakephp[windows php driver]. I don't know which version cakephp are you using. But for any version of cakephp and wampserver windows php drivers are different. for more information
Download the sqlsrv driver from here
and then the rest of configuration.
By the way you have to use sqlsrv driver for config/database.php
var $default = array(
'driver' => 'sqlsrv',
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's a safe way to declare a variable so I can call it from another script? I've built an array of image URLs on a Wordpress template page like this:
<?php $attachments = get_posts(array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
));
if ($attachments) {
//set up array of urls
$image_urls = array();
foreach($attachments as $attachment){
$image_object = wp_get_attachment_image_src($attachment->ID,'full');
$image_urls[] = $image_object[0];
}
} ?>
Then, in footer.php, I'd like to print the array for Javascript like this:
<script>
var images = [<?php $num_urls = count($image_urls);
$num = 1;
foreach($image_urls as $image_url) {
echo $image_url;
$num++;
if($num<$num_urls) echo ', ';
} ?>];
</script>
I mistakenly assumed that, in concatenating the template page and footer.php, PHP would view the script as continuous, and remember the variable value, but that's not the case, as it returns:
Warning: Invalid argument supplied for foreach()
How do I declare that $image_urls array so that I can refer to it later, without a scoping/namespacing danger?
PS Is there a better way to add a comma after all but the last item in the latter piece of code?
A: To safely pass the $image_urls around in multiple scripts, declare it like this:
$GLOBALS['image_urls'] = array();
foreach($attachments as $attachment){
$image_object = wp_get_attachment_image_src($attachment->ID,'full');
$GLOBALS['image_urls'][] = $image_object[0];
}
And later, to reference it:
<script>
var images = [<?php $num_urls = count($GLOBALS['image_urls']);
$num = 1;
foreach($GLOBALS['image_urls'] as $image_url) {
echo $image_url;
$num++;
if($num<$num_urls) echo ', ';
} ?>];
</script>
To make sure you do not conflict with anything, you can add a prefix to image_urls to indicate that it is yours.
A: Script looks fine.
Though, this would be better:
<script>
var images = [<?php echo implode(',',$image_urls) ?>];
</script>
A:
I mistakenly assumed that, in concatenating the template page and footer.php, PHP would view the script as continuous, and remember the variable value
It should, unless Wordpress is odd this way, or unless the variable is inside a function scope (in either file). If so, add this declaration:
global $image_urls;
at the top of the function(s). Alternatively, reference $image_urls everywhere via $GLOBALS. E.g.,
$GLOBALS['image_urls'][] = $image_object[0];
Is there a better way to add a comma after all but the last item in the latter piece of code?
Use the implode function:
echo implode(', ', $image_urls);
I think you need quotes around each item too, so:
if (count($image_urls)) {
echo '"' . implode('", "' $image_urls) . '"';
}
Or, in general, I'd do something like this for that type of loop:
$first = true;
foreach (...) {
if ($first) $first = false; else echo ', ';
echo $item;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I convert my python script to a .app? Is it possible to convert my .py script to a .app that works through a text box or something?
Thanks
A: Try py2app.
py2app is a Python setuptools command which will allow you to make
standalone application bundles and plugins from Python scripts. py2app
is similar in purpose and design to py2exe for Windows.
A: Because this is a vague question, I will provide a general answer.
You need to decide on a GUI framework. There are a number of them to choose from.
PyQt4
http://qt.nokia.com/products/
http://www.riverbankcomputing.co.uk/software/pyqt/download
PySide (LGPL version of PyQt4) - http://www.pyside.org/
GTK - http://www.pygtk.org/
wxPython - http://www.wxpython.org/
TkInter
http://wiki.python.org/moin/TkInter
You could even write a web interface that communicates with your python script via RPC or an HTTP rest interface. Take your pick!
My vote is on PySide/PyQt. Its very flexible and easy to use.
At that point you would then use something like py2app to package up the entire environment into a standalone .app that can be distributed.
A: You can also use the cross-platform pyinstaller, which is more modern and I've had a good experience with.
sudo pip install pyinstaller
pyinstaller myprogram.py --windowed
There's a lot more configuration if you want to go cross platform, but this may get you started:
http://pythonhosted.org/PyInstaller/#building-mac-os-x-app-bundles
This creates the distrutable. From there I use things like Inno Setup on windows or app2dmg for mac.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to fix LayoutParam's for imageview ClassCaseException? This is the error i get each time i try and set the LayoutParam's for a image view.
10-02 03:27:53.081: ERROR/AndroidRuntime(1272): FATAL EXCEPTION: main
10-02 03:27:53.081: ERROR/AndroidRuntime(1272): java.lang.ClassCastException: android.widget.Gallery$LayoutParams
10-02 03:27:53.081: ERROR/AndroidRuntime(1272): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:659)
10-02 03:27:53.081: ERROR/AndroidRuntime(1272): at android.widget.LinearLayout.onMeasure(LinearLayout.java:311)
10-02 03:27:53.081: ERROR/AndroidRuntime(1272): at android.view.View.measure(View.java:8313)
10-02 03:27:53.081: ERROR/AndroidRuntime(1272): at android.view.ViewGroup.measureChild(ViewGroup.java:3109)
Here is my layout with the imageview i am trying to set the layoutParam's for..
<?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="wrap_content">
<ImageView
android:id="@+id/imageView"
android:layout_width="50dip"
android:layout_height="50dip" android:src="@drawable/stub" android:scaleType="centerCrop"/>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical" android:textSize="20dip" android:layout_marginLeft="10dip"/>
</LinearLayout>
And here is the code i inflate the view and then try to set the Param's but i keep getting the error above.
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.lazyitemt, null);
ImageView image=(ImageView)vi.findViewById(R.id.imageView);
image.setLayoutParams(new Gallery.LayoutParams(150, 150));
imageLoader.DisplayImage(data[position], activity, image);
return vi;
}
I dont know why i keep getting this. Everything seems to be right? How can i resolve this?
A: You put imageView inside LinearLayout. So, you should modify your layout param code like this
image.setLayoutParams(new LinearLayout.LayoutParams(150, 150));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove Axis2 web service Is there a way to remove an already deployed axis2 web service ?
I tried deactivating, but that does not remove the web service, it merely disables it till the system is restarted.
Thanks. Any help is appreciated.
A: remove the artifact from the services folder. you may have to set hot update true. Please see the axis2.xml.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reading filecontent pairs of chars into array In C++, how can I read the contents of a file into an array of strings? I need this for a file that consists of pairs of chars separated by spaces as follows:
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
c can be any char, including space! Attempt:
ifstream myfile("myfile.txt");
int numPairs = 24;
string myarray[numPairs];
for( int i = 0; i < numPairs; i++) {
char read;
string store = "";
myfile >> read;
store += read;
myfile >> read;
store += read;
myfile >> read;
myarray[i] = store;
}
The problem is that this just skips spaces alltogether, hence leading to wrong values. What do I need to change to make it recognize spaces?
A: That's expected behavior, since operator>>, by defaults, skips whitespace.
The solution is to use the get method, which is a low level operation that reads raw bytes from the stream without any formatting.
char read;
if(myfile.get(read)) // add some safety while we're at it
store += read;
By the way, VLAs (arrays with a non constant size) are non standard in C++. You should either specify a constant size, or use a container such as vector.
A: If the input is exact like you say the following code will work:
ifstream myfile("myfile.txt");
int numPairs = 24;
string myarray[numPairs];
EDIT: if the input is from STDIN
for( int i = 0; i < numPairs; i++) {
myarray[i] = "";
myarray[i] += getchar();
myarray[i]+= getchar();
getchar(); // the space or end of line
}
EDIT: If we don't now the number of pairs beforehand
we shoud use a resizable data structure, e.g. vector<string>
vector<string> list;
// read from file stream
while (!myfile.eof()) {
string temp = "";
temp += myfile.get();
temp += myfile.get();
list.push_back(temp);
myfile.get();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't show the tabbar icon, even with size 30*30 I prepared some PNG icons, size 30*30, but with colors, not only black/white. The icons are OK when I want to display them on buttons.
It can't be shown in the tabbar.
I am wondering if the iphone only supports some simple icons (the black/white icons with lines).
Do you have any ideas?
Thanks in advance.
Michael
A: TabBar icons displayed in gray scale even if they are color, and iPhone uses the alpha channel for masking.
I recommend checking this site, most iPhone developers like it :
http://www.glyphish.com/
A: The alpha component of the image is all that is used to draw the icon on the tab bar. So you need to make sure your image has a alpha channel or it will either not show up or show up as a blank square in the tab bar.
This does mean that effectively only monochrome images can be used in the tab bar.
I'm not at my mac right now and I can't remember if it is 1.0 alpha or 0.0 alpha that shows up as white in the tab bar, or if you need to have a black or white background, but if you create an image with varying transparency it should be easy enough to work out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to prevent page from unloading when app is active I have a few tabs in my app. I am currently facing an issue whereby my pages gets unloaded whenever the memory gets low (especially if I bring up the camera in my app).
Is there anyway to mitigate this and prevent unloading from happening? Or is there any way to intercept the unloading process so that something can be done instead of allowing the page to be unloaded?
A: You should not prevent view unloading, if the application runs out of memory, it MUST free memory, or else your app will simply be killed by the system. You should really cleanup as much memory as you can, as well as views.
Also, views are only there to display data, if the view is unloaded it's only in one specific case: there was a memory warning and the view didn't have a superview (not visible to the user). If it's not visible to the user, it makes absolutely no sense to keep it around when running out of memory. If you're storing [important] data in these views, you're doing it wrong. Data model should be kept in controllers.
A: When the memory gets low, all the view controllers get their delegate method: didReceiveMemoryWarning called.
The default implementation of UIViewController is to unload the view.
So, all you need to do in order to override this behavior is override the method:
- (void)didReceiveMemoryWarning
{
//[super didReceiveMemoryWarning]; - calling this will unload the view
// Relinquish ownership any cached data, images, etc that aren't in use.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RailRoad is not working. Giving me issues ie /railroad-0.5.0/lib/railroad/app_diagram.rb:54:in `disable_stdout': uninitialized constant Here is various outputs
railroad -M | dot -Tsvg > models.svg
/Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/lib/railroad/app_diagram.rb:54:in `disable_stdout': uninitialized constant AppDiagram::PLATFORM (NameError)
from /Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/lib/railroad/app_diagram.rb:72:in `load_environment'
from /Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/lib/railroad/app_diagram.rb:18:in `initialize'
from /Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/lib/railroad/models_diagram.rb:14:in `initialize'
from /Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/bin/railroad:36:in `new'
from /Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/bin/railroad:36:in `<top (required)>'
from /Users/me/.rvm/gems/ruby-1.9.2-p290/bin/railroad:19:in `load'
from /Users/me/.rvm/gems/ruby-1.9.2-p290/bin/railroad:19:in `<main>'
Versions
me$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.1.0]
me$ rvm -v
rvm 1.8.0 by Wayne E. Seguin ([email protected]) [https://rvm.beginrescueend.com/]
me$ rails -v
Rails 3.0.10
Every command is giving me same issue:
*
*railroad -o models.dot -M
*railroad -a -i -o full_models.dot -M
*railroad -M | dot -Tsvg > models.svg
*railroad -C | neato -Tpng > controllers.png
A: Edit /Users/me/.rvm/gems/ruby-1.9.2-p290/gems/railroad-0.5.0/lib/railroad/app_diagram.rb at line 54 and change PLATFORM to RUBY_PLATFORM.
See: http://rubyforge.org/tracker/index.php?func=detail&aid=26418&group_id=3383&atid=12998
A: Railroad is not working with ruby 1.9.2 and rails 3.0.10. Railroady is advanced maintained version..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Most efficient way to modify xml I'm writing an app that needs to modify xml documents. More precisely it need to add attributes and add/delete nodes. These documents are relatively small, 30-50K at most. From what I'm reading the best way to read XML is use the SAX parser, but does that apply to modifying XML as well? The DOM parser seems to be the easiest to manipulate XML with, but, obviously, uses more battery and memory.
Just looking for the most efficient way (uses the least battery/memory) to manipulate XML on an Android device.
A: I suggest XOM - It is very memory efficient and support dual streaming/tree-based API.
A: The most efficient way to modify XML is to use VTD-XML(http://vtd-xml.sf.net)...it is the only way to do so called incremental update..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XML time stamp "Thu, 30 Jun 2011 07:34:33 +0000" to Unixtime? I have "Thu, 30 Jun 2011 07:34:33 +0000" as a time stamp from Twitter RSS feed. My server is in Eastern time. I need to some how convert this over to unixtime. I have no clue where to start. I guess Twitter would be in pacific time unless its like 24 hours.
I also have another rss feed that uses the same format. Any ideas? Not even sure what i would type in to Google to find a answer for this.
A: Use the strtotime() function:
date_default_timezone_set($user_timezone); // Set the user's timezone if you'd like
$time = strtotime("Thu, 30 Jun 2011 07:34:33 +0000") // Convert the time
echo date("l M j \- g:ia", $time); // Print it in any format you want!
And for future reference, try "php twitter date unix" on Google for next time :)
A: use strtotime();
e.g.: strtotime("Thu, 30 Jun 2011 07:34:33 +0000")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Visual Basic 2d array from .dat file So I'm trying to pull some data from two text files. The first loads and populates the listboxes perfectly. The second text file is where I'm having trouble. I can't seem to get it to load correctly. I'm trying to put it into a 2D array, MileageAr. The messagebox is to troubleshoot if it is loading into the array correctly. What am I doing wrong?
Sample Data from SDMileage.dat
1,54,465,58,488,484
5,54,654,87,841,844
etc....
Public Class ArrayFun
Dim MileageAr(10, 10) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim State As New System.IO.StreamReader("SDCities.dat")
Dim strState As String
Dim i, j As Integer
Do While State.Peek <> -1
strState = State.ReadLine
lstFrom.Items.Add(strState)
lstTo.Items.Add(strState)
Loop
Dim Mileage As New System.IO.StreamReader("SDMileage.dat")
Dim strLine As String
Dim strSplit() As String
Do While State.Peek <> -1
strLine = Mileage.ReadLine
strSplit = strLine.Split(",")
j = 0
For Each miles In strSplit
MileageAr(i, j) = miles
j += 1
Next
i += 1
Loop
State.Close()
Mileage.Close()
End Sub
Private Sub lstTo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstTo.SelectedIndexChanged
MsgBox(MileageAr(1, 1))
End Sub
End Class
A: Dim Mileage As New System.IO.StreamReader("SDMileage.dat")
Dim strLine As String
Dim strSplit() As String
CHANGE THIS TO Mileage.Peek
Do While State.Peek <> -1
strLine = Mileage.ReadLine
strSplit = strLine.Split(",")
Try looping this way instead
Dim Mileage As System.IO.TextReader = New StreamReader("SDMileaage.dat")
do while ((strline = Mileage.ReadLine) <> nothing)
The Peek method might be fine, I just typically use the code above when working with text files, might be worth a shot...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changing values in nested lists with python Ok, with the same program previously I've now hit a problem I should have anticipated; the grid (of variable width and height) is constructed based on a code to alternate the symbols which creates a list, those lists are then stored in the grid as nested lists. below is a section of code for making the list (called line) the odd numbered width is necessary.
1 - + -
2 + - +
3 - + -
if gridwidth % 2 != 0:
for i in range(gridwidth):
if i % 2 == 0:
line.append('-')
else:
line.append('+')
Edit - sorry I didn't want to spam with code; the lines are put into the list grid below;
grid = []
for i in range(height):
if i % 2 == 0:
grid.append(line)
else:
grid.append(linerev)
line is then appended to grid by the range(height) and there is another block of code to handle the alternating lines which creates another list (linerev) - my problem is that because of how the grid is created, if I try to change a value in it say turn grid[0,0] into a + or -, it changes it along several rows as grid[1,0], grid[5,0] etc are all referring the the same list - is there any way to avoid this without using global variables, deep copy, or drastically revising how the grid is created? Any help would be much appreciated.
A: The easiest way is to make copies of the lists when you add them:
grid = []
for i in range(height):
if i % 2 == 0:
grid.append(line[:])
else:
board.append(linerev[:])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: pass data using jquery $.get() I try to implement the following code:
html
<span id = "myset">school</span>
Javascript
var myset =$("#myset").val();
var ID=$("#data li:last").attr("id");
$.get('page.php', 'id='+ID+'&set='+myset, function(newdata){
$('#data').append(newdata);
});
In the page.php file, it doesn't receive the value of the $_GET['set'], but if I change
var myset =$("#myset").val();
to:
var myset ='school';
everything works fine in this case, what am I doing wrong, anyone could help me, thanks.
I also tried
var myset =document.getElementById("myset").value;
but it is still not working;
A: "school" isn't the value of your span. It is the data of a text node inside your span. You can access it like this:
var myset = $("#myset").text();
A: Span tags don't have a value, they have .innerText or .innerHTML or, with jQuery, .html() or .text()
A: Use var myset =$("#myset").text(); instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Initialize a UIViewController before an item in a search bar is selected I have a UITabBarController and a SearchBar on the home page. The SearchBar searches items in the database and when an item is selected, jumps to that item in tab 2. I changed my view hierarchy to use a UINavigationController in that tab. In my viewDidLoad of the rootViewController for the UINavigationController, I push the first viewController (out of 3). It's on this viewController that the search item goes to.
If I go to that tab just once, then my first viewController is loaded, and I select a search item, then it works. The problem is if I never go to that tab and my first viewController is not pushed onto the stack, then the search does not know where to go and crashes. I'm pretty sure I do NOT call viewDidLoad myself from my first tab to ensure that the first ViewController is pushed onto the stack. How do I get around this problem? Is there something I can do in loadView? Thanks.
A: You are correct, viewDidLoad is a delegate method, not supposed to be called by you. One of the approaches that you can follow is- from tab 1, set an instance variable of firstViewController in tab 2, something like pendingItemIndex, corresponding to the item that is to be displayed in tab 2.
Then, in viewDidLoad of firstViewController, check if pendingItemIndex has a valid value (you can set the default value to -1). If it does, display the corresponding item.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Overloading multiple operators Concisely, my goal is to have foo[bar] return type1, and foo[bar]= return type2.
I am writing an object in C++, and it's coming along quite nicely, however there's just one tiny little thing that I wish to do, yet it seems impossible.
My object is a storage class, so I am using an array subscript to access values. I also need to assign, so I also overload the = operator. However, it is somewhat inconvenient because the values that my class holds are first class objects, so for my array subscript overload I can't return them as is. I have to return an intermediate class to handle the = operator, but I also want to retrieve the value without additional typing.
Is there any way to do this? Hackish ways are acceptable.
Edit: Here's an example of what it (should) do
#include<cstdio>
#include<cstdlib>
class foo{
char* a[100];
foo(){
for( int i = 0; i < 100; i ++)
a[i] = 0;
}
char* operator[] (int location){
return a[location];
}
foo& operator[]= (int location, const char* value ){
if( a[location] == 0 )
a[location] = (char*) malloc( strlen( value ) + 1 );
else
a[location] = (char*) realloc( a[location], strlen( value ) + 1 );
strcpy( a[location], value );
}
};
int main(){
foo bar;
bar[20] = "Hello";
printf( "bar[20] = %s\n", bar[20] );
bar[20] = "Hello There";
printf( "bar[20] = %s\n", bar[20] );
printf( "bar[20][0] = %c\n", bar[20][0] );
}
Output:
bar[20] = Hello
bar[20] = Hello There
bar[20][0] = H
Edit again: I think I'll try phrasing this in a different, but workable way. Is there a way to overload the return type when a class is referenced? Such that if I have
class foo{
bool a;
bool operator /*referenced*/ (){
return a
}
foo& operator=(bool b){
a = b;
}
};
int main(){
foo a;
a = b;
if( a == b )
printf("It Works!");
}
that would actually work?
A: There is no operator[]=, so the solution is to write some sort of wrapper class with two key features: an operator= that takes a value and sets it to the parent container, and an implicit conversion operator that takes the value from the parent container and returns it. Your operator[] will then return such wrapper.
class foo
{
friend class wrapper;
public:
class wrapper
{
friend class foo;
foo & _parent;
int _index;
wrapper(foo & parent, int index) : _index(index), _parent(parent) {}
public:
wrapper & operator=(const char * value)
{
if( _parent.a[_index] == 0 )
_parent.a[_index] = (char*) malloc( strlen( value ) + 1 );
else
_parent.a[_index] = (char*) realloc( _parent.a[_index], strlen( value ) + 1 );
strcpy( _parent.a[_index], value );
return *this;
}
operator char *()
{
return _parent.a[_index];
}
};
char* a[100];
foo()
{
for( int i = 0; i < 100; i ++)
a[i] = 0;
}
wrapper operator[] (int location){
return wrapper(*this, location);
}
};
For the second question, well, you could always overload operator== on foo. But maybe I misunderstood.
A: If you're willing to use C++ (as your tag suggests), then most of the work has been done for you:
class foo: public vector<string>
{
public:
foo()
{
resize(100);
}
};
int main()
{
foo bar;
bar[20] = "Hello";
cout << "bar[20] = " << bar[20] << endl;
bar[20] = "Hello There";
cout << "bar[20] = " << bar[20] << endl;
cout << "bar[20][0] = " << bar[20][0] << endl;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to Combine TemplateFields in ASP.Net GridView? Everyone.
I have a question when combining cells in GridView. I konw how to combine BoundField cells, but I do not know how to combine TemplateField cells in asp.net GridView.
EDIT:
Perhaps I did not make my question clearly and I am sorry about that. My question is that I use GridView to bind data from db and There is a field named UserName, one user has several records in the db, so I want to combine UserName in one cell(i can combine it correctly). In the same way, I want to do some operation to this user such as Add, Delete. So i put these operations into TemplateField, but i do not konw how to combine TemplateField like BoundField. I have a low reputation, so i can not post images
Any good ideas?
Sorry for my poor english! Thanks in advance.
A: There isn't a way to merge/combine fields. I think you misunderstood the BoundFields/TemplateField. However you can use Eval() and Bind() to show/bind one or more expression into single cell//column..
Read MSDN articles:
*
*BoundField
*TemplateField
EDIT:
@loren : There is a field named UserName, one user has several records
in the db.
I guess you need to use "nested" grid or you may also use any data control (formview, detail view or ListView).
Here is demo that shows how to bind nested data controls.
I've define two classes - Contact, Info
public class Contact
{
public string Address{get;set;}
public string Phone {get;set;}
}
public class Info
{
public string UserName {get;set;}
private List<Contact> _addr=new List<Contact>();
public List<Contact> Address
{
get { return _addr; }
set { _addr = value; }
}
}
In .aspx page (Markup),
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="false"
onrowdatabound="GridView1_RowDataBound"
>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>
Username :
<asp:Literal
ID="UserName"
runat="server"
Text='<%#Eval("UserName") %>'
>
</asp:Literal>
</p>
<asp:GridView
ID="GridView2"
runat="server"
AutoGenerateColumns="false"
>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>Phone :
<asp:TextBox
runat="server"
ID="txtDetail"
Text='<%#Bind("Phone") %>'
></asp:TextBox>
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code-behind (aspx.cs),
List<Info> info;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
info = new List<Info>()
{
new Info()
{
UserName="User1",
Address =
{
new Contact() { Phone="2929927", Address="Address1"},
new Contact() { Phone="2929928", Address="Address2"},
}
},
new Info()
{
UserName="User2",
Address =
{
new Contact() { Phone="2929929", Address="Address3"},
new Contact() { Phone="2929930", Address="Address4"},
}
},
};
GridView1.DataSource = info;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Literal username=(Literal)e.Row.FindControl("UserName");
GridView view=(GridView)e.Row.FindControl("GridView2");
if (view != null)
{
var result = from ele in info
from add in ele.Address
where ele.UserName == username.Text
select add;
view.DataSource = result;
view.DataBind();
}
}
A: you can use Eval as bellow
<asp:TemplateField HeaderText="Header">
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" Text='<%#Bind("Phone") %>'></asp:TextBox>
<asp:TextBox runat="server" ID="txt2" Text='<%#Bind("Address") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
A: If possible, you can update the source type.
For example, if you an object data source and a model like this :
[DataObject]
public class MyOds{
[DataObjectMethod(DataObjectMethodType.Select)]
public ICollection<MyModel> GetMyModels()
{
var result = new ListMyModel();
Populate(result); // load model with any method of you choice
return result;
}
}
public class MyModel{
public string Address { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string FullAddress {
get
{
return string.Format("{0} - {1} - {2}", Address, City, Country);
}
}
}
Note the FullAddress property. The idea is to build, for the view, properties easy to exploit. The ASPX can looks like this :
<asp:TemplateField HeaderText="Header">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label">
<%# Eval("FullAddress")%>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: error while trying to display view in asp.net mvc 3 app? I am trying to display a list in a View, how to fix this error?
The model item passed into the dictionary is of type
'System.Data.Objects.ObjectQuery1[System.Linq.IGrouping2[System.Int32,mvc3Post.Models.Contact]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[mvc3Post.Models.Contact]'.
controller:
public ActionResult Index()
{
AdventureWorksEntities db = new AdventureWorksEntities();
var result = from soh in db.SalesOrderHeaders
join co in db.Contacts
on soh.ContactID equals co.ContactID
orderby co.FirstName
group co by co.ContactID into g
select g;
return View(result.AsEnumerable());
}
view:
@model IEnumerable<mvc3Post.Models.Contact>
@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
NameStyle
</th>
<th>
Title
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.NameStyle)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ContactID }) |
@Html.ActionLink("Details", "Details", new { id = item.ContactID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ContactID })
</td>
</tr>
}
</table>
A: Updated now that I see the controller method:
You might need to transform your LINQ result set into a list or something (e.g., contacts.ToList()) more concrete.
Another alternative might be to create a root object for your page's list object to live on. I find it a little easier to follow and maintain if each View has a corresponding Model class that represents it's entire state.
I think either route will resolve your issue though. I think that the latter is probably the better way if I had to recommend one vs the other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shared Preferences in WebView I want to limit how many songs a user can download in my FREE app. The download is executed everytime a user clicks on a link that ends with /download/. I can't seem to wrap my head around how to get this to work with shared preferences. When testing I was able to download a file at least 5 times so it obviously didn't work. Here is a snippet of what I am doing:
else if (url.startsWith("http://xxxxxx.com/songs2/Music%20Promotion/Download/")) {
prefs2 = getSharedPreferences("downloadlimit", 0);
editor = prefs2.edit();
long launch_count = prefs2.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
if (launch_count >= 2) {
showRateDialog(getApplicationContext(), editor);
}
A: You'll have to call editor.commit(); to ensure that your changes are saved. See here for more info:
http://developer.android.com/guide/topics/data/data-storage.html#pref
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Can't find model for source store" occurring during iphone "Automatic Lightweight Migration"? I'm really stuck here with upgrade testing from v1 to v2 of an iPhone application. I have IPA releases that I'm testing via ad hoc distribution via iTunes to my iPhone device, one for v1 of the app and one for v2. Note that:
*
*v1 installs runs fine on my device
*if I delete v1 and deploy v2 (so no migration) then it works fine
*when I deploy v2 whilst v1 is already there I get the error: "reason=Can't find model for source store"
A snippet from the error...*
reason=**Can't find model for source store**}, {
URL = "file://localhost/var/mobile/Applications/AAAAF424-D6ED-40FE-AB8D-66879386739D/Documents/MyApp.sqlite";
metadata = {
NSPersistenceFrameworkVersion = 320;
<cut>
*
*when I use "phone disk" to look at my device I see there is Documents/MyApp.sqlite file
Question - Any ideas how to resolve this? What debugging/analysis could I do here? Let me know if you need any more info.
What I have done as an overview is:
*
*Deployed my v1 app to the AppStore without setting up a version for my core data model (i.e. wasn't really aware at the time of versions, so didn't set one up)
*The only additional change for v2 was one new attribute on the one model
*So for the v2 release what I've done is:
*Recreated a new Core Data Model
*Created a v1 version for the model
*Created the object/attributes for v1
*Saved
*Created a v2 version for the model
*Created the one additional attribute
*Saved
*Recreated the managed object classes
*Updated the code to put the options in per http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmLightweight.html#//apple_ref/doc/uid/TP40008426-SW1 when calling addPersistentStoreWithType
PS fuller version of error if this helps - this time it comes from simulating the migration error on the simulator
, reason=Can't find model for source store}, {
URL = "file://localhost/Users/greg/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/69FDFDCF-631D-4191-B852-CD75151B1EA9/Documents/MyApp.sqlite";
metadata = {
NSPersistenceFrameworkVersion = 320;
NSStoreModelVersionHashes = {
Config = <5f92f988 71e11a66 554ae924 61887562 22b8de8a c318b110 e3e4a569 81adafa2>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "3B9832DA-E3A1-431B-83E8-43431A7F3452";
};
reason = "Can't find model for source store";
}
PSS. If this helps the contents of the core data model *.mom directory/package for each version archieve are:
v1
-rw-r--r-- 1 greg staff 1664 5 Sep 21:06 MyApp.mom
-rw-r--r-- 1 greg staff 2656 5 Sep 21:06 MyApp.omo
-rw-r--r-- 1 greg staff 480 5 Sep 21:06 VersionInfo.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd>">
<plist version="1.0">
<dict>
<key>NSManagedObjectModel_CurrentVersionName</key>
<string>MyApp</string>
<key>NSManagedObjectModel_VersionHashes</key>
<dict>
<key>MyApp</key>
<dict>
<key>Config</key>
<data>
X5L5iHHhGmZVSukkYYh1YiK43orDGLEQ4+SlaYGtr6I=
</data>
</dict></dict></dict>
</plist>
v2
-rw-r--r-- 1 greg staff 497 2 Oct 12:47 MyApp 1.mom
-rw-r--r-- 1 greg staff 1601 2 Oct 12:47 MyApp 2.mom
-rw-r--r-- 1 greg staff 1695 2 Oct 12:47 MyApp.mom
-rw-r--r-- 1 greg staff 2920 2 Oct 12:47 MyApp.omo
-rw-r--r-- 1 greg staff 665 2 Oct 12:47 VersionInfo.plist
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd>">
<plist version="1.0">
<dict>
<key>NSManagedObjectModel_CurrentVersionName</key>
<string>MyApp</string>
<key>NSManagedObjectModel_VersionHashes</key>
<dict>
<key>MyApp</key>
<dict>
<key>Config</key>
<data>
Z/n8092QBHPfBwInZvIm1lei53T1UtZhpNzjl3JA0gs=
</data>
</dict>
<key>MyApp 1</key>
<dict/>
<key>MyApp 2</key>
<dict>
<key>Config</key>
<data>
Fih24clI+kZszFd3X6Gm8itq8YDxudiKnjHW8ydNmps=
</data>
</dict></dict></dict>
</plist>
EDIT: Another question that is not clear to me, as raised by reviewing the link jrturton provided below is:
*
*How does one now in the latest XCode version do the "Set Current Version" to the appropriate model version file? i.e. the previous posts highlights two different steps being one Adding Model Version, but then separately "Set Current Version"
*How is one supposed to use the Core Data Model "identifier" field which one can set for each of the core data model files. It's in the inspector. The parameter exists against for example the MyApp 1.xcdatamodel, MyApp 2.xcdatamodel, and MyApp.xcdatamodel files, so what do you need to put in each one here?
A: You set the version of your data model in the Utilities inspector (right hand pane), under the Identity and Type tab when the xcdatamodeld file is selected. This has a section called "Core Data Model", and a field called "Identifier".
You add a new model version by selecting the xcdatamodeld file, the going to Editor --> Add model version.
At this point it prompts you for the previous model to base it on.
If youve added a new model without going through this process the lightweight migration may not work.
A: another thing that can cause this, is if you:
*
*make version 2
*then edit version 1 accidentally
*then make version 2 default
*realize your change isn't there
*make your change again on version 2
you get the same effect, because the version 1 that you are trying to merge from isn't the version that created the store.
A: If you made changes to your model and you made sure that you generated a model object AND don't care about the migration nor are interested in making a new version, you simply need to do a Product -> Clean and that will typically fix this issue.
If you are still having this error, locate your sqlite DB and delete it. When you launch the app again it will make a new one that's built from the new model.
Alternatively, you can delete the app from the simulator or, if all else fails, tap on "iOS Settings" at the top of simulator and select "Reset Content and Settings..." and it will quickly wipe the simulator so you can start fresh.
A: Xcode 8, i had this issue without doing migration
Can't find model for source store
what i did is simply
Simulator > Reset Content and Settings
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Can display dialogue with function, but cannot set variable with function I want to take the return value of the function getProjectTag().
tell application "TaskPaper"
tell front document
repeat with the_entry in entries
-- For each entry, get the data from TaskPaper
tell the_entry
set project_name to getProjectTag(the_entry)
I get the error:
TaskPaper got an error: item 26 of every entry of document 1 doesn’t
understand the getProjectTag message." number -1708 from item 26 of every entry of document 1
However, when I replace:
set project_name to getProjectTag(the_entry)
with:
display dialogue my getProjectTag(the_entry)
it shows me a dialogue of the correct return value -- so the function is working correctly.
A: Stupid me:
set project_name to my getProjectTag(the_entry)
fixes the problem.
I wasn't aware of what my did.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Instantiate plugins efficiently with observer pattern (php) I'm implementing the observer pattern to all plugins to interact with my web app. Now, I want to make installing plugins painless (i.e just putting files into a plugin folder) like most web apps do.
For example:
A plugin with the name "Awesome Stuff" that executes code based on events that occur in the Auth class and the Content class would include the following files in the "/plugin" directory.
AwesomeStuffAuth.php
AwesomeStuffContent.php
I've got a solution that's working, but I'm afraid it's not efficient, as it has to cycle through ALL the declared classes before it actually finds what it's looking for.
function __construct() {
//Get files in plugin directory that work on Auth
foreach (glob("plugins/*AuthPlugin.php") as $filename) {
//Include'em
include_once($filename);
}
//Get all declared classes
foreach (get_declared_classes() as $class){
if (substr($class,-10)=='AuthPlugin'){
$obj = new $class;
$this->addObserver($obj);
}
}
}
This is the __construct() method that I use with the Auth class, and other classes would have similar methods.
Is this an efficient way of doing this? Is it worth me connecting to a database to avoid cycling through all the declared classes? How about flat file?
Thanks so much for taking a look at this.
A: A possible solution would be to use __autoload to catch the moment where the plugin is requested and add it to a list of observers at this moment, based on naming conventions:
function __autoload($class) {
include_once 'plugins/' . $class . '.php';
$observable = substr($class,-16); # E.g. 'Auth'
$observable::addObserverClass($class);
}
then in the Auth class:
class Observable {
static $observer_classes = array();
static function addObserverClass($class) {
self::$observer_classes[] = $class;
}
static function addObservers($self) {
foreach(self::$observer_classes as $class) {
$self->addObserver($class);
}
}
function addObserver($class) {
# Add the Observer.
}
}
class Auth extends Observable {
function __construct() {
self::addObservers($self);
}
}
Haven't tested the code, but you should get the idea. It eliminates both the need to glob and the need to iterate over every declared class each time a class is created.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I autoscroll down using javascript, stop the function, and then scroll to the top onClick? There is also an image (a down arrow), that I want to animate to face upwards when the page reaches a certain point. I have a function to scroll to the bottom, but I can't figure out how to end the function. I am very new with javascript and obviously not that good at it.
Here is a link to the fiddle file: http://jsfiddle.net/thindjinn/LCYEp/embedded/result/
Enjoy Anderson Cooper as my poster. I was just testing the code. :D
A: On a sidenote: Instead of setTimeout(), use setInterval(). It eliminates the need of a recursive function.
To stop the page from scrolling any further, just call clearInterval().
A: Try this:
http://jsfiddle.net/LCYEp/6/
I added this:
window.pageScroll=function() {
window.scrollBy(0,50);
if(document.body.scrollHeight>
document.html.clientHeight+
document.body.scrollTop){
scrolldelay = setTimeout('pageScroll()',100);}
}
For some reason, I couldn't get the clientHeight of the document body to work right.
The scrollHeight is how tall the page that can be scrolled is.
The clientHeight is the visible region of the scroll area.
The scrollTop is the distance scrolled from the top of the scrollable region.
If the scrollTop + the clientHeight equals the scrollHeight, then you've scrolled to the bottom.
See:
https://developer.mozilla.org/en/DOM/element.clientHeight
https://developer.mozilla.org/en/DOM/element.scrollHeight
https://developer.mozilla.org/en/DOM/element.scrollTop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Injection: is this secure? I have this site with the following parameters:
http://www.example.com.com/pagination.php?page=4&order=comment_time&sc=desc
I use the values of each of the parameters as a value in a SQL query.
I am trying to test my application and ultimately hack my own application for learning purposes.
I'm trying to inject this statement:
http://www.example.com.com/pagination.php?page=4&order=comment_time&sc=desc' or 1=1 --
But It fails, and MySQL says this:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in /home/dir/public_html/pagination.php on line 132
Is my application completely free from SQL injection, or is it still possible?
EDIT: Is it possible for me to find a valid sql injection statement to input into one of the parameters of the URL?
A: The application secured from sql injection never produces invalid queries.
So obviously you still have some issues.
Well-written application for any input produces valid and expected output.
A: That's completely vulnerable, and the fact that you can cause a syntax error proves it.
There is no function to escape column names or order by directions. Those functions do not exist because it is bad style to expose the DB logic directly in the URL, because it makes the URLs dependent on changes to your database logic.
I'd suggest something like an array mapping the "order" parameter values to column names:
$order_cols = array(
'time' => 'comment_time',
'popular' => 'comment_score',
... and so on ...
);
if (!isset($order_cols[$_GET['order'])) {
$_GET['order'] = 'time';
}
$order = $order_cols[$_GET['order']];
Restrict "sc" manually:
if ($_GET['sc'] == 'asc' || $_GET['sc'] == 'desc') {
$order .= ' ' . $_GET['sc'];
} else {
$order .= ' desc';
}
Then you're guaranteed safe to append that to the query, and the URL is not tied to the DB implementation.
A: I'm not 100% certain, but I'd say it still seems vulnerable to me -- the fact that it's accepting the single-quote (') as a delimiter and then generating an error off the subsequent injected code says to me that it's passing things it shouldn't on to MySQL.
Any data that could possibly be taken from somewhere other than your application itself should go through mysql_real_escape_string() first. This way the whole ' or 1=1 part gets passed as a value to MySQL... unless you're passing "sc" straight through for the sort order, such as
$sql = "SELECT * FROM foo WHERE page='{$_REQUEST['page']}' ORDER BY data {$_REQUEST['sc']}";
... which you also shouldn't be doing. Try something along these lines:
$page = mysql_real_escape_string($_REQUEST['page']);
if ($_REQUEST['sc'] == "desc")
$sortorder = "DESC";
else
$sortorder = "ASC";
$sql = "SELECT * FROM foo WHERE page='{$page}' ORDER BY data {$sortorder}";
I still couldn't say it's TOTALLY injection-proof, but it's definitely more robust.
A: I am assuming that your generated query does something like
select <some number of fields>
from <some table>
where sc=desc
order by comment_time
Now, if I were to attack the order by statement instead of the WHERE, I might be able to get some results... Imagine I added the following
comment_time; select top 5 * from sysobjects
the query being returned to your front end would be the top 5 rows from sysobjects, rather than the query you try to generated (depending a lot on the front end)...
A: It really depends on how PHP validates those arguments. If MySQL is giving you a warning, it means that a hacker already passes through your first line of defence, which is your PHP script.
Use if(!preg_match('/^regex_pattern$/', $your_input)) to filter all your inputs before passing them to MySQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python C API doesn't load module I'm trying to load a python module that contains a math and numpy import in C, using the C API. I can load and run the module but, if I import the math module it doesn't work.
I'm using Arch Linux, Python 2.7.2 and gcc.
Here the codes:
#include <stdio.h>
#include <stdlib.h>
#include <python2.7/Python.h>
int main(int argc, char **argv)
{
PyObject *pName, *pModule, *pFunc, *pArg, *pDict, *pReturn, *pT1, *pT2, *pX, *pY;
int i;
double x, y;
Py_Initialize();
PySys_SetPath(".");
pName = PyString_FromString("func");
if (!pName)
{
printf("pName\n");
return 0;
}
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "get_vals");
pArg = PyTuple_New(2);
PyTuple_SetItem(pArg, 0, PyFloat_FromDouble(4.0));
PyTuple_SetItem(pArg, 1, PyFloat_FromDouble(2.0));
pReturn = PyObject_CallObject(pFunc, pArg);
pT1 = PyTuple_GetItem(pReturn, 0);
pT2 = PyTuple_GetItem(pReturn, 1);
for (i = 0; i < PyTuple_Size(pT1); i++)
{
pX = PyTuple_GetItem(pT1, i);
pY = PyTuple_GetItem(pT2, i);
x = PyFloat_AsDouble(pX);
y = PyFloat_AsDouble(pY);
Py_XDECREF(pX);
Py_XDECREF(pY);
pX = NULL;
pY = NULL;
printf("Point p position is: %.2fx, %.2fy", x, y);
}
Py_XDECREF(pName); Py_XDECREF(pModule); Py_XDECREF(pFunc); Py_XDECREF(pArg); Py_XDECREF(pDict); Py_XDECREF(pReturn); Py_XDECREF(pT1); Py_XDECREF(pT2);
Py_Finalize();
return 0;
}
func.py
from math import cos
def get_vals(width, height):
x = (1, 2)
y = (cos(3), 4)
return x, y
And how can I embbed the Python script to C without need to use the script?
A: The PySys_SetPath(".") cleared the python path, so it could no longer find any library whatsoever. What you really need to do is import sys.path and then append your string to it:
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyString_FromString("."));
(I didn't test the above code, but it should be close. Also, you should do error checking)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Loading twitter data using JSONP in Chrome I am trying to get some data from twitter using jsonp. Here is the jsfiddle for the code. So, there is nothing too complicated about the code. It even works fine inside jsFiddle window, but as soon as I put it in javascript file inside an on ready function, nothing happens in chrome. I have looked into this many times and can't seem to get anywhere. Any suggestions?
A: ffs, just spilled coffee all over my laptops keyboard. anyway,
if it's only for a one-time data fetch you dont have to use jQuery.ajax..
here is a simple solution.
<script>
function DataFromTwitter(data) {
console.log(data);
}
</script>
<script src="http://api.twitter.com/1/users/lookup.json?user_id=15,16,17,18&callback=DataFromTwitter"></script>
enjoy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: No View Based Application Template XCode I've just installed the new iOS SDK and the View Based Application template has disappeared. Any ideas as to how to get it back?
A: Now it's called "Single View Application". Take this template and it should work :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Modify build-in Object prototype String.prototype = new Number();
console.log(String.prototype.__proto__ === Number.prototype);//return false
why i cant change the prototype chain of bulid-in Object.
A: This is because the prototype property of built-in constructors1 is non-writable (also non-configurable and non-enumerable).
See the property attributes:
Object.getOwnPropertyDescriptor(String, 'prototype');
/*
configurable: false,
enumerable: false,
writable: false
*/
This is described in each built-in constructor, for the String.prototype property see :
15.5.3.1 String.prototype
...
This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
1: by "built-in constructor" I refer to the constructor functions defined on the global object: String, Number, Boolean, Object, Array, Function, Date, RegExp, Error (and other NativeError types).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add current value of EditText to a set value public void onClick(View v)
{
s.setText(s.getText().toString() + .5);
}
I want to have the value that is currently in s (EditText) to be .5 higher than it was before I clicked the button, I am a completely new to java and am unsure how to make this work. Any help is good help, Thank you in advance.
A: Edit: as others have mentioned, doubles are usually better than floats.
getText().toString() needs to be turned into a numeric value before it's possible to add .5
try {
double currentValue = Double.parseDouble(s.getText().toString())
double newValue = currentValue + 0.5;
s.setText(newValue.toString());
} catch (NumberFormatException e) {
// text in EditText was not a parsable number
...
}
A: float can cause unwanted representation. So if you want exact representation, try BigDecimal.
Modify your code
s.setText( new BigDecimal(s.getText().toString()).add(new BigDecimal( "0.5")).toString());
A: First of all use Double.parseDouble() method to convert string to double.
double val=Double.parseDouble(s.getText().toString()) + 0.5;
s.setText(String.valueOf(val);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tiny Encryption Algorithm in game engine After being warned that my simple rotation encryption wouldn't be enough for my game, I decided to look around for some good, simple alternatives. I found a simple looking TEA example here I plugged it into my game engine.
void encipher(unsigned long *const v,unsigned long *const w,
const unsigned long *const k)
{
register unsigned long y=v[0],z=v[1],sum=0,delta=0x9E3779B9,
a=k[0],b=k[1],c=k[2],d=k[3],n=32;
while(n-->0)
{
sum += delta;
y += (z << 4)+a ^ z+sum ^ (z >> 5)+b;
z += (y << 4)+c ^ y+sum ^ (y >> 5)+d;
}
w[0]=y; w[1]=z;
}
I try to plug in some numbers into it but an error is popping up:
Cast loses const qualifier
wondering If anyone knew what this means?
A: This is wrong:
unsigned long *const v
Use this instead:
unsigned long const *v
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternative to absolute positioning of shapes' points I was wondering if there was a way in WPF to create a shape (ex.: polygon, line, ...) but instead of using absolute positioning for the points of the shape, we could use something like percentage.
For example, instead of having a line with absolute positioning like this: (X1=0,Y1=50,X2=100,Y2=50), we could have a line with percentage values (0 to 1) like this (X1=0,Y1=0.5, X2=1, Y2=0.5 where 1 is equivalent to the size of the parent). So no matter what is the size of the parent of the shape, the shape would always be proportional to its parent.
That could be done with dependency properties, but I would find it much cleaner if there was a way to do it with something like I described. I hope I didn't miss something really obvious that does exactly that...
Thanks!
A: You could achieve a similar effect if you scale it by applying a scale transform on your geometry the size of the control.
<Path Width="100" Height="100" Stroke="Red">
<Path.Data>
<LineGeometry StartPoint="0 0" EndPoint="1 1">
<LineGeometry.Transform>
<ScaleTransform ScaleX="{Binding Path=Width, RelativeSource={RelativeSource FindAncestor, AncestorType=Path}}"
ScaleY="{Binding Path=Height, RelativeSource={RelativeSource FindAncestor, AncestorType=Path}}" />
</LineGeometry.Transform>
</LineGeometry>
</Path.Data>
</Path>
This should draw a red line with absolute points (0, 0) to (100, 100).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Htaccess Re-write rules problems with chrome displaying web pages Website displays correctly on IE. Chrome will not dislpay correctly or follow links. Any ideas or suggestions would be appreciated. If I remove the htaccess file, google displays correctly and links work.
Options +FollowSymLinks
Options -Indexes
RewriteEngine on
#services
RewriteRule ^index.html$ index.php [L]
RewriteRule ^showthread_([^/]*).html$ index.php?method=showthread&id=$1 [L]
RewriteRule ^postcomment.html$ index.php [L]
RewriteRule ^maturecontent.html$ index.php?method=maturecontent [L]
RewriteRule ^randomthread.html$ index.php?method=randomthread [L]
RewriteRule ^readnotapproved.html$ index.php?method=readnotapproved [L]
RewriteRule ^contacts.html$ index.php?method=contacts [L]
RewriteRule ^about.html$ index.php?method=aboutus [L]
A: .htaccess files are on the server-side: they handle requests by the client, and return resources (like HTML or image files) to the browser.
The browser, in turn, interprets this HTML code and/or resources and displays a webpage with it's rendering engine.
You said that there are differences between browsers in displaying your page. This is entirely possible, but it is impossible that the cause is an .htaccess file, because all browsers, no matter what type, are always given the same code when requesting from a server.
If there is a difference in appearance on the site between browsers, and you believe the cause to be an .htaccess file, it probably means there is an issue with your browser's cache of the page. Browsers, as they should, cache (or save locally) some data to save time as to not have to request the same data again and again every time a page is accessed. Sometimes, there are inconsistencies with this- so you can fix this problem by clearing your browser's cache.
If this is not the issue, keep checking your layout and/or URL scheme, but I assure you it has nothing to do with .htaccess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: Is there a python module for ssh that supports lots of tunnels? I am writing a program that creates reverse tunnels with ssh.
I am using Popen currently, but I am receiving an error because I have too many arguments.
So my question is:
Is there any python module that supports a lot of tunnels? (Preferably 1000+)
A: Not so much a module as a library, Twisted.Conch might be a better approach... but be warned that of all the modules in Twisted, conch can be one of the most intimidating ( atleast IMHO ).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sparrow or Cocos2D for iPhone 2D game? I want to develop a game for iPhone. For 2D game development in iPhone which one of these would be better in the long run....Sparrow or Cocos2D? I've seen that there is a scarce documentation for Sparrow framework but Sparrow forum says it is easier to develop games in Sparrow as compared to Cocos2D. So, where should i start with?
A: Both look pretty good for basic 2D development but Cocos2D seems a bit more mature (though Sparrow does seem to have a good start.
Another potential consideration is portability. The cocos2d API has been ported to android but Sparrow hasn't.
A: Cocos2d is thoroughly developed, and there are several books and a myriad of forums on the subject. I don't know too much about Sparrow. "Easy" is a relative term. If I were you, learn cocos2d.
Edit: since this question was asked, there's Apple's SpriteKit and a game engine I've built called MBTileParser.
A: If your game is making use of large amount of animation, most likely that Cocos2D is your friend. It is because Cocos2D supports PVRTC texture which reduce memory usage. PVRTC is an image format. When it is loaded into RAM, it consumes less memory at the expense of image quality. PVRTC is not yet supported in the current version of Sparrow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What's a good way of caching information in an Android App? If I have a lot of images that I would like to cache, what would be the ideal way?
I was thinking SQLite, but I'm not sure
A: There are a few different ways of persisting data with Android as delineated here http://developer.android.com/guide/topics/data/data-storage.html. The method that's best for you will depend on why you're caching the images and how you use them.
A: if you have a lot of images then use external storage else it will slow down the performance of mobile. if you store them in phone memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scala: Can I reproduce anonymous class creation with a factory method? As far as I understand it, Scala creates an anonymous class if I create a class using the new keyword and follow the class name with a constructor:
class MyClass {
def doStuff() {
// ...
}
}
val mc = new MyClass {
doStuff()
}
The nice thing being that all the code in the constructor is in the scope of the new object.
Is there a way I can reproduce this syntax where the class is created by a factory method rather than the new keyword? i.e. make the following code work:
val mf = new MyFactory
val mc = mf.MyClass {
doStuff()
}
I can't find a way to do it but Scala has so much to it that this might be pretty easy!
Using an import as suggested by @Ricky below I can get:
val mf = MyFactory;
val mc = mf.MyClass
{
import mc._
doStuff()
}
(Where the blank line before the block is needed) but that code block is not a constructor.
A: You can do this, but you still have to keep the new keyword, and create the nested class as a path-dependent type:
class Bippy(x: Int) {
class Bop {
def getIt = x
}
}
val bip = new Bippy(7)
val bop = new bip.Bop
bop.getIt // yields 7
val bop2 = new bip.Bop{ override def getIt = 42 }
bop2.getIt // yields 42
A: I don't think it's possible. However, a common pattern is to add a parameter to factory methods which takes a function modifying the created object:
trait MyClass {
var name = ""
def doStuff():Unit
}
class Foo extends MyClass {
def doStuff() { println("FOO: " + name) }
}
trait MyClassFactory {
def make: MyClass
def apply( body: MyClass => Unit ) = {
val mc = make
body(mc)
mc
}
}
object FooFactory extends MyClassFactory {
def make = new Foo
}
You can then create and modify instance with a syntax close to your example:
val foo = FooFactory { f=>
f.name = "Joe"
f.doStuff
}
A: It sounds like you're just looking to mix in a trait. Instead of calling myFactoryMethod(classOf[Foo]] which ideally would do (if Scala permitted it):
new T {
override def toString = "My implementation here."
}
you can instead write
trait MyImplementation {
override def toString = "My implementation here."
}
new Foo with MyImplementation
However, if you are just looking to get the members of the new object accessible without qualification, remember you can import from any stable identifier:
val foo = new Bar
import foo._
println(baz) //where baz is a member of foo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to pass C# array to C++ and return it back to C# with additional items? I have a C# project which is using a C++ dll. (in visual studio 2010)
I have to pass a array of int from C# code to C++ function and C++ function will add few elements in array, when control comes back to C# code, C# code will also add elements in same array.
Initially i declared a array(of size 10000) in C# code and C++ code is able to add elements (because it was just an array of int, memory allocation is same), but the problems is i have got run time error due to accessing out side of array.
I can increase size to 100000 but again i don't know how much elements C++ code will add( even it can be just 1 element).
So is there a common data structure (dynamic array) exist for both or other way to do? I am using Visual studio 2010.
Something like this i want to do.
PS: not compiled code, and here i used char array instead of int array.
C# code
[DllImport("example1.dll")]
private static extern int fnCPP (StringBuilder a,int size)
...
private void fnCSHARP(){
StringBuilder buff = new StringBuilder(10000);
int size=0;
size = fnCPP (buff,size);
int x = someCSHARP_fu();
for ( int i=size; i < x+size; i++) buff[i]='x';// possibility of run time error
}
C++ code
int fnCPP (char *a,int size){
int x = someOtherCpp_Function();
for( int i=size; i < x+size ; i++) a[ i ] = 'x'; //possibility of run time error
return size+x;
}
A: There's a good MSDN article about passing arrays between managed and unmanaged code Here. The question is, why would you need to pass the array from C# to C++ in the first place? Why can't you do the allocation on the C++ side (in your fnCPP method), and return a pointer to the C# code, and than just use Marshal.Copy( source, destination, 0, size ) as in yet another Stackoverflow question? Than in your fnCSHARP method you could copy the contents of the array to some varaiable length data structure (e.g. List).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Get a word's definition using PHP? I have something where it randomly generates words using PHP...
I have a iFrame currently linking to dictionary.com...
I don't like this because it's old and ugly.
I want to get the definition of a word and display it how I want!
Is this possible by using PHP?
A: If you want to use PHP to check the definition of a word, and you're using a Unix-based platform, check out this question:
https://stackoverflow.com/questions/415615/is-there-any-api-to-integrate-with-english-dictionary-in-php
A: If you like dictionary.com, maybe consider using its API? See http://developer.dictionary.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: media query debug I trying create a responsive site and need see where is page break in my current layout then i think about something that tell me it putting te current window size in each window resize.
I see someone telling about responsive layout in this post. A link about the function here.
I found this code but cant put to work, now is 01:09, is night here in brazil and im getiing crazy. Someone can help me ? Im testing in chrome. The author tell it put current size in corner of page in em;
<html>
<head>
<title>MediaQuery DBG</title>
<SCRIPT LANGUAGE="JavaScript" SRC="http://code.jquery.com/jquery-1.6.4.js"></SCRIPT>
<script type="text/javascript">
$(document).ready(function() {
var step = 1;
var start = 1;
var end = 2048;
var unit = "em";
var command = "";
var expression = "";
for (cs=start;cs<=end;cs=cs+step)
{
expression = "screen and (min-device-width: "+(cs-step)+unit") and (max-device-width: "+(cs)+unit")";
command = "var mql = window.matchMedia("+expression+");" +
"function handleOrientationChange(mql) {" +
" if (mql.matches) {" +
" $(\"#lblmq\").replaceWith( \"<div id='lblmq'>tamanho: "+cs+"</div>\" ); " +
" }" +
"}";
command = "mql.addListener("+command+");"
eval(command);
});
</script>
<style>
#lblmq
{
background-color: #789;
width:20em;
}
</style>
</head>
<body >
<div id='lblmq'></div>
</body>
</html>
A: You are a little lost. Perhaps these will help:
*
*http://johanbrook.com/design/css/debugging-css-media-queries
*http://responsivepx.com/?www.google.com.br%2F#1051x883&scrollbars
*http://developer.practicalecommerce.com/articles/3086-10-Frameworks-and-Tools-for-Responsive-Mobile-Optimized-Design
A: What you need is here : https://github.com/josscrowcroft/Window-Size-Bookmarklet
It works on firefox only.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: About Customized SurfaceView I inflate layer on the main frame and there is a ScrollView.
I want to draw a large image that can move left, right, top, and down on the screen.
So, I described this with a SurfaceView that I customized and addView to ScrollView,
but the Image that I want doesn't show. How can I solve this problem?
A: I don't see a need to use a SurfaceView in this case. SurfaceViews are typically used for things like Camera preview, Video playback. And there's GLSurfaceView for opengl drawing.
If you are procedurally creating the large image that you want to display, for example, via Canvas.draw methods, then you can probably simple create a custom View subclass and override onDraw (and possibly onMeasure).
Or, if you are loading a large image from disk or as a resource, just use an ImageView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CakePHP: How can i stop inserting/adding html tag during commenting of a post? This is the form for comment:
echo $this->Form->create('Comment',array('url'=>array('controller' => 'comments', 'action' =>'add', $listposts['Post']['id']) ) );
echo $this->Form->input('post_id',array('type'=>'hidden','style'=>'width:30%','value'=>$listposts['Post']['id']));
echo $this->Form->input('name',array('style'=>'width:30%'));
echo $this->Form->input('email',array('style'=>'width:30%'));
echo $this->Form->input('body',array('rows'=>'5'));
echo $this->Form->end('Comment');
The comment.php model =>
var $useTable='comments';
var $belongsTo = array('Post');
var $validate = array(
'name' => array(
'required' => true,
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Enter Name.'
),
'email' => array(
'required' => true,
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Enter Email.'
),
'body' => array(
'required' => true,
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Enter Body.'
)
);
}
But during commenting someone can type in any textbox of the comment form like this =>
<script>
alert("Hello world");
</script>
Then this alert will be displayed during the page load.
How can i stop inserting this html tags in database ?
How can i check this html block ?
A: There are two ways to handle this: sanitizing or escaping the string. Sanitizing means you strip all unwanted content out. Escaping means you "disable" any special characters in the string. You should always escape user-supplied content when outputting it:
echo htmlspecialchars($comment['body']);
Optionally you may want to sanitize the string, but that can be tricky. Look into Cake's Sanitize class. The Great Escapism is also apropos.
A: You can use: strip_tags() or htmlspecialchars()
$str = "<script>alert('Hello world');</script>";
echo "strip_tags = " . strip_tags($str);
echo "htmlspecialchars = " . htmlspecialchars($str);
Demo
A: Use this:
http://php.net/manual/en/function.htmlspecialchars.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why side-by-side installation of Visual Studio editions conflicting with Entity Framework? I have Visual Studio 2008 and 2010 (both Professional editions) installed. I installed Entity Framework 4.1 but after that neither VS-2008 nor VS-2010 is showing ADO.NET Entity Data Model in the choices when I select Add New Item from the Solution Explorer.
I tried Maintenance option of the Setup and re-installed VS 2010, but still EF is unavailable, whereas it is being listed in Windows uninstall programs list. I even tried installing NuGet package, but still it is unavailable.
How to resolve this conflict?
A: Make sure you have set your Target framework to .net 3.5 SP1+.
Also, Install Visual Studio 2008 Service Pack 1, since I've seen people not being able to see the ADO.NET Entity Data Model because they have not installed VS2008 SP1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to handle situation where page unloads due to low memory //In App Delegate
UserProfileTableViewController *uptvc = [[UserProfileTableViewController alloc]init];
UITabBarItem *tempTabBarItem4 = [[UITabBarItem alloc]initWithTitle:@"Fans" image:nil tag:FANSTAB_INDEX];
//I am setting the user id information here directly in app delegate
uptvc.userId = [[UserStockInfo sharedUserStockInfo]getUserId];
UINavigationController *navconUptvc = [[UINavigationController alloc]initWithRootViewController:uptvc];
The problem arises when my UserProfileTableViewController gets unloaded due to low memory (might be due to using the camera feature in my app). The page will fail to load properly as it is missing the 'userId' information passed in from the app delegate (as seen above). I am unable to set this userId information directly in the UserProfileTableViewController (in view did load method) as other pages might pass a different userId when pushing the page onto their stack.
Any advise on how I can resolve this issue?
A: First off, you should keep your UserProfileTableViewController object into an ivar of the app delegate (since you allocate it there). Second, make the app delegate provide that userId to the controller. Third, if the navigation controller is removed from the interface/deallocated, then even with low memory your uptvc should not be deallocated either.
View controllers maintain the full hierarchy of controllers, even when running out of memory, what's deleted are views, and anything you tell them to remove.
You most certainly want to keep the UINavigationController in an ivar of the AppDelegate as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using multiple conditions in a do...while loop So I'm making a program that asks a user if they want to do something. The answer is as simple as Y/N. I would like the program to be able to accept both capital and lowercase "Y". Problem is, when I type while (answer == 'Y', answer == 'y') only the lowercase "Y" is accepted. If I type while (answer == 'y', answer == 'Y')
What am I doing wrong?
(More info: "answer" is the name of my "char" variable, and I'm using the "iostream", "cstdlib", and "string" libraries)
A: You need to use the 'logical or' operator ||
So your code would become while (answer =='Y' || answer == 'y')
A: You should be using the logical operator for or ("||"):
while( answer=='Y' || answer=='y' ){
//code
}
Also, FFR:
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
A: The problem is that you're using the comma operator instead of an "or" operator, like the logical or, ||.
From Wikipedia:
In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type). The comma operator has
the lowest precedence of any C operator, and acts as a sequence point.
(emphasis added)
A: Its the comma operator's property to return the second operand only (it executes both operands though). Consider the following code:
int main() {
int i=1, j=2, k=3;
int l= (i,cout<<"print; ",j,k);
cout << l;
}
Because of the comma operator, output is 'print; 3'.
So try avoiding this comma operator in your code, and as stated above by many, use instead a logical (||) operator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Mix transactional replication and log shipping? I've replicated a large database (close to 1TB) to three remote servers using pushing transactional replication. The subscribers are read-only. A lot of data is inserted and updated (from other sources) in one day every month. It always fail the replication after the day and we manually initialize the replication from backup every month.
Is it possible to switch to log shipping before the inserting day and switch back to transactional replication after the bulk insertions are log shipped? So there is no need to copy the big backup file for re-initialization?
A: No. Transactional replication is logical while log shipping is physical. You can't switch at will between the two. But if your subscribers are read only to start with then transactional replication can be replaced out of the box with log shipping, at the cost of a slight delay in updates and having to disconnect readers on the stand-by sites every time a log is being applied (usually this is nowhere near as bad as it sounds). Given how much more efficient and less problematic log shipping is compared to transactional replication, I would not hesitate for a single second in doing this replace for good.
A: I question your need to re-initialize on a scheduled basis. I've had replication topologies go for a really long time without having the need to re-init. And when we did, it was only because there was a schema change that didn't play nice. When you say that the large amount of data fails replication, what does that mean? Replication will gladly deliver large data changes that to the subscribers. If you're running afoul of latency limits, you can either increase those or break down large transactions into smaller ones at the publisher. You also have the option of setting the MaxCmdsInTran option for the log reader agent to have it break up your transactions for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bing Search API: Narrow by date In it's current version, is it possible to use Bing's "Narrow By Date" feature when accessing it's API?
I cannot find any information about how to narrow the results such that it only shows results from the "past 24 hours" or "past week" (and so on).
The website/documentation isn't exactly clear on what I can and cannot do, and how. Do any of you know whether it's possible or not?
I can see on their Advanced Search Keywords page that you can use other narrowing features (region, language, hasfeed, etc.) here: http://onlinehelp.microsoft.com/en-ca/bing/ff808421.aspx
If you need any more context or information please ask. Thank you for your patience and help.
A: The Bing search API is pretty vague in terms of limiting results and what you can and cannot use. After testing various words and placement to try and get date to work, I'm fairly certain that there is not a way to use a date to narrow results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Rotating CALayer of NSImageView 90 degrees I am trying to rotate the CALayer of an NSImageView. My problem is that the anchorPoint appears to be (0.0, 0.0) by default but I want it to be the center of the image (Apple's documentation indicates the default should be the center (0.5, 0.5), but it's not on my system OS X 10.7), When I modify the anchor point the origin of the center of the image shifts to the lower left corner.
Here's the code I am using to rotate the layer:
CALayer *myLayer = [imageView layer];
CGFloat myRotationAngle = -M_PI_2;
NSNumber *rotationAtStart = [myLayer valueForKeyPath:@"transform.rotation"];
CATransform3D myRotationTransform = CATransform3DRotate(myLayer.transform, myRotationAngle, 0.0, 0.0, 1.0);
myLayer.transform = myRotationTransform;
CABasicAnimation *myAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
myAnimation.duration = 1.0;
myAnimation.fromValue = rotationAtStart;
myAnimation.toValue = [NSNumber numberWithFloat:([rotationAtStart floatValue] + myRotationAngle)];
[myLayer addAnimation:myAnimation forKey:@"transform.rotation"];
myLayer.anchorPoint = CGPointMake(0.5, 0.5);
[myLayer addAnimation:myAnimation forKey:@"transform.rotation"];
A: It appears that changing the anchor point of something also changes it's position. The following snippet fixes the problem:
CGPoint anchorPoint = CGPointMake(0.5, 0.5);
CGPoint newPoint = CGPointMake(disclosureTriangle.bounds.size.width * anchorPoint.x,
disclosureTriangle.bounds.size.height * anchorPoint.y);
CGPoint oldPoint = CGPointMake(disclosureTriangle.bounds.size.width * disclosureTriangle.layer.anchorPoint.x,
disclosureTriangle.bounds.size.height * disclosureTriangle.layer.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint,
[disclosureTriangle.layer affineTransform]);
oldPoint = CGPointApplyAffineTransform(oldPoint,
[disclosureTriangle.layer affineTransform]);
CGPoint position = disclosureTriangle.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
disclosureTriangle.layer.position = position;
disclosureTriangle.layer.anchorPoint = anchorPoint;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Pygame group update takes no arguments I've read up on similar problems elsewhere, but it says just to add 'self' to the function definition. When I check the file it's self, it actually already has the self keyword first! Here's the traceback:
Traceback (most recent call last):
File "C:\Users\Brenda\Documents\The Nick Folder\Mobile Fortress War 3\MFWRT3 - TileClass test\Title.pyw", line 142, in <module>
SelectServer.main()
File "C:\Users\Brenda\Documents\The Nick Folder\Mobile Fortress War 3\MFWRT3 - TileClass test\SelectServer.pyw", line 44, in main
Main.mainloop()
File "C:\Users\Brenda\Documents\The Nick Folder\Mobile Fortress War 3\MFWRT3 - TileClass test\Main.pyw", line 72, in mainloop
globals.alltiles.update()
File "C:\Python32\lib\site-packages\pygame\sprite.py", line 462, in update
s.update(*args)
TypeError: update() takes no arguments (1 given)
And I called it like this:
globals.alltiles.update()
Can anyone help out?
A: i am a bit late but it's probably because of improper declaration of the update method for each card (which i assume is subclassing pygame.sprite.Sprite)
it should be declared as "def update(self)" and not "def update()"
A: Without code to debug it's going to be a guessing game, but for future reference, sprite groups are created like this:
#first create a sprite class
class Card(pygame.sprite.Sprite):
def __init__(self,img,pos):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(os.path.join('img','cards', img))
self.rect = self.image.get_rect()
self.rect.center = pos
#then create a group
mycards = pygame.sprite.Group()
#then add a sprite to the group
holders.add(Card('ace_spade.jpg',coord))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android animation - frame-by-frame? So, I'm new to programming with android and one of the first thing I'm trying to do is create a basic animation that starts on its own. Nothing complicated, just a looping animation. I am trying to stick with frame-by-frame because it seems the most basic and easiest to understand. I have looked at many tutorials/websites/videos (including the android dev sites) on how to do this and can't figure out what I'm doing wrong. I'm sure I have a simple logic error somewhere. Below is my posted code. Can someone help me out? Thank you for the help! (Also, as a side note this is specifically running on a NookColor emulator, according to Nook Developer site, the nook runs the latest android. Unfortunately the Nook site gives no tutorials or anything useful, only the same links to Android developers.)
//main class
public class WallpaperActivity extends Activity {
AnimationDrawable animSequence;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView animImg = (ImageView) findViewById(R.id.animatepic);
animImg.setBackgroundResource(R.drawable.animation);
animSequence = (AnimationDrawable) animImg.getBackground();
}
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
animSequence.start();
}
}
//animation.xml class ( << this is not my main.xml class)
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/animatepic" android:oneshot="false" >
<item android:drawable="@drawable/a" android:duration="200" />
<item android:drawable="@drawable/b" android:duration="200" />
<item android:drawable="@drawable/c" android:duration="200" />
<item android:drawable="@drawable/d" android:duration="200" />
<item android:drawable="@drawable/e" android:duration="200" />
<item android:drawable="@drawable/f" android:duration="200" />
<item android:drawable="@drawable/g" android:duration="200" />
<item android:drawable="@drawable/h" android:duration="200" />
<item android:drawable="@drawable/i" android:duration="200" />
<item android:drawable="@drawable/j" android:duration="200" />
<item android:drawable="@drawable/k" android:duration="200" />
<item android:drawable="@drawable/l" android:duration="200" />
<item android:drawable="@drawable/m" android:duration="200" />
<item android:drawable="@drawable/n" android:duration="200" />
<item android:drawable="@drawable/o" android:duration="200" />
</animation-list>
A: Did you say what error you were getting?
In any case, your code example seems to have been updated.
Here is its zip file you can download.
A: ImageView animImg = (ImageView) findViewById(R.id.animatepic);
animImg.setBackgroundResource(R.drawable.animation);
animSequence = (AnimationDrawable) animImg.getBackground();
animSequence.start();
try this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make a single if-statement wait before executing in Java? I am trying to make Java wait for 1 second before evaluating an if statement to see if it should change a boolean.
I have it set up where if Rectangle r intersects Rectangle y, a boolean "Intersect" becomes true and r moves backwards. 1 second later, I want an if-statement to check if r is still intersecting y. If not, "Intersect" becomes false again and r stops moving backwards. How can I do this? These statements are in the same Thread and there is animation involved so Thread.sleep() hasn't worked as it makes the animation very jumpy.
Here is the snippets of code that are relevant to the problem:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JFrame {
boolean p1Intersect=false;
private class Move1 extends Thread {
public void run() {
if((p1horizontal.intersects(grass1)&&(hleft==true||hright==true)&&p1Intersect!=true) { //Normal speed
p1Speed = 5;
}
if(p1horizontal.intersects(edge2)&&hleft==true) { //moves backwards after collision as long as p1Intersect = true
p1Speed=-4;
p1Intersect=true;
}
if((p1horizontal.intersects(edge2)&&hleft==true)==false) { //This is the statement that I would like to wait for 1 second before executing
p1Intersect=false;
}
A: In principle, what you want to do is set a timer that will fire one second after your first event is detected. If, when that event fires, check to see whether your rectangles are still intersecting. If so, take whatever action you need at that point.
As you noticed, Thread.sleep() will halt the execution of your whole thread and nothing else will happen there. That will also make your animation jumpy.
A: In game design, try keeping logic in main thread (that is, I would avoid using a timer). I suggest the following solution:
When intersection is detected, store the system time in a long,
using long intersectTime = System.currentTimeMillis() .
Now, in the second if statement, just check for the extra condition
System.currentTimeMillis()-intersectTime>1000
since 1000 milliseconds = 1 second.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Play! Framework app on EC2 I want to deploy and run my Play! Framework app on EC2.
I have installed the Play! Framework on one instance, now I don't want to copy my source code over but instead I want to "build" my app into libraries/jar/wars and copy the binary over and have play run against the binaries. Does Play! support that?
A: You can deploy your play application as standalone java application without installing play framework on EC2. You will need to generate distribution file of your play application by following step
*
*Navigate to project folder
*type play
*type dist
This will generate project snapshot zip file in dist folder of your play application.
Upload that zip file to EC2 instance and extract in some folder. There you will find a start shell script file. Just execute that script file
Note: To make file executable type: chmod 777 start
./start
This will publish application and opens port to receive http request on default port 9000. If you want to change port when executing file,
./start -Dhttp.port=8080
This will publish application on port 8080
A: Well, the Play documentation mention it clearly that you can.
play war myapp -o myapp.war
Take a look on Play documentation, its very clear.
A: No, there is no native single-file format for play apps.
But, yes you can use any archive format for your purpose. Instead of running :
play command myfile
you'll do something like this :
unzip myfile; play command file;
Plus, you could always try using wars and rune those across multiple tomcats, but it would be a waste of ressources as native play server is better.
A: If you are using activator you can exploit its stage command which prepares all dependent libraries and compiles your code.
In my blog, I have tried to explain the whole deployment scenario of an Play application to an EC2 instance. Here is the link for more detail:
http://www.javacirecep.com/cloud/deploy-play-scala-applications-on-amazon-ec2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compile Boost Program I'm having trouble understanding the basics of compiling a boost program. I'm working with Fedora 15, with boost installed through yum in /usr/include/boost. I have boost build installed as well.
I'd really like to know how to link with the boost library and compile the following example under the terminal, and with boost-jam/build.
//
// reference_counted.cpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <vector>
using boost::asio::ip::tcp;
// A reference-counted non-modifiable buffer class.
class shared_const_buffer
{
public:
// Construct from a std::string.
explicit shared_const_buffer(const std::string& data)
: data_(new std::vector<char>(data.begin(), data.end())),
buffer_(boost::asio::buffer(*data_))
{
}
// Implement the ConstBufferSequence requirements.
typedef boost::asio::const_buffer value_type;
typedef const boost::asio::const_buffer* const_iterator;
const boost::asio::const_buffer* begin() const { return &buffer_; }
const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
private:
boost::shared_ptr<std::vector<char> > data_;
boost::asio::const_buffer buffer_;
};
class session
: public boost::enable_shared_from_this<session>
{
public:
session(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
using namespace std; // For time_t, time and ctime.
time_t now = time(0);
shared_const_buffer buffer(ctime(&now));
boost::asio::async_write(socket_, buffer,
boost::bind(&session::handle_write, shared_from_this()));
}
void handle_write()
{
}
private:
// The socket used to communicate with the client.
tcp::socket socket_;
};
typedef boost::shared_ptr<session> session_ptr;
class server
{
public:
server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
session_ptr new_session(new session(io_service_));
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void handle_accept(session_ptr new_session,
const boost::system::error_code& error)
{
if (!error)
{
new_session->start();
new_session.reset(new session(io_service_));
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
}
private:
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: reference_counted <port>\n";
return 1;
}
boost::asio::io_service io_service;
using namespace std; // For atoi.
server s(io_service, atoi(argv[1]));
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
As requested here is the giant block of error:
/tmp/ccvtengY.o: In function `__static_initialization_and_destruction_0(int, int)':
example.cpp:(.text+0x182): undefined reference to `boost::system::generic_category()'
example.cpp:(.text+0x18e): undefined reference to `boost::system::generic_category()'
example.cpp:(.text+0x19a): undefined reference to `boost::system::system_category()'
/tmp/ccvtengY.o: In function `boost::system::error_code::error_code()':
example.cpp:(.text._ZN5boost6system10error_codeC2Ev[_ZN5boost6system10error_codeC5Ev]+0x17): undefined reference to `boost::system::system_category()'
/tmp/ccvtengY.o: In function `boost::asio::error::get_system_category()':
example.cpp:(.text._ZN5boost4asio5error19get_system_categoryEv[boost::asio::error::get_system_category()]+0x5): undefined reference to `boost::system::system_category()'
/tmp/ccvtengY.o: In function `boost::asio::detail::posix_tss_ptr_create(unsigned int&)':
example.cpp:(.text._ZN5boost4asio6detail20posix_tss_ptr_createERj[boost::asio::detail::posix_tss_ptr_create(unsigned int&)]+0x19): undefined reference to `pthread_key_create'
/tmp/ccvtengY.o: In function `boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context>::~posix_tss_ptr()':
example.cpp:(.text._ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceEE7contextEED2Ev[_ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceEE7contextEED5Ev]+0x15): undefined reference to `pthread_key_delete'
/tmp/ccvtengY.o: In function `boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context>::operator boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context*() const':
example.cpp:(.text._ZNK5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceEE7contextEEcvPS6_Ev[boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context>::operator boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context*() const]+0x15): undefined reference to `pthread_getspecific'
/tmp/ccvtengY.o: In function `boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::strand_service::strand_impl>::context>::~posix_tss_ptr()':
example.cpp:(.text._ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_14strand_service11strand_implEE7contextEED2Ev[_ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_14strand_service11strand_implEE7contextEED5Ev]+0x15): undefined reference to `pthread_key_delete'
/tmp/ccvtengY.o: In function `boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context>::operator=(boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context*)':
example.cpp:(.text._ZN5boost4asio6detail13posix_tss_ptrINS1_10call_stackINS1_15task_io_serviceEE7contextEEaSEPS6_[boost::asio::detail::posix_tss_ptr<boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context>::operator=(boost::asio::detail::call_stack<boost::asio::detail::task_io_service>::context*)]+0x20): undefined reference to `pthread_setspecific'
collect2: ld returned 1 exit status
A: It compiles fine for me with g++ -lboost_system-mt -pthread.
A: For a list of linkable boost libraries:
for f in $(ls -1 /usr/lib64/libboost_*.a); do basename $f .a | cut -c 4-99; done;
A: It looks like you may need to explicitly include the boost library path when you build. What is your exact build command? Do you have something like -L/usr/lib/boost in the command?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dictionary containing objects with Timers. Need to find out which object's timer is calling the elapsed event i have this poll class
class Poll
{
public string question { get; set; }
public Timer pollTimer { get; set; }
public List<string> userVoted { get; set; }
public Dictionary<string, int> choices { get; set; }
public bool PollRunning { get; set; }
public Poll(string question,Dictionary<string,int> choices)
{
this.question = question;
this.choices = choices;
this.pollTimer = new Timer(15000);
this.PollRunning = true;
this.userVoted = new List<string>();
}
public string pollResults()
{
string temp = "";
foreach (KeyValuePair<string, int> keyValuePair in choices)
{
temp = temp + keyValuePair.Key + " " + keyValuePair.Value + ", ";
}
return string.Format("Poll Results: {0}", temp);
}
}
and I have this code in a StartPool method
static Dictionary<Channel, Poll> polls = new Dictionary<Channel, Poll>();
public void startPool(Channel channel)
{
polls.Add(channel, new Poll(question, tempdict));
polls[channel].pollTimer.Elapsed += new ElapsedEventHandler(pollTimer_Elapsed);
polls[channel].pollTimer.Start();
}
When this method gets called
static void pollTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//do stuff to the poll that called this.
}
I need know what poll object's timer is calling this method
so I can do polls[channel].pollTimer.Stop(); and do polls[channel].pollResults();
As it is I have no idea which poll stop and post results for when this runs
i'm willing to post entire solution if that will help you help me.
A: The problem with the way you've designed the Poll class is that the Poll class doesn't completely do its job. You require other classes to know how to start and stop polling, meaning half of the polling implementation is inside the Poll class and half of the implementation is outside the Poll class. If you're going to create a Poll class, hide ALL the implementation details from everyone else.
Here is what I mean. I would create an event in Poll like this:
public event EventHandler<ElapsedEventArgs> Elapsed;
In Poll's constructor, add this line:
this.pollTimer.Elapsed += pollTimer_elapsed;
and the pollTimer_elapsed looks like this:
private void pollTimer_elapsed(object sender, ElapsedEventArgs e)
{
var han = this.Elapsed;
if (han != null)
han(this, e); // Fire the Elapsed event, passing 'this' Poll as the sender
}
Add a new public method in Poll to start the timer:
public void Start()
{
this.pollTimer.Start();
}
So now your startPool method looks like this:
public void startPool(Channel channel)
{
polls.Add(channel, new Poll(question, tempdict));
polls[channel].Elapsed += poll_Elapsed;
polls[channel].Start();
}
static void poll_Elapsed(object sender, ElapsedEventArgs e)
{
//sender is now a Poll object
var poll = sender as Poll;
// Now you can do poll.pollTimer.Stop()
// Or better yet, add a Stop method to the Poll class and call poll.Stop()
}
IMHO this approach is slightly better because the Poll object is hiding more of its implementation from external objects. From startPool's point of view, the Poll class is simpler to use, and you also don't require anything outside of your Poll class to know about Timers.
A: you can add a property :
public bool pollTimerElapsed { get; set; }
and subscribe a handler in the contsructeur of Poll of Elapsed event of pollTimer where you set to true the property pollTimerElapsed
then you can filter elapsed Polls by this property
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Small code, value isn't carried I've got this problem, I have a java file that obtains 2 variables from another file and is supposed to add them together and return the summed value. So far it works on obtaining the values aFirst and aSecond but I'm not sure why value one and two is lost (is back at 0) when it gets to the sum method. This is for an assignment I have for homework.
public class Pair
{
private double one, two ;
public Pair(double aFirst, double aSecond)
{
double one = aFirst;
double two = aSecond;
}
public double sum()
{
double xys = one + two;
return(xys);
}
}
A: the problem is the constructor. you are creating local variables and not using the class fields
private double one, two ;
public Pair(double aFirst, double aSecond)
{
this.one = aFirst;
this.two = aSecond;
}
you can do it without the "this." but dont put type ahead
A: You're declaring one and two as local variables, shadowing the instance variables.
A: Use this to access the class member variables in override cases when you have the same variable name in local scope and in the class members.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Optimize - Select whether record/condition exists in another table -TSQL CREATE TABLE IntegrationLog (
IntegrationLogID INT IDENTITY(1,1) NOT NULL,
RecordID INT NOT NULL,
SyncDate DATETIME NOT NULL,
Success BIT NOT NULL,
ErrorMessage VARCHAR(MAX) NULL,
PreviousError BIT NOT NULL --last sync attempt for record failed for syncdate
)
My goal here, is to return every recordid, erorrmessage that has not been followed by a complete success, exclude where for the recorid there was a ( Success == 1 and PreviousError == 0) that occurred after the last time this error happened. For this recordid, I also want to know whether there has ever been a success ( Partial or otherwise ) that has ever happened.
Or in other words, I want to see errors and the record they occurred on that haven't been fixed since the error occurred. I also want to know whether I have ever had a success for the particular recordid.
This works, but I am curious if there is a better way to do this?
SELECT errors.RecordID ,
errors.errorMessage,
CASE WHEN PartialSuccess.RecordID IS NOT NULL THEN 1
ELSE NULL
END AS Resolved
FROM ( SELECT errors.RecordID ,
errors.ErrorMessage ,
MAX(SyncDate) AS SyncDate
FROM dbo.IntegrationLog AS Errors
WHERE errors.Success = 0
GROUP BY errors.RecordID ,
errors.ErrorMessage ,
errors.ErrorDescription
) AS Errors
LEFT JOIN dbo.IntegrationLog AS FullSuccess ON FullSuccess.RecordID = Errors.RecordID
AND FullSuccess.Success = 1
AND FullSuccess.PreviousError = 0
AND FullSuccess.SyncDate > Errors.SyncDate
LEFT JOIN ( SELECT partialSuccess.RecordID
FROM dbo.IntegrationLog AS partialSuccess
WHERE partialSuccess.Success = 1
GROUP BY partialSuccess.RecordID
) AS PartialSuccess ON Errors.RecordID = PartialSuccess.RecordID
WHERE FullSuccess.RecordID IS NULL
I also created a pastebin with a few different ways I saw of structuring the query. http://pastebin.com/FtNv8Tqw
Is there another option as well?
If it helps, background for the project is that I am trying to sync records that have been updated since their last successful sync ( Partial or Full ) and log the attempts. A batch of records is identified to be synced. Each record attempt is logged. If it failed, depending on the error it might be possible try to massage the data and attempt again. For this 'job', the time we collected the records is used as the SyncDate. So for a given SyncDate, we might have records that successfully synced on the first try, records we gave up on the first attempt, records we massaged and were able to sync, etc. Each attempt is logged.
Does it change anything if instead of wanting to know whether any success has occurred for that recordid, that I wish to identify whether a partial success has occurred since the last error occurrence.
Thank You! Suggestions on my framing of the question are welcome as well.
A: You should probably show query plan take a look at where most of the time is being spent and index appropriately.
That said one thing you can try is to use the Window Function ROW_NUMBER instead of MAX.
WITH cte
AS (SELECT errors.recordid,
errors.errormessage,
CASE
WHEN partialsuccess.recordid IS NOT NULL THEN 1
ELSE NULL
END
AS resolved,
Row_number() OVER (PARTITION BY errors.recordid ORDER BY
syncdate
DESC)
rn
FROM integrationlog error
LEFT JOIN integrationlog fullsuccess
ON fullsuccess.recordid = errors.recordid
AND fullsuccess.success = 1
AND fullsuccess.previouserror = 0
AND fullsuccess.syncdate > errors.syncdate
LEFT JOIN (SELECT partialsuccess.recordid
FROM dbo.integrationlog AS partialsuccess
WHERE partialsuccess.success = 1
GROUP BY partialsuccess.recordid) AS partialsuccess
ON errors.recordid = partialsuccess.recordid
WHERE errors.success = 0)
SELECT
recordid,
errormessage,
resolved
FROM cte
WHERE rn = 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Including Smarty templates from sub-folders using relative paths I have created a folder structure for smarty templates
f
.f1
..template1.tpl
..test.tpl
template1.tpl
the template_dir path is pointed to folder 'f/'
in test.tpl is the code below
{include file="template1.tpl"}
{include file="../template1.tpl"}
This code does not work. Any idea where I might be going wrong?
I read about $smarty-> use_sub_dirs = true, which did create subfolders in my template_c folder but I'm still not able to include templates as per the above code.
Thanks in advance.
A: just add f1 to your URL
{include file="f1/template1.tpl"}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Difference between foreach and iterate in smarty What is difference between {iterate} and {foreach} in smarty tpl files?
are they different in using 'from' phrase?
A: As far as I know, there is no command called "iterate" in Smarty. There is, however, a command called {section} that is often confused with {foreach}.
From the documentation at Smarty.net:
The {foreach} loop can do everything a {section} loop can do, and has
a simpler and easier syntax. It is usually preferred over the
{section} loop.
Also:
{section} loops cannot loop over associative arrays, they must be
numerically indexed, and sequential (0,1,2,...). For associative
arrays, use the {foreach} loop.
Hopefully that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: google app engine python uploading application first time i'm trying to upload my app engine project for the very first time and i have no clue why it is not working. the error from my terminal is:
[me][~/Desktop]$ appcfg.py update ProjectDir/
Application: tacticalagentz; version: 1
Host: appengine.google.com
Starting update of app: tacticalagentz, version: 1
Scanning files on local disk.
Error 404: --- begin server output ---
This application does not exist (app_id=u'tacticalagentz').
--- end server output ---
i'm using python 2.6.5 and ubuntu 10.04.
not sure if this is relevant, but i just created a google app engine account today. and i also just created the application today (like a couple of hours ago). this is really frustrating because i just want to upload what i have so far (as a demo). in my app.yaml this is my first line:
application: tacticalagentz
Furthermore, i checked on my admin console, and i CLEARLY see the app id right there, and it matches letter for letter with the app id in my app.yaml
could someone please enlighten me and tell me what i am doing wrong? or is it something beyond my comprehension (like indexing issue with Google that they need time to index my app id) ?
thank you very much in advance
A: apparently adding the "--no_cookies" parameter will work
appcfg.py update --no_cookies ProjectDir/
the way i was able to find my answer was by uploading my app from my Mac OS X (thank god i have linux mac and windows). AppEngine on Mac OS X comes with a GUI interface, and it worked for uploading. so then i found the command they used in the console, which included "--no_cookies". perhaps if you run into similar issues in the future, this is one approach to getting the answer
A: App Engine for Java have the same problem. The problem is about account login.
If you are using Eclipse, use Sign In button.
If u are using command-line, use "-e" option, like this:
appcfg.sh -e [email protected] update yoursite/
A: I had the same problem. When I changed the name of the app I used in the launcher to match the one in the app engine, It worked without any problem. The way I figured out, it was the name mismatch which caused the problem. You can see the name of your registered app in the admin console of app engine.(https://appengine.google.com/)
A: Here's what fixed it for me:
i had an instance of dev_appserver.py myProjDirectory/ on a different terminal.
i guess the scripts are somehow linked and aren't thread safe
A: An alternate option that worked for me is to just "Clear Deployment Credential" from the Control option of the GUI. When the app was deployed after this, it opened a google page to allow GAE to access the user profile and then deployment was successful.
A: The key bit is
This application does not exist (app_id=u'tacticalagentz').
which is telling you that appspot.com doesn't know of an application by that name. The admin console (https://appengine.google.com/) shows your applications. Check there. You might have made an inadvertent typo when you registered the app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: excel vba - check if radio button is selected?
I'm trying to check the value of these simple radio button groups but my syntax is off, does anyone know what to change?
Note: they are Excel Option Buttons not ActiveX ones and they are not on a userform.
If Worksheets("Input").Shapes("Option Button 3").Select.Value = xlOn Then
MsgBox "fir"
ElseIf Worksheets("Input").Shapes("Option Button 4").Select.Value = xlOn Then
MsgBox "sec"
Else
MsgBox "none" 'in case they were deleted off the sheet
End If
A: Try this
Sub ZX()
Dim shp3 As Shape
Dim shp4 As Shape
On Error Resume Next
Set shp3 = Worksheets("Input").Shapes("Option Button 3")
Set shp4 = Worksheets("Input").Shapes("Option Button 4")
On Error Goto 0
If shp3 Is Nothing Then
If shp4 Is Nothing Then
MsgBox "none" 'in case they were deleted off the sheet
ElseIf shp4.ControlFormat.Value = xlOn Then
MsgBox "sec"
Else
MsgBox "Only Button 4 exists and it is off"
End If
Else
If shp3.ControlFormat.Value = xlOn Then
MsgBox "fir"
Else
If shp4 Is Nothing Then
MsgBox "Only Button 3 exists and it is off"
ElseIf shp4.ControlFormat.Value = xlOn Then
MsgBox "sec"
Else
MsgBox "Both exists, both are off"
End If
End If
End If
End Sub
A: I had a similar problem. To solve it, I decided to use a toggle button with this macro VBA code to access its value and toggle my display accordingly to it:
Call ThisWorkbook.Sheets("MySheet").toggleDisplay(CBool(ThisWorkbook.Sheets("MySheet").ToggleButton1.Value))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Inserting Hebrew text into MySQL using PHP (garbage text) I'm facing a weird problem with inserting hebrew text into mysql.
Basically the problem is :
I have a php script which picks up hebrew text from a csv file then send it to mysql database. The charset of both database and all fields of tables are set to UTF8 and collation to utf8_bin. But when I insert it using mysql, random garbage value appears inside the text which renders it completely useless for output. NOTE : I can still see half of the words appear correctly.
Here is my homework which might help you in understanding :
1. As I mentioned the table charset and collation are utf8.
2. I've send header('Content-Type: text/html; charset=utf-8')
3. If I echo out the text, it appears perfectly. When I convert it using utf-8_encode
it get converted properly. (eg. שי יפת get converted to ×©× ×פת)
4. When I use utf-8_decode on the converted variable and use echo, it still displays perfectly.
5. I've used these after mysql_connect
mysql_query("SET character_set_client = 'utf8';");
mysql_query("SET character_set_result = 'utf8';");
mysql_query("SET NAMES 'utf8'");
mysql_set_charset('utf8');
and even tried this :
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con)
*Added default_charset = "UTF-8" in my php.ini file.
*I am unaware of the encoding used in csv file but when I open it with notepad++ the encoding is utf-8 without BOM.
*Here is a sample of the actual garbage :
original text : שי יפת
text after utf8_encode : ×©× ×פת
text after utf8_decode in same script : שי יפת (perfect)
text send to mysql database : ש×? ×?פת (notice the ? in between)
text if we echo from mysql : ש�? �?פת (the output is close)
*Used addslashes and stripslashes before utf8_encoding. (even tried after no luck)
*Server is on windows running xamp 1.7.4
*
*Apache 2.2.17
*MySQL 5.5.8 (Community Server)
*PHP 5.3.5 (VC6 X86 32bit)
EDIT 1 : Just to clarify that I did searched the site for similar questions and did implemented the suggestions found (SET NAME UTF8 and alot other options etc) but it didn't work out. So please don't mark this question as repeat.
EDIT 2 :
Here is the full script :
<?php
header('Content-Type: text/html; charset=utf-8');
if (isset($_GET['filename'])==true)
{
$databasehost = "localhost";
$databasename = "what_csv";
$databaseusername="root";
$databasepassword="";
$databasename= "csv";
$fieldseparator = "\n";
$lineseparator = "@contact\n";
$csvfile = $_GET['filename'];
/********************************/
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_query( "SET NAMES utf8" );
mysql_set_charset('utf8',$con);
/*
mysql_query("SET character_set_client = 'utf8';");
mysql_query("SET character_set_result = 'utf8';");
mysql_query("SET NAMES 'utf8'");
mysql_set_charset('utf8');
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con);
*/
@mysql_select_db($databasename) or die(mysql_error());
$lines = 0;
$queries = "";
$linearray = array();
foreach(explode($lineseparator,$csvcontent) as $line) {
$Name="";
$Landline1="";
$Landline2="";
$Mobile="";
$Address="";
$Email="";
$IMEI="temp";
$got_imei=false;
//echo $line.'<br>';
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
$linearray = explode($fieldseparator,$line);
//check for values to insert
foreach($linearray as $field)
{
if (is_numeric($field)){ $got_imei=true;$IMEI=trim($field);}
if (stristr($field, 'Name:')) {$Name=trim(str_replace("Name:", "", $field));}
if (stristr($field, 'Landline:')) {$Landline1=trim(str_replace("Landline:", "", $field));}
if (stristr($field, 'Landline2:')) {$Landline2=trim(str_replace("Landline2:", "", $field));}
if (stristr($field, 'Mobile:')) {$Mobile=trim(str_replace("Mobile:", "", $field));}
if (stristr($field, 'Address:')) {$Address=trim(str_replace("Address:", "", $field));}
if (stristr($field, 'Email:')) {$Email=trim(str_replace("Email:", "", $field));}
}
if ($got_imei==true)
{
$query = "UPDATE $databasetable SET imei=$IMEI where imei='temp'";
mysql_query($query);
}
else if (($Name=="") && ($Landline1=="" ) && ($Landline2=="") && ($Mobile=="") && ($Address=="")) {echo "";}
else
{
//$Name = utf8_encode("$Name");
//$Name = addslashes("$Name");
$Name = utf8_encode(mysql_real_escape_string("$Name"));
echo"$Name,$Landline1,$Landline2,$Address,$IMEI<br>";
$query = "insert into $databasetable (imei, name, landline1, landline2, mobile, address, email) values('$IMEI','$Name', '$Landline1','$Landline2','$Mobile', '$Address', '$Email');";
mysql_query($query);
$Name = utf8_decode(($Name));
echo $Name."<br>";
}
}
@mysql_close($con);
echo "Found a total of $lines records in this csv file.\n";
}
?>
<form>
Enter file name <input type="text" name="filename" /><br />
<input type="submit" value="Submit" /><br>
NOTE : File must be present in same directory as this script. Please include full filename, for example filename.csv.
</form>
Here is a sample of csv file :
@contact
Name: שי יפת
Mobile: 0547939898
@IMEI
355310042074173
EDIT 3 :
If I directly enter the string via cmd I get this warning:
Warning Code : 1366
Incorrect string value: '\xD7\xA9\xD7\x99 \xD7...' for column 'name' at row 1
Here is something I found on the net that could be related, any help?
http://bugs.mysql.com/bug.php?id=30131
A: I had this problem too. Thees lines solve it:
mysql_query( "SET NAMES utf8" );
mysql_query( "SET CHARACTER SET utf8" );
Shana Tova
A: Use Text/LongText instead of varchar. Also use Collation as utf8_general_ci
Hope this will help you @Ajit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to interprete gprof output I just profiled my program with gprof and got this:
100.01 0.01 0.01 23118 0.43 0.43 std::vector<int, std::allocator<int> >::operator=(std::vector<int, std::allocator<int> > const&)
Which confuses me, as it says that it is using 100.01% of the time using the = operator. Am i right guessing that this means it is just copying data all along and is there a limit of how much memory a program is allowed to use?
A: It looks like you profiled too short a run to get any useful data.
The way gprof works is that it periodically interrupts your code to see what function you were in at that instant. If the code isn't running very long, it may only collect a small number of data points. In contrast, callgrind instruments your code and tracks each function call and return and checks how much time was spent between hooks. This gives it a much fuller view, even if the run is short. This has a downside, it slows the program down quite a bit.
Another advantage of callgrind is that you can stop, start, and save its data collection. So if you don't want to monitor your program's startup or want to catch only the time it's doing a particular thing, you can. Plus, there's a tool called kcachegrind that can give you a great graphical view of the data you collected.
If you can tolerate slowing your program down by a factor of four while you're running it for testing, use callgrind instead -- it's part of valgrind.
If you're using Linux, your distribution probably has a valgrind package and a package that includes kcachegrind (which may be called kdesdk or something else). It's worth the time invested to learn how to use them (they are not as easy to get started with as gprof). I think you'll find the kcachegrind's GUI impressive (look at this screenshot). And, as its name suggests, it can analyze cachegrind output too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to embed strings inside code of executable? I have a string literal that's used in a number of different places around my executable.
Let's say something like:
const char *formatString = "Something I don't want to make obvious: %d";
int format1(char *buf) { sprintf(buf, formatString, 1); }
int format2(char *buf) { sprintf(buf, formatString, 2); }
//...
Now, this string literal becomes very obvious inside the executable code, because it's embedded literally.
Is there any way to avoid this by forcing the compiler to, for example, generate assembly instructions (e.g. mov [ptr + 4], 0x65) instructions to create the strings, instead of embedding the strings literally?
I don't want to do an obfuscation of any sort -- I simply want to avoid making the string obvious inside the executable. (I also don't want to have to modify my code in every single place the string is used.)
Is this possible?
A: To avoid pasting encrypted strings into code by hand, you can create a macro which would mark strings that need obfuscation and a function which decrypts them:
#define OB(s) dec("START_MARK_GUID" s "\0" "END_MARK_GUID")
const char* dec(const char* s) { ... }
...
const char* s = OB("not easily readable"); // on all strings needed
const char* s = OB("either");
The function must do two things:
*
*If the parameter starts with START_MARK_GUID, simply return the original string (without the guids). This will allow you to use unobfuscated executable too, e.g. when debugging.
*If it starts with ENCRYPTED_MARK_GUID, deobfuscate first then return a new string. In C you will have to care about memory lifetime here; in C++ you could simply return std::string().
Finally, create an obfuscator program which looks for GUIDs in a compiled binary and encrypts data between them. It is only a few lines in Python or similar language. I also recommend to fix EXE's CRC back after, though my program worked even without that.
You can change guids with less unique identifiers to save some space. Also you can improve this to make decryption happen only one time (e.g. write string ID among with ENCRYPTED_MARK_GUID and keep decrypted strings in a dictionary by that ID).
A: Obfuscation is probably your best bet. Use a simple obfuscation (such as XOR), and unobfuscate it into another variable at the beginning of your program before running any code that needs the string.
A: Pretty soon with C++11 you'll be able to use user-defined literals.
constexpr const char*
operator"" _decrypto(const char*, size_t len)
{
// decrypt input string.
}
const char* formatString = "encrypted gibberish"_decrypto;
int format1(char* buf) { sprintf(buf, formatString, 1); }
int format2(char* buf) { sprintf(buf, formatString, 2); }
int
main()
{
}
gcc is working on this furiously and I think IBM has this already. Not sure about the status of Visual Studio. This compiled on a patched gcc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Data Encryption algorithm I want to know if our data is encrypted with one encryption algorithm(AES, DES, etc.) and then we transfer our data in open network, can anyone get real data or do some thing if the encryption algorithm is known even though the hacker doesn't know about the private keys, public key or PV?
A:
can anyone get real data or do some thing if the encryption algorithm is known
If the attacker knows the encryption algorithm, it's a start, because now all they need to do is to find out what was the key used to encrypt it. But established encryption algorithms like AES have no known weaknesses. Thus an attacker would be forced to bruteforce it to gain access to the data.
If you are using keys of an appropriate size (eg: AES 256 bits or more), this would be a very difficult task. DES also has no known weaknesses, but its small key size (56 bits) allows for a bruteforce attack to succeed in a reasonable timeframe, (eg: days). That's why DES is not widely used any more.
even though the hacker doesn't know about the private keys, public key or PV?
Note that public keys are only relevant in the context of asymmetrical encryption. In this case, the public key is usually publicly available (hence, the name "public key"). But asymmetric encryption is designed so that even if you know the public key, you can't decrypt it unless you have the private key.
In summary, encryption algorithms like AES have stood the test a time and proven to be secure enough. As David Schwartz points out in his answer, if you have a problem, (usually) your implementation is the thing to blame, not the encryption algorithm.
A: Almost by definition, if the encryption is implemented properly and part of a sensibly-designed system, no. That's the whole point of encryption.
Note that encryption is not magic. It must be used precisely correctly to provide useful security. There are a lot of ways to do it wrong.
If you're not using a widely respect product (like TrueCrypt, Firefox, or GPG) and using it precisely how it's intended to be used, there's a very good chance you aren't getting real security. For example, Dropbox used AES, but a security flaw in another part of their system allowed one user to decrypt another user's data. So it didn't help that it was encrypted.
A: Yes, keeping the algorithm secret helps security marginally. If an attacker knows that you used DES (which isn't terrifically hard to break) they may be more likely to try to break it.
I think the core of your question is about statistical attacks, which tries to see through the encryption to decipher the nature of the data. Any reasonably modern algorithm is mathematically designed to thwart any attempts to guess what the data is.
However David makes a very good point. Even perfect encryption (if it existed) would be vulnerable to the human factor. These algorithms are worthless if you don't dot your i's and cross your t's, and have absolute (and justified) faith in those who can decrypt the data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible for a class to conform to more than one protocol in objective-c? Is it possible for a class to conform to more than one protocol in objective-c? If so,
what is the syntax for declaring a class that conforms to more than one protocol?
A: @interface MyClass : NSObject <Protocol1, Protocol2, Protocol3>
@end
A: Yes; Just put a comma between each Protocol.
A: Yes it is possible for a class to conform to multiple protocols. The syntax is as follows:
@interface MyClass : NSObject <Protocol1, Protocol2, Protocol3>
//...Some code here...
@end
A protocol in Objective-C is essentially a list of methods which must be implemented in order for an object or class to be said to be conforming to that protocol. A common example of a class conforming to multiple protocols is a UITableViewController that acts as a UITableViewDataSource and a UITableViewDelegate.
For a UITableViewController example, it might look like this:
@interface MyTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
//...Some code here...
@end
You separate each protocol with a comma, and put it inside of those brackets. When you add those protocols to your interface declaration, you're essentially saying "yes, I'll implement the methods defined by those protocols". Now, go ahead and implement those methods, or the compiler will remind you that you haven't kept your word.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML and CSS is not working? I am really new when it comes to web programming, specially when it comes to HTML and CSS, I was reading the Head first book by O reily and there was this example that is not working when I run it to my web browser, I am using Google chrome and I was using a notepad++ for this code of mine, can anyone help me out here? since my CSS code doesn't seem to work
<html>
<head>
<title> Starbuzz Coffee</title>
<style type=”text/css”>
body {
background-color: #d2b48c;
margin-left: 20%;
margin-right: 20%;
border: 1px dotted gray;
padding: 10px 10px 10px 10px;
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>StarBuzz Coffee Beverages!</h1>
<h2>House Blend , $1.49</h2>
<p>A smooth, mild blend of coffee from mexico,Oblivia and Guatemala</p>
<h2>Mocha Coffee Latter , $2.96</h2>
<p>EsPresso, Steamed milk and Chocolate chip</p>
<h2>Capuccino , $1.07</h2>
<p>A mixture of Espresso, steamed milk and foam</p>
<h2>Chai Tea , $2.59</h2>
<p> A spicy drink with black tea, spices, milk and honey</p>
</body>
</html>
A: I pasted your code directly into jsfiddle and the CSS was not applied to the document. Try changing the curly quotes (style type=”text/css”) to regular quotes (style type="text/css") and try again.
Working example: http://jsfiddle.net/dPdHu/
A: instead of (shift+') to get "
do not press shift and then press '+' to get ''
Simple yet I had the exact same problem until Rob's post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Application validation was skipped" because "the bundle “ITunesSoftwareService” couldn’t be loaded" Trying to build an iOS app, I get the warning "Application validation was skipped," and the Application Loader rejects my binary because the code signing step has failed. I never had any problems building and submitting with Xcode 3. This is my first time attempting to build and submit with Xcode 4. I don't know what the "ITunesSoftwareService" framework is and I don't explicitly use it anywhere. I'm a bit baffled - any help would be appreciated. Here is the full build log:
Validate "/Users/lukebradford/Library/Developer/Xcode/DerivedData/Random_Acts_of_Haiku-fbxqwasqdxqcoofxwybyjbxiuwvp/Build/Products/Release-iphoneos/Random Acts of Haiku.app"
cd "/Users/lukebradford/Documents/My Apps/Random Acts of Haiku"
setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
setenv PRODUCT_TYPE com.apple.product-type.application
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/Validation "/Users/lukebradford/Library/Developer/Xcode/DerivedData/Random_Acts_of_Haiku-fbxqwasqdxqcoofxwybyjbxiuwvp/Build/Products/Release-iphoneos/Random Acts of Haiku.app"
2011-10-02 00:34:21.486 Validation[73657:607] Could not load framework at “file://localhost/Developer/Applications/Utilities/Application%20Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/” (err = Error Domain=NSCocoaErrorDomain Code=3587 UserInfo=0x200033ec0 "The bundle “ITunesSoftwareService” couldn’t be loaded because it is damaged or missing necessary resources." (dlopen_preflight(/Developer/Applications/Utilities/Application Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/ITunesSoftwareService): Library not loaded: @rpath/ITunesConnectFoundation.framework/Versions/A/ITunesConnectFoundation
Referenced from: /Developer/Applications/Utilities/Application Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/ITunesSoftwareService
Reason: image not found))
warning: Application validation was skipped.
A: Seems like the /Developer/Applications/Utilities/Application Loader.app App was corrupted when installing Xcode. My suggestion is to uninstall / reinstall Xcode. The Application Loader app is necessary to validate and submit an App to Apple for review.
You can also try installing the new iTunes Beta 7/8 if your using Xcode 4.2 dev preview, that might contain some required libraries that your missing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make an intelligent decision about which standard exception to throw? We know that the exception class has two derived classes: logic_error and runtime_error.
logic_error has four derived classes: domain_error, invalid_argument, length_error and out_of_range.
runtime_error has three derived classes: range_error, overflow_error and underflow_error.
While some of them are self-explanatory, like overflow_error and underflow_error, some are not that clear, especially range_error, both MSDN and cplusplus just say "to report a range error", which is close to saying nothing, how it is different out_of_range and domain_error???
Another question is when I throw an exception, which one should I choose? For example, In reverse_string(char* s), which exception to throw when s is NULL? In float calc_ellipse_area(float a, float b), which to throw when a or b is <=0? Which to throw when a == b (strictly speaking, circle is not an ellipse!)?
Finally, practically speaking, does it really matter if I throw an exception which is not correctly categorized?
A:
For example, In reverse_string(char* s), which exception to throw when s is NULL?
In float calc_ellipse_area(float a, float b), which to throw when a or b is <=0? Which to throw when a == b (strictly speaking, circle is not an ellipse!)?
For both of these, use std::invalid_argument.
Or you can define your own exception called null_argument deriving from std::logic_error (or from std::invalid_argument), and use it for NULL argument.
The point is that if none of the standard exception class applies to your situation, or you want more specific exception, then define one deriving from existing classes.
For example, if you want to throw exception when you encounter an invalid index, then either you can use std::out_of_range or define more specific class called index_out_of_range deriving from std::out_of_range.
does it really matter if I throw an exception which is not correctly categorized?
Yes, it does matter. For example, it increases readability of your code. If you throw std::logic_error when an invalid index is encountered, then well, it doesn't add much to the readability, but instead of that if you throw std::out_of_range , then it greatly increases the readability. And if you throw index_out_of_range, it increases even more, as it's more specific.
A: From the standard:
*
*The Standard C++ library provides classes to be used to report certain errors (17.6.5.12) in C++ programs. In the error model reflected in these classes, errors are divided into two broad categories: logic errors and runtime errors.
*The distinguishing characteristic of logic errors is that they are due to errors in the internal logic of the program. In theory, they are preventable.
*By contrast, runtime errors are due to events beyond the scope of the program. They cannot be easily predicted in advance.
However, all the exception types derived from runtime_error are misclassified -- all of them are easily preventable.
For actual runtime errors, the C++ standard library is rather inconsistent, it sometimes uses return values or internal state (e.g. iostream::bad(). And when it does use exceptions, they don't derive from runtime_error. For example, std::bad_alloc is a direct subclass of std::exception.
In conclusion, you shouldn't ever use std::runtime_error or any of its predefined subclasses.
A: The difference between out_of_range and range_error is found in the description of their parent classes:
logic_error: This class defines the type of objects thrown as exceptions to report
errors in the internal logical of the program. These are theoretically
preventable.
runtime_error: This class defines the type of objects thrown as exceptions to report
errors that can only be determined during runtime.
Domain error is for mathematical functions specifically. So your calc_ellipse_area could quite sensibly throw a domain error on negative value (and return 0 if one or both arguments are 0). I don't see any reason to complain if the ellipse happens to also be a circle, any more than a rectangle area function should fail on a square.
Passing null pointers to functions that shouldn't receive NULL I would handle by invalid argument exceptions.
C++ lets you throw whatever you like. What's really helpful to those who might use your code is that you name what you throw after the method signature, and that these names are reasonably descriptive. By default, a function could throw anything - to promise that a function won't throw, you have to use an empty throw() in the signature.
A: A logic error is the (theoretically) result of a programmer error.
A runtime error is something that could not easily have been prevented by the programmer.
When you write a function, it is useful to document its preconditions and/or assumptions. If those preconditions are broken, it is a logic error.
A runtime error is usually due to something external: a file operation failed, a printer is offline, a DLL could not be loaded.
If a path parameter is malformed, that is a logic error. If it is a valid path string, but does not exist, or you don't have permission to access it, that is a runtime error.
Sometimes it becomes arbitrary. Bad user input is probably a runtime error, but failure to validate user input is more of a logic error. It may not be obvious which is the case in a particular situation.
If something starts in 01 Feb 2011, a finish date of "01 Jan 2011" is an invalid argument, while "31 Feb 2011" is out of range. A finish date of "fish and chips" is a domain error. Length errors are often about buffer size, but that might also include too much or too little input data or something like that.
A range error is similar to an out of range error, except for the context (runtime, not logic). e.g. Number of printers available = 0. Overflow and underflow are more or less self-explanatory.
In the end, use them in a way that you and your colleagues find meaningful -- or possibly don't use them at all. Some people just use std::exception for everything.
It is only really important if you are going to handle different exceptions differently. If you are just going to display (or log) a message and carry on, it doesn't matter what exception(s) you use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: No syntax highlight for *.qss file in Qt Creator? It's wired that Qt Creator didn't have a syntax highlight for its own style file format , or did i missed some packages ?
VER: Qt Creator 2.1.0
A: Go to
Tools > Options > Environment > Mime types
Find text/css and add *.qss to patterns.
A: I could not find any evidence in Qt's documentation that .qss is an officially designated file extension. I'd say just change it to .css.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Why are XVisuals repeated in xdpyinfo Looking into my output of xdpyinfo, I see a lot of Visuals of the exact same characteristics repeated. Why are they repeated?
For example,
visual:
visual id: 0x6e
class: TrueColor
depth: 32 planes
available colormap entries: 256 per subfield
red, green, blue masks: 0xff0000, 0xff00, 0xff
significant bits in color specification: 8 bits
visual:
visual id: 0x6f
class: TrueColor
depth: 32 planes
available colormap entries: 256 per subfield
red, green, blue masks: 0xff0000, 0xff00, 0xff
significant bits in color specification: 8 bits
0x6e and 0x6f are exactly the same.
A related question: A visual already has a concept of depth, so why is it required to pass both a depth and a visual to XCreateWindow?
A: *
*The two visuals are not necessarily exactly the same. They may have different GLX properties. Run glxinfo -v to see them.
*The depth of the visual is the maximal depth. My screen for instance has many visuals, all of them are of depth 24 or 32. The X server supports more depths, in my case 24, 1, 4, 8, 15, 16, and 32. In a visual of a given depth you can create a window of a smaller depth. The preceding is wrong. The depth of the visual is the only depth it supports. One cannot create a window of any other depth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rake "already initialized constant WFKV_" warning Trying to run rake cucumber:ok and am getting this error:
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rack-1.3.4/lib/rack/backports/uri/common_192.rb:53: warning: already initialized constant WFKV_
Then:
Command failed with status (1): [/Users/dev/.rbenv/versions/1.9.2-p290/bin...]
I am pretty new to Rails and Google didn't turn anything up for this error.
EDIT: I've tried adding bundle exec and that makes no difference.
Here's what I got with --trace:
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:53:in `block in create_shell_runner'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:45:in `call'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:45:in `sh'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `sh'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/cucumber-1.1.0/lib/cucumber/rake/task.rb:104:in `run'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/cucumber-1.1.0/lib/cucumber/rake/task.rb:193:in `block in define_task'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in `call'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in `block in execute'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in `each'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:112:in `invoke_task'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `block (2 levels) in top_level'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `each'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `block in top_level'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:84:in `top_level'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:62:in `block in run'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:59:in `run'
/Users/dev/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/rake-0.9.2/bin/rake:32:in `<top (required)>'
/Users/dev/.rbenv/versions/1.9.2-p290/bin/rake:19:in `load'
/Users/dev/.rbenv/versions/1.9.2-p290/bin/rake:19:in `<main>'
Tasks: TOP => cucumber:ok
A: Rack 1.3.5 is out now, which has fixed this warning.
A: I started having the same problem this evening. It seems to be related to Rack 1.3.4. I fixed it by adding this to my Gemfile:
gem 'rack', '1.3.3'
Then running:
bundle update rack
Incidentally, I tried Bozhidar's suggestion before this, but to no avail.
A: you should uninstall rake-0.9.2
and install rack 1.6.13
gem uninstall rake
gem install rack 1.6.13
A: So, I included:
require 'uri/common'; ::URI.send :remove_const, :WFKV_
however the comment which says "it will work in the Gemfile" in fact should read "Must be in the Gemfile."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Best way to create the behavior of an extendable Enum in java I want to create something that resembles an extendable Enum (understanding extending Enums isn't possible in Java 6).
Here is what im trying to do:
I have many "Model" classes and each of these classes have a set of Fields that are to be associated with it. These Fields are used to index into Maps that contain representations of the data.
I need to be able to access the Fields from an Class OR instance obj as follows:
MyModel.Fields.SOME_FIELD #=> has string value of "diff-from-field-name"
or
myModel.Fields.SOME_FIELD #=> has string value of "diff-from-field-name"
I also need to be able to get a list of ALL the fields for Model
MyModel.Fields.getKeys() #=> List<String> of all the string values ("diff-from-field name")
When defining the "Fields" class for each Model, I would like to be able to keep the definition in the same file as the Model.
public class MyModel {
public static final Fields extends BaseFields {
public static final String SOME_FIELD = "diff-from-field-name";
public static final String FOO = "bar";
}
public Fields Fields = new Fields();
// Implement MyModel logic
}
I also want to have OtherModel extends MyModel and beable to inherit the Fields from MyModel.Fields and then add its own Fields on top if it ..
public class OtherModel extends MyModel {
public static final class Fields extends MyModel.Fields {
public static final String CAT = "feline";
....
Which woulds allow
OtherModel.Fields.CAT #=> feline
OtherModel.Fields.SOME_FIELD #=> diff-from-field-name
OtherModel.Fields.FOO #=> bar
OtherModel.Fields.getKeys() #=> 3 ["feline", "diff-from-field-name", "bar"]
I am trying to make the definition of the "Fields" in the models as clean and simple as possible as a variety of developers will be building out these "Model" objects.
Thanks
A:
I need to be able to access the Fields from an Class OR instance obj as follows:
MyModel.Fields.SOME_FIELD #=> has string value of "diff-from-field-name"
That is not possible in Java unless you use a real enum or SOME_FIELD is a real field. In either case, the "enum" is not extensible.
The best you can do in Java 6 is to model the enumeration as mapping from String names to int values. That is extensible, but the mapping from names to values incurs a runtime cost ... and the possibility that your code will use a name that is not a member of the enumeration.
The reason that enum types in Java are not extensible is that the extended enum would break the implicit invariants of the original enum and (as a result) could not be substitutable.
A: I've just tried out some code trying to do what you've just described and it was really cumbersome.
If you have a Fields static inner class somewhere in a model class like this:
public class Model {
public static class Fields {
public static final String CAT = "cat";
protected static final List<String> KEYS = new ArrayList<String>();
static {
KEYS.add(CAT);
}
protected Fields() {}
public static List<String> getKeys() {
return Collections.unmodifiableList(KEYS);
}
}
}
and you extend this class like this:
public class ExtendedModel extends Model {
public static class ExtendedFields extend Model.Fields {
public static final String DOG = "dog";
static {
KEYS.add(DOG);
}
protected ExtendedFields() {}
}
}
then its just wrong. If you call Model.Fields.getKeys() you'd get what you expect: [cat], but if you call ExtendedModel.ExtendedFields.getKeys() you'd get the same: [cat], no dog. The reason: getKeys() is a static member of Model.Fields calling ExtendedModel.ExtendedFields.getKeys() is wrong because you really call Model.Fields.getKeys() there.
So you either operate with instance methods or create a static getKeys() method in all of your Fields subclasses, which is so wrong I can't even describe.
Maybe you can create a Field interface which your clients can implement and plug into your model(s).
public interface Field {
String value();
}
public class Model {
public static Field CAT = new Field() {
@Override public String value() {
return "cat";
}
};
protected final List<Field> fields = new ArrayList();
public Model() {
fields.add(CAT);
}
public List<Field> fields() {
return Collections.unmodifiableList(fields);
}
}
public class ExtendedModel extends Model {
public static Field DOG= new Field() {
@Override public String value() {
return "dog";
}
};
public ExtendedModel() {
fields.add(DOG);
}
}
A: I wonder whether you really need a generated enumeration of fields. If you are going to generate a enum of a list the fields based on a model, why not generate a class which lists all the fields and their types? i.e. its not much harder to generate classes than staticly or dynamically generated enums and it much more efficient, flexible, and compiler friendly.
So you could generate from a model something like
class BaseClass { // with BaseField
String field;
int number;
}
class ExtendedClass extends BaseClass { // with OtherFields
String otherField;
long counter;
}
Is there a real benefit to inventing your own type system?
A: Curses - For some reason my very lengthy response with the solution i came up with did not post.
I will just give a cursory overview and if anyone wants more detail I can re-post when I have more time/patience.
I made a java class (called ActiveField) from which all the inner Fields inherit.
Each of the inner field classes have a series of fields defined:
public static class Fields extends ActiveField {
public static final String KEY = "key_value";
}
In the ActiveRecord class i have a non-static method getKeys() which uses reflection to look at the all the fields on this, iterates through, gets their values and returns them as a List.
It seems to be working quite well - let me know if you are interested in more complete code samples.
A: I was able to come up with a solution using reflection that seems to work -- I haven't gone through the full gamut of testing, this was more me just fooling around seeing what possible options I have.
ActiveField : Java Class which all other "Fields" Classes (which will be inner classes in my Model classes) will extend. This has a non-static method "getKeys()" which looks at "this's" class, and pulled a list of all the Fields from it. It then checks a few things like Modifiers, Field Type and Casing, to ensure that it only looks at Fields that match my convention: all "field keys" must be "public static final" of type String, and the field name must be all UPPERCASE.
public class ActiveField {
private final String key;
protected ActiveField() {
this.key = null;
}
public ActiveField(String key) {
System.out.println(key);
if (key == null) {
this.key = "key:unknown";
} else {
this.key = key;
}
}
public String toString() {
return this.key;
}
@SuppressWarnings("unchecked")
public List<String> getKeys() {
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> names = new ArrayList<String>();
Class cls;
try {
cls = Class.forName(this.getClass().getName());
} catch (ClassNotFoundException e) {
return keys;
}
Field fieldList[] = cls.getFields();
for (Field fld : fieldList) {
int mod = fld.getModifiers();
// Only look at public static final fields
if(!Modifier.isPublic(mod) || !Modifier.isStatic(mod) || !Modifier.isFinal(mod)) {
continue;
}
// Only look at String fields
if(!String.class.equals(fld.getType())) {
continue;
}
// Only look at upper case fields
if(!fld.getName().toUpperCase().equals(fld.getName())) {
continue;
}
// Get the value of the field
String value = null;
try {
value = StringUtils.stripToNull((String) fld.get(this));
} catch (IllegalArgumentException e) {
continue;
} catch (IllegalAccessException e) {
continue;
}
// Do not add duplicate or null keys, or previously added named fields
if(value == null || names.contains(fld.getName()) || keys.contains(value)) {
continue;
}
// Success! Add key to key list
keys.add(value);
// Add field named to process field names list
names.add(fld.getName());
}
return keys;
}
public int size() {
return getKeys().size();
}
}
Then in my "Model" classes (which are fancy wrappers around a Map, which can be indexed using the Fields fields)
public class ActiveResource {
/**
* Base fields for modeling ActiveResource objs - All classes that inherit from
* ActiveResource should have these fields/values (unless overridden)
*/
public static class Fields extends ActiveField {
public static final String CREATED_AT = "node:created";
public static final String LAST_MODIFIED_AT = "node:lastModified";
}
public static final Fields Fields = new Fields();
... other model specific stuff ...
}
I can then make a class Foo which extends my ActiveResource class
public class Foo extends ActiveResource {
public static class Fields extends ActiveResource.Fields {
public static final String FILE_REFERENCE = "fileReference";
public static final String TYPE = "type";
}
public static final Fields Fields = new Fields();
... other Foo specific stuff ...
Now, I can do the following:
ActiveResource ar = new ActiveResource().
Foo foo = new Foo();
ar.Fields.size() #=> 2
foo.Fields.size() #=> 4
ar.Fields.getKeys() #=> ["fileReference", "type", "node:created", "node:lastModified"]
foo.Fields.getKeys() #=> ["node:created", "node:lastModified"]
ar.Fields.CREATED_AT #=> "node:created"
foo.Fields.CREATED_AT #=> "node:created"
foo.Fields.TYPE #=> "type"
etc.
I can also access the Fields as a static field off my Model objects
Foo.Fields.size(); Foo.Fields.getKeys(); Foo.Fields.CREATED_AT; Foo.Fields.FILE_REFERENCE;
So far this looks like a pretty nice solution, that will require minimal instruction for building out new Models.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get body of HTTP response in Clojure I'm trying to get the body of a HTTP response with Clojure, with a handler. However the http-agent function hangs without returning.
This will print the response, and then hang without returning:
(use '[clojure.contrib.http.agent])
(def text (result (http-agent "http://jsonip.com"
:method "GET")))
(println text)
This will print "Handling...", then hang indefinitely:
(use '[clojure.contrib.http.agent])
(defn do-stuff
"handler"
[response]
(do
(println "Handling...")
(slurp (string response))))
(def text (result (http-agent "http://jsonip.com"
:method "GET"
:handler do-stuff)))
(println (str "text! " text))
How can I get the http-agent method to stop hanging? In the second case I've listed above, how can I get the handler to return the response body?
Thanks for your help,
Kevin
A: In the second piece of code you have not printed out what is slurped. Should be like this -
(println (slurp (string response)))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the difference between these two JavaScript patterns I am trying to organize my JavaScript better. My goal is to have modular architecture that I can break into separate files (sitename.js, sitename.utils.js etc).
I'd like to know what are advantages and disadvantages of these two patterns and which one is more suitable for breaking into modules that live in separate files.
PATTERN #1 (module pattern)
var MODULE = (function () {
//private methods
return {
common: {
init: function() {
console.log("common.init");
}
},
users: {
init: function () {
console.log("users.init");
},
show: function () {
console.log("users.show");
}
}
}
})();
PATTERN #2 (singleton)
var MODULE = {
common: {
init: function() {
console.log("common.init");
}
},
users: {
init: function() {
console.log("users.init");
},
show: function() {
console.log("users.show");
}
}
};
A: Personally, I recommend an extension of #1, as follows:
var Module = (function(Module) {
// A comment
Module.variable1 = 3;
/**
* init()
*/
Module.init = function() {
console.log("init");
};
// ...
return Module;
})(Module || {});
I like this pattern for a couple reasons. One, documentation (specifically javadoc-style) look more natural when all your functions are declarations rather than a big hash. Two, if your submodules grow in size, it lets you break them into multiple files without any refactoring.
For example, if Module.Users were to go into its own file:
var Module = Module || {};
Module.Users = (function(Users) {
/**
* init()
*/
Users.init = function() {
console.log("Module.Users.init");
};
// ...
return Users;
})(Module.Users || {});
Now "module.js" and "module.users.js" can be separate files, and they'll work regardless of the order they are loaded. Also note the local scoping of the module name - this is very handy if your module name is long, because you can take "MyApp.Users.EditScreen" and refer to it with a variable like "ES" within the scope of your module definition.
A: The first pattern allows for private variables, methods, etc via closures. For example:
var MODULE = (function () {
var privateStuff = 'This is private';
var doStuff = function(obj) {
console.log('Doing stuff...');
console.log(privateStuff);
};
return {
common: {
init: function() {
console.log("common.init");
doStuff(this);
}
},
users: {
init: function () {
console.log("users.init");
},
show: function () {
console.log("users.show");
}
}
}
})();
privateStuff and doStuff are not properties of the object, and are not available to anything but what's defined inside the function that returns MODULE. So showing an example for how to do this with #2 is not possible.
JS doesn't have the concept of private members, so you can't define them via a regular object literal. So if you need private stuff, go for the first option. If you don't, though, #2 is simpler.
A: Your code as written is pretty much the same. However, the first form is much easier to work with as you evolve your code, because it allows you to add private variables and functions. The second form doesn't support this, and you nearly always end up wanting the first form eventually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Summing XML data that is in two arrays I am very new to XSL and XML and have, I hope, an easy question. I have an XML file that has two arrays of numbers in them that I need to sum. Here is part of the XML file
<?xml version="1.0" encoding="UTF-8"?>
<out_xml>
<Root>
<ItemCollection>
<Item name="BaseLineOffSet" type="2">
<Histogram>
<DispOrder>This is Order</DispOrder>
<IntensityArray>
<Intensity>105.84667205810547</Intensity>
<Intensity>105.83854675292969</Intensity>
<Intensity>105.57729339599609</Intensity>
<Intensity>105.66104888916016</Intensity>
<Intensity>105.56392669677734</Intensity>
<Intensity>105.33917236328125</Intensity>
<Intensity>105.33854675292969</Intensity>
<Intensity>105.31544494628906</Intensity>
<Intensity>105.40036010742187</Intensity>
<Intensity>105.21470642089844</Intensity>
<Intensity>105.14356994628906</Intensity>
<Intensity>104.92792510986328</Intensity>
<Intensity>104.93791961669922</Intensity>
<Intensity>104.93979644775391</Intensity>
<Intensity>104.96470642089844</Intensity>
<Intensity>105.01107025146484</Intensity>
<Intensity>104.76479339599609</Intensity>
<Intensity>104.9085693359375</Intensity>
<Intensity>104.70166778564453</Intensity>
<Intensity>104.75499725341797</Intensity>
<Intensity>104.77352905273437</Intensity>
<Intensity>104.77714538574219</Intensity>
<Intensity>104.59485626220703</Intensity>
<Intensity>104.73235321044922</Intensity>
<Intensity>104.35479736328125</Intensity>
<Intensity>104.56911468505859</Intensity>
<Intensity>104.38999938964844</Intensity>
<Intensity>104.30992889404297</Intensity>
<Intensity>104.37964630126953</Intensity>
</IntensityArray>
</Histogram>
</Item>
<Item name="DispIntervalsMaxValues" type="2">
<Histogram>
<DispOrder>This is Order</DispOrder>
<IntensityArray>
<Intensity>1.0229243040084839</Intensity>
<Intensity>48.868541717529297</Intensity>
<Intensity>47.504795074462891</Intensity>
<Intensity>162.17105102539062</Intensity>
<Intensity>91.323570251464844</Intensity>
<Intensity>44.405426025390625</Intensity>
<Intensity>51.243541717529297</Intensity>
<Intensity>131.44705200195312</Intensity>
<Intensity>2.8496425151824951</Intensity>
<Intensity>21.435295104980469</Intensity>
<Intensity>47.006423950195312</Intensity>
<Intensity>0.72917240858078003</Intensity>
<Intensity>46.669178009033203</Intensity>
<Intensity>83.804801940917969</Intensity>
<Intensity>44.197799682617187</Intensity>
<Intensity>32.138923645019531</Intensity>
<Intensity>30.30479621887207</Intensity>
<Intensity>58.928920745849609</Intensity>
<Intensity>29.930421829223633</Intensity>
<Intensity>38.282505035400391</Intensity>
<Intensity>30.801467895507813</Intensity>
<Intensity>43.710361480712891</Intensity>
<Intensity>38.167644500732422</Intensity>
<Intensity>27.842643737792969</Intensity>
<Intensity>34.102294921875</Intensity>
<Intensity>61.118381500244141</Intensity>
<Intensity>10.910002708435059</Intensity>
<Intensity>3.6150767803192139</Intensity>
<Intensity>3.1703603267669678</Intensity>
</IntensityArray>
</Histogram>
</Item>
</ItemCollection>
</Root>
</out_xml>
What I really want is the sum of the the elements from the two Intensity arrays to be added up. So it would be something like this:
FirstArray[0]+SecondArray[0]=sum[0] which is really
105.84667205810547 + 1.0229243040084839=106.8696
and
FirstArray[1]+SecondArray[1] =sum[1]
105.83854675292969+ 48.868541717529297=154.7071 and so on ...
There are a few other Items in between these two that I need to ignore for now.
Thanks !
A: Updated:
Look at sum function, e.g.:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="k" match="Intensity" use="count(preceding-sibling::Intensity)"/>
<xsl:template match="/">
<root>
<xsl:apply-templates select="//Intensity[generate-id(.) =
generate-id(key('k', count(preceding-sibling::Intensity)))]"/>
</root>
</xsl:template>
<xsl:template match="Intensity">
<sum>
<xsl:value-of select="sum(key('k', count(preceding-sibling::Intensity)))"/>
</sum>
</xsl:template>
</xsl:stylesheet>
This template sums Intensity elements for both IntensityArray.
Output:
<root>
<sum>106.86959636211395</sum>
<sum>154.70708847045898</sum>
<sum>153.08208847045898</sum>
<sum>267.8320999145508</sum>
<sum>196.8874969482422</sum>
<sum>149.74459838867187</sum>
<sum>156.58208847045898</sum>
<sum>236.7624969482422</sum>
<sum>108.25000262260437</sum>
<sum>126.6500015258789</sum>
<sum>152.14999389648437</sum>
<sum>105.65709751844406</sum>
<sum>151.60709762573242</sum>
<sum>188.74459838867187</sum>
<sum>149.16250610351562</sum>
<sum>137.14999389648437</sum>
<sum>135.06958961486816</sum>
<sum>163.8374900817871</sum>
<sum>134.63208961486816</sum>
<sum>143.03750228881836</sum>
<sum>135.5749969482422</sum>
<sum>148.48750686645508</sum>
<sum>142.76250076293945</sum>
<sum>132.5749969482422</sum>
<sum>138.45709228515625</sum>
<sum>165.68749618530273</sum>
<sum>115.3000020980835</sum>
<sum>107.92500567436218</sum>
<sum>107.5500066280365</sum>
</root>
A: Does the following do what you need it to?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<root>
<xsl:apply-templates select="//ItemCollection"/>
</root>
</xsl:template>
<xsl:template match="ItemCollection">
<xsl:variable name="itemCollection" select="." />
<xsl:variable name="itemsCount" select="count((.//IntensityArray)[1]//Intensity)" />
<xsl:for-each select="1 to $itemsCount">
<xsl:variable name="itemIndex" select="." />
<sum position="{$itemIndex}">
<xsl:value-of select="sum($itemCollection//IntensityArray//Intensity[$itemIndex])" />
</sum>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
I got the following output when I ran it on your sample data:
<root>
<sum position="1">106.86959636211395</sum>
<sum position="2">154.70708847045898</sum>
<sum position="3">153.08208847045898</sum>
<sum position="4">267.8320999145508</sum>
<sum position="5">196.8874969482422</sum>
<sum position="6">149.74459838867187</sum>
<sum position="7">156.58208847045898</sum>
<sum position="8">236.7624969482422</sum>
<sum position="9">108.25000262260437</sum>
<sum position="10">126.6500015258789</sum>
<sum position="11">152.14999389648437</sum>
<sum position="12">105.65709751844406</sum>
<sum position="13">151.60709762573242</sum>
<sum position="14">188.74459838867187</sum>
<sum position="15">149.16250610351562</sum>
<sum position="16">137.14999389648437</sum>
<sum position="17">135.06958961486816</sum>
<sum position="18">163.8374900817871</sum>
<sum position="19">134.63208961486816</sum>
<sum position="20">143.03750228881836</sum>
<sum position="21">135.5749969482422</sum>
<sum position="22">148.48750686645508</sum>
<sum position="23">142.76250076293945</sum>
<sum position="24">132.5749969482422</sum>
<sum position="25">138.45709228515625</sum>
<sum position="26">165.68749618530273</sum>
<sum position="27">115.3000020980835</sum>
<sum position="28">107.92500567436218</sum>
<sum position="29">107.5500066280365</sum>
</root>
A: This transformation produces the wanted result even in cays the two node-sets have different number of nodes and/or some of the nodes in the 2nd node-set don't have value that is castable to a number:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vArr1" select=
"/*/*/*/Item[1]/*/IntensityArray/*"/>
<xsl:variable name="vArr2" select=
"/*/*/*/Item[2]/*/IntensityArray/*"/>
<xsl:variable name="vShorterArr" select=
"$vArr1[not(count($vArr1) > count($vArr2))]
|
$vArr2[not(count($vArr2) >= count($vArr1))]
"/>
<xsl:variable name="vLongerArr" select=
"$vArr2[not(count($vArr1) > count($vArr2))]
|
$vArr1[not(count($vArr2) >= count($vArr1))]
"/>
<xsl:template match="/">
<summedIntensities>
<xsl:apply-templates select="$vLongerArr"/>
</summedIntensities>
</xsl:template>
<xsl:template match="Intensity">
<xsl:variable name="vPos" select="position()"/>
<Intensity>
<xsl:variable name="vVal2" select="$vShorterArr[position()=$vPos]"/>
<xsl:value-of select=
".
+
concat('0',
substring($vVal2,
1 div (number($vVal2) = number($vVal2))
)
)
"/>
</Intensity>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied to the following XML document (the same as the provided one, but added to the first node-set one more Intensity element (the last one), to make the two node-sets different in size):
<out_xml>
<Root>
<ItemCollection>
<Item name="BaseLineOffSet" type="2">
<Histogram>
<DispOrder>This is Order</DispOrder>
<IntensityArray>
<Intensity>105.84667205810547</Intensity>
<Intensity>105.83854675292969</Intensity>
<Intensity>105.57729339599609</Intensity>
<Intensity>105.66104888916016</Intensity>
<Intensity>105.56392669677734</Intensity>
<Intensity>105.33917236328125</Intensity>
<Intensity>105.33854675292969</Intensity>
<Intensity>105.31544494628906</Intensity>
<Intensity>105.40036010742187</Intensity>
<Intensity>105.21470642089844</Intensity>
<Intensity>105.14356994628906</Intensity>
<Intensity>104.92792510986328</Intensity>
<Intensity>104.93791961669922</Intensity>
<Intensity>104.93979644775391</Intensity>
<Intensity>104.96470642089844</Intensity>
<Intensity>105.01107025146484</Intensity>
<Intensity>104.76479339599609</Intensity>
<Intensity>104.9085693359375</Intensity>
<Intensity>104.70166778564453</Intensity>
<Intensity>104.75499725341797</Intensity>
<Intensity>104.77352905273437</Intensity>
<Intensity>104.77714538574219</Intensity>
<Intensity>104.59485626220703</Intensity>
<Intensity>104.73235321044922</Intensity>
<Intensity>104.35479736328125</Intensity>
<Intensity>104.56911468505859</Intensity>
<Intensity>104.38999938964844</Intensity>
<Intensity>104.30992889404297</Intensity>
<Intensity>104.37964630126953</Intensity>
<Intensity>105.37964630126953</Intensity>
</IntensityArray>
</Histogram>
</Item>
<Item name="DispIntervalsMaxValues" type="2">
<Histogram>
<DispOrder>This is Order</DispOrder>
<IntensityArray>
<Intensity>1.0229243040084839</Intensity>
<Intensity>48.868541717529297</Intensity>
<Intensity>47.504795074462891</Intensity>
<Intensity>162.17105102539062</Intensity>
<Intensity>91.323570251464844</Intensity>
<Intensity>44.405426025390625</Intensity>
<Intensity>51.243541717529297</Intensity>
<Intensity>131.44705200195312</Intensity>
<Intensity>2.8496425151824951</Intensity>
<Intensity>21.435295104980469</Intensity>
<Intensity>47.006423950195312</Intensity>
<Intensity>0.72917240858078003</Intensity>
<Intensity>46.669178009033203</Intensity>
<Intensity>83.804801940917969</Intensity>
<Intensity>44.197799682617187</Intensity>
<Intensity>32.138923645019531</Intensity>
<Intensity>30.30479621887207</Intensity>
<Intensity>58.928920745849609</Intensity>
<Intensity>29.930421829223633</Intensity>
<Intensity>38.282505035400391</Intensity>
<Intensity>30.801467895507813</Intensity>
<Intensity>43.710361480712891</Intensity>
<Intensity>38.167644500732422</Intensity>
<Intensity>27.842643737792969</Intensity>
<Intensity>34.102294921875</Intensity>
<Intensity>61.118381500244141</Intensity>
<Intensity>10.910002708435059</Intensity>
<Intensity>3.6150767803192139</Intensity>
<Intensity>3.1703603267669678</Intensity>
</IntensityArray>
</Histogram>
</Item>
</ItemCollection>
</Root>
</out_xml>
the wanted, correct result is produced:
<summedIntensisites>
<Intensity>106.86959636211395</Intensity>
<Intensity>154.70708847045898</Intensity>
<Intensity>153.08208847045898</Intensity>
<Intensity>267.8320999145508</Intensity>
<Intensity>196.8874969482422</Intensity>
<Intensity>149.74459838867188</Intensity>
<Intensity>156.58208847045898</Intensity>
<Intensity>236.7624969482422</Intensity>
<Intensity>108.25000262260437</Intensity>
<Intensity>126.6500015258789</Intensity>
<Intensity>152.14999389648438</Intensity>
<Intensity>105.65709751844406</Intensity>
<Intensity>151.60709762573242</Intensity>
<Intensity>188.74459838867188</Intensity>
<Intensity>149.16250610351562</Intensity>
<Intensity>137.14999389648438</Intensity>
<Intensity>135.06958961486816</Intensity>
<Intensity>163.8374900817871</Intensity>
<Intensity>134.63208961486816</Intensity>
<Intensity>143.03750228881836</Intensity>
<Intensity>135.5749969482422</Intensity>
<Intensity>148.48750686645508</Intensity>
<Intensity>142.76250076293945</Intensity>
<Intensity>132.5749969482422</Intensity>
<Intensity>138.45709228515625</Intensity>
<Intensity>165.68749618530273</Intensity>
<Intensity>115.3000020980835</Intensity>
<Intensity>107.92500567436218</Intensity>
<Intensity>107.5500066280365</Intensity>
<Intensity>105.37964630126953</Intensity>
</summedIntensisites>
Explanation:
*
*Two variables are defined, each containing the nodes that comprize an "array".
*Another two variables are defined: $vShorterArr, containing the shorter node-set and $vLongerArr containing the longer node-set.
*Templates are applied to the longer node-set.
*Each node in the longer node-set is summed with the corresponding (if such exists) node in the shorter node-set, or with 0, otherwise.
II. XSLT 2.0 solution:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vArr1" select=
"/*/*/*/Item[1]/*/IntensityArray/*/number()"/>
<xsl:variable name="vArr2" select=
"/*/*/*/Item[2]/*/IntensityArray/*/number()"/>
<xsl:variable name="vShorterArr" select=
"if(count($vArr1) lt count($vArr2))
then $vArr1
else $vArr2
"/>
<xsl:variable name="vLongerArr" select=
"if(count($vArr1) ge count($vArr2))
then $vArr1
else $vArr2
"/>
<xsl:template match="/">
<summedIntensities>
<xsl:for-each select="$vLongerArr">
<xsl:variable name="vPos" select="position()"/>
<Intensity>
<xsl:variable name="vVal2" select=
"$vShorterArr[$vPos]"/>
<xsl:sequence select=
".
+
(if($vVal2 castable as xs:double)
then $vVal2
else 0
)
"/>
</Intensity>
</xsl:for-each>
</summedIntensities>
</xsl:template>
</xsl:stylesheet>
III. Using FXSL:
It is much easier to solve this problem using the f:zip-with() function/template of FXSL.
Below is a solution using FXSL 2:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
exclude-result-prefixes="f"
>
<xsl:import href="../f/func-zipWithDVC.xsl"/>
<xsl:import href="../f/func-Operators.xsl"/>
<!-- To be applied on numList.xml -->
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<summedIntensities>
<xsl:for-each select=
"f:zipWith(f:add(),
/*/*/*/Item[1]/*/IntensityArray/*/number(),
/*/*/*/Item[2]/*/IntensityArray/*/number()
)"
>
<Intensity>
<xsl:sequence select="."/>
</Intensity>
</xsl:for-each>
</summedIntensities>
</xsl:template>
</xsl:stylesheet>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to use RCM theming Library for C# Winform Application I have Downloaded the RCM Library from http://www.codeproject.com/KB/cs/RCM.aspx but i don't know how to add the controls that it provides to c# toolbox or how to use the custom form it provides.Guys Plz Help me Out.
A: One of the solutions can be derive every control you need with your own class inside your project . After rebuild you SHOULD see them in toolbox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to solve "Device 0 (vif) could not be connected. Hotplug scripts not working."? When starting a virtual machine, xm shows:
Device 0 (vif) could not be connected. Hotplug scripts not working.
Why does xm show this? How to solve it?
A: From the Xen wiki:
Error: Device 0 (vif) could not be connected. Hotplug scripts not working.
This problem is often caused by not having "xen-netback" driver loaded in dom0 kernel.
The hotplug scripts are located in /etc/xen/scripts by default, and are labeled with the prefix vif-*. Those scripts log to /var/log/xen/xen-hotplug.log, and more detailed information can be found there.
http://wiki.xen.org/wiki/Xen_Common_Problems
A: As weird as it sound, I encountered this error in a situation where the sum of vm memory I assigned left the dom0 with too little memory to complete the addition of a virtual interface. Sizing down the virtual machines was the solution.
A: I agree with PypeBros. Once I put a new entry in /etc/fstab to mount /tmp as tempfs and allocate 10G memory to it. Then the Xen guest won't start and gives me this error:
Error: Device 0 (vif) could not be connected. Hotplug scripts not working.
It worked fine when I removed /tmp as tempfs. So I think this error could be due to memory problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: In VBA, how to insert text before and after style? I have been trying to work out how to insert text before and after a given style in Word using VBA.
At present I run through the document from top to bottom, find the style, and make the insertions. It is time-consuing and inelegant (to say the least).
It should be possible to use a Range object and
Selection.InsertBefore ()
and
Selection.InsertAfter ()
but I can't get it to work.
Does anyone know how to do this?
This a second edit to give a better idea of the sort of thing I am looking for, but would need it modified to find a particular style:
Sub InsertBeforeMethod()
Dim MyText As String
Dim MyRange As Object
Set MyRange = ActiveDocument.Range
MyText = "<Replace this with your text>"
' Selection Example:
Selection.InsertBefore (MyText)
' Range Example: Inserts text at the beginning
' of the active document.
MyRange.InsertBefore (MyText)
End Sub
Another way it might be possible to fo this, is through using wildcards and style, but when I use (*) it only finds one character with the style, not the whole string.
Maybe there is some way to make it find the whole string? Then it would be possible to do a "replace all" with "mytext1"\1"mytext2"
A: Word has a feature to find and replace text with certain styles, so you don't even need a macro. But if you wish to automate it with VBA, the following sample code inserts foo in front of any Heading 2-styled code and appends bar afterwards:
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = ""
.Replacement.Text = "foo^&bar"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make all src strings global in PHP? I am writing a web browser in PHP, for devices (such as the Kindle) which do not support multi-tab browsing. Currently I am reading the page source with file_get_contents(), and then echoing it into the page. My problem is that many pages use local references (such as < img src='image.png>'), so they all point to pages that don't exist. What I want to do is locate all src and href tags and prepend the full web address to any that do not start with "http://" or "https://". How would I do this?
A: add <base href="http://example.com/" />
at the head of the page
this will help you insert it to the <head></head> section
A: Like elibyy suggested, I too would recommend using the base tag. Here's a way to do it with PHP's native DOMDocument:
// example url
$url = 'http://example.com';
$doc = new DOMDocument();
$doc->loadHTMLFile( $url );
// first let's find out if there a base tag already
$baseElements = $doc->getElementsByTagName( 'base' );
// if so, skip this block
if( $baseElements->length < 1 )
{
// no base tag found? let's create one
$baseElement = $doc->createElement( 'base' );
$baseElement->setAttribute( 'href', $url );
$headElement = $doc->getElementsByTagName( 'head' )->item( 0 );
$headElement->appendChild( $baseElement );
}
echo $doc->saveHTML();
Having said this however; are you sure you are aware of how ambitious your goal is?
For instance, I don't think this is exactly what you really need at all, as your application is basically acting as a proxy. Therefor you will probably want to route, at least, all user-clickable links through your application, and not route them directly to the original links at all, because I presume you want to keep the user in your tabbed application, and not break out of it.
Something like:
http://yourapplication.com/resource.php?resource=http://example.com/some/path/
Now, this could of course be achieved by basically doing what you requested, and in stead of prepending it with either, http:// or https:// prepend with something such that it results in above example url.
However, how are you gonna discern what resources to do this with, and what resources not? If you take this approach for all resources in the page, your application will quickly become a full fletched proxy, thereby becoming very resource intensive.
Hopefully I've given you a brief starter for some things to take into consideration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Inapp Purchase is succeeded but content is not unlock in iPhone app.. Why? In My iphone app i have used In App purchase. All the things are working and the contents are in Resource folder. After successful transaction i have used a Sql Query to insert data in Sqlite database. I have Uploaded this app in App Store and find that after successful transaction the payment is taken from users but the content is not inserted in database and not Showed in app. Please help me. i am stressed on this Point. Due to this i have removed my app form App Store.
In this code after successful finding list of In App Purchases i am using method
For better Understanding i am putting my Some code here:
- (void)insertNewObject {
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
// NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
-(void)updateObject {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
abort();
}
}
#pragma mark -
#pragma mark Store request
- (void) requestProductData {
request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:[arrayProductID objectAtIndex:b-2]]];//@"Scaringmirror11"
request.delegate = self;
[request start];
}
- (void) startPurchase {
//int newB=b-2;
SKPayment *payment = [SKPayment paymentWithProductIdentifier:[arrayProductID objectAtIndex:b-2]];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
#pragma mark Store delegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *myProduct = response.products;
if (myProduct == nil || [myProduct count] == 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"Missing product from App store.\n"
delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
SKProduct *product;
BOOL existProduct = NO;
for (int i=0; i<[myProduct count]; i++) {
product = (SKProduct*)[myProduct objectAtIndex:0];
if ([product.productIdentifier isEqualToString:[arrayProductID objectAtIndex:b-2]]) {
existProduct = YES;
//[[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt" ];
//[[NSUserDefaults standardUserDefaults] synchronize];
break;
}
}
if (existProduct == NO) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"Missing product from App store.No match Identifier found.\n"
delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
[request autorelease];
[self startPurchase];
}
#pragma mark Store delegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *myProduct = response.products;
if (myProduct == nil || [myProduct count] == 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"Missing product from App store.\n"
delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
SKProduct *product;
BOOL existProduct = NO;
for (int i=0; i<[myProduct count]; i++) {
product = (SKProduct*)[myProduct objectAtIndex:0];
if ([product.productIdentifier isEqualToString:[arrayProductID objectAtIndex:b-2]]) {
existProduct = YES;
//[[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt" ];
//[[NSUserDefaults standardUserDefaults] synchronize];
break;
}
}
if (existProduct == NO) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"Missing product from App store.No match Identifier found.\n"
delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
[request autorelease];
[self startPurchase];
}
#pragma mark observer delegate
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
NSLog(@"Success");
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
NSLog(@"Failed");
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:transaction];
default:
break;
}
}
}
- (void) completeTransaction: (SKPaymentTransaction *)transaction {
//[[NSUserDefaults standardUserDefaults] setBool:YES forKey:REGISTRATION_KEY];
registered = YES;
//NSData *receiptData = [transaction transactionReceipt];
//NSString *str =[NSString string
//[[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt" ];
//[self registeredEnable];
// Remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
[sqlite insertIntoScaryImage:[arrayGetMoreScaryImage objectAtIndex:b] add:[arrayGetMoreScarySound objectAtIndex:b]];
}
- (void) restoreTransaction: (SKPaymentTransaction *)transaction {
//[[NSUserDefaults standardUserDefaults] setBool:YES forKey:REGISTRATION_KEY];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"Purchase success."
delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
[alert release];
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
//[sq];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction {
if (transaction.error.code != SKErrorPaymentCancelled)
{
// Optionally, display an error here.
NSString *stringError = [NSString stringWithFormat:@"Payment Cancelled\n\n%@", [transaction.error localizedDescription]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:stringError
delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
[alert release];
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
Please have a look and tell me where should i insert data in database so that i will able to provide data to users after Successful in app Purchase.
Thanks in Advance
A: You should implement your unlocking functionality into the payment observer, right after you receive confirmation that the payment is all right.
Your implementation of the observer is kinda strange, I guess it's not working.
EDIT:
your observer class
#import Foundation/Foundation.h
#import StoreKit/StoreKit.h
@interface InAppPurchaseObserver : NSObject {
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions;
@end
#import "InAppPurchaseObserver.h"
@implementation InAppPurchaseObserver
// The transaction status of the SKPaymentQueue is sent here.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
// Item is still in the process of being purchased
NSLog(@"Processing!!!");
break;
case SKPaymentTransactionStatePurchased:
// Item was successfully purchased!
// --- UNLOCK FEATURE OR DOWNLOAD CONTENT HERE ---
// The purchased item ID is accessible via
// transaction.payment.productIdentifier
// After customer has successfully received purchased content,
// remove the finished transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
break;
case SKPaymentTransactionStateRestored:
// Verified that user has already paid for this item.
// Ideal for restoring item across all devices of this customer.
// --- UNLOCK FEATURE OR DOWNLOAD CONTENT HERE ---
// The purchased item ID is accessible via
// transaction.payment.productIdentifier
// After customer has restored purchased content on this device,
// remove the finished transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
break;
case SKPaymentTransactionStateFailed:
// Purchase was either cancelled by user or an error occurred.
NSLog(@"Failed!!!");
if (transaction.error.code != SKErrorPaymentCancelled) {
// A transaction error occurred, so notify user.
NSLog(@"Cancelled!!!");
}
// Finished transactions should be removed from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
break;
}
}
}
@end
implementation
- (void) requestProductData {
inappObserver = [[InAppPurchaseObserver alloc] init];
request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:[arrayProductID objectAtIndex:b-2]]];//@"Scaringmirror11"
request.delegate = self;
[request start];
}
- (void) startPurchase {
//int newB=b-2;
SKPayment *payment = [SKPayment paymentWithProductIdentifier:[arrayProductID objectAtIndex:b-2]];
[[SKPaymentQueue defaultQueue] addTransactionObserver:inappObserver];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamically Button Text? Top rows of three buttons shows the top three values of the database but from the next rows again top three values were shown in the three buttons ?
public class ButtonTest extends Activity {
/** Called when the activity is first created. */
NoteHelper helper = null;
Cursor ourCursor = null;
NoteAdapter adapter = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.list);
helper = new NoteHelper(this);
ourCursor = helper.getAll();
startManagingCursor(ourCursor);
adapter = new NoteAdapter(ourCursor);
list.setAdapter(adapter);
}
catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE :" + e.toString());
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
helper.close();
}
class NoteAdapter extends CursorAdapter {
NoteAdapter(Cursor c) {
super(ButtonTest.this, c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c) {
NoteHolder holder = (NoteHolder) row.getTag();
holder.populateFrom(c, helper);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
NoteHolder holder = new NoteHolder(row);
row.setTag(holder);
return (row);
}
}
My NoteHolder Class Is
static class NoteHolder {
private Button b1 = null;
private Button b2 = null;
private Button b3 = null;
NoteHolder(View row) {
b1 = (Button) row.findViewById(R.id.one);
b2 = (Button) row.findViewById(R.id.two);
b3 = (Button) row.findViewById(R.id.three);
}
void populateFrom(Cursor c, NoteHelper helper) {
if (!c.moveToFirst()) return;
b1.setText(helper.getNote(c));
c.moveToNext();
b2.setText(helper.getNote(c));
c.moveToNext();
b3.setText(helper.getNote(c));
}
}
My SQLiteHelper Class is
class NoteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "note.db";
private static final int SCHEMA_VERSION = 1;
public SQLiteDatabase dbSqlite;
public NoteHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Notes (_id INTEGER PRIMARY KEY AUTOINCREMENT,note TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAll() {
return (getReadableDatabase().rawQuery("SELECT _id,note From Notes",
null));
}
public String getNote(Cursor c) {
return(c.getString(1));
}
public Cursor getById(String id) {
return (getReadableDatabase().rawQuery(
"SELECT _id,note From Notes", null));
}
}
}
My main.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="6dip"
android:background="#1F8B26">
<ListView android:layout_height="wrap_content" android:id="@+id/list"
android:layout_width="fill_parent"></ListView>
A: First I want to say is that Gridview will be more suitable in your case
second you are getting multiple rows because cursor adapter will create those many view that it has rows and for each row you are again reading rows in populateFrom() method so that your rows are being repeated.
Instead of Cursor adapter use Base adapter
Solution
1) first create arraylist from your cursor
2) after getting arraylist create a object of NoteAdapter which is below
3) set adapter in gridview
private class NoteAdapter extends BaseAdapter implements OnClickListener {
ArrayList<Note> arrNote;
LayoutInflater inflater;
public NoteAdapter(ArrayList<Note> arr) {
this.arrNote = arr;
inflater = ExploreDestination.this.getLayoutInflater();
}
@Override
public int getCount() {
return arrNote.size();
}
@Override
public Object getItem(int index) {
return arrNote.get(index);
}
@Override
public long getItemId(int id) {
return id;
}
@Override
public View getView(int position, View v, ViewGroup arg2) {
v = inflater.inflate(R.layout.Notebutton, null);
v.setTag(arrNote.get(position));
((Button)v).setText(arrNote.get(position).getTitle());
v.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
//do your work
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting parse error but I can't see anythting wrong in the line Here is my code:
if($_POST['format'] == "csv")
{
Line 174 -> $objWriter = new PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($FNAME);
} else {
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($FNAME);
}
I am getting parse error: "( ! ) Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$' in B:\wamp\www\SuperPages\action.php on line 174" but I can't see anything wrong."
A: PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')
Looks like a factory method, which I would guess creates the object you want and returns it to you. However, you're using new on it, which you would do if you were creating the object yourself... and not the factory method.
Therefore, just remove new from that line.
A: Remove "new". The createWriter() is static method.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.