text stringlengths 8 267k | meta dict |
|---|---|
Q: Is it *really* worth to use integer over varchar for a set of data? For example if I have a table User, I want to store gender or sex, I'll add a column like sex.
Is it really worth to use an integer and then map it in my favorite programming language?
Like 1 => 'Male' and 2 => 'Female'
Is there any performance reason to do that?
Or could I safely use a varchar which more meaning with 'female' or 'male' almost like I was using mysql ENUM ?
Edit: I here and there that it is sometimes better, sometimes it doesn't matter, so I more looking for benchmark or something over a "it is better" answer.
I mean I think using varchar is actually more meaningfull than an integer, and I would use an integer only if performance are more than 0.3% or something.
A: Ortiginal Answer:
I would suggest storing it in a CHAR(1) column as M or F
It is expressive enough for the specific purpose AND has the speed benefit of being a single character comparison
Update 4 (fixed benchmark):
All previous benchmarks had a fatal flaw that one (the CHAR(1)) table was MyISAM and all other were InnoDB. So I recreated the database with all tables using the MyISAM and the results make much more sense now.
The error creeped in as I used the MySQLWorkbench's wizard to create the tables and forgot to change the database engine in the other tables and it defaulted to InnoDB (I have MySQL 5.5)
So the corrected results are as follows, (I have removed all my previous benchmarks as they were invalid) :
// select queries
$query['char'] = "select count(*) from test_table where gender = 'M'";
$query['char_lower'] = "select count(*) from test_table where LOWER(gender) = 'm'";
$query['varchar'] = "select count(*) from test_table_2 where gender = 'Male'";
$query['varchar_lower'] = "select count(*) from test_table_2 where LOWER(gender) = 'male'";
$query['tinyint'] = "select count(*) from test_table_3 where gender = 1";
// benchmark result
array
'char' => float 0.35457420349121
'char_lower' => float 0.44702696800232
'varchar' => float 0.50844311714172
'varchar_lower' => float 0.64412498474121
'tinyint' => float 0.26296806335449
New Conclusion : TINYINT Is fastest. But my recommendation would be still yo use CHAR(1) as it would be easier for future developers to understand the database.
If you do use TINYINT, my recommendation would be name the column ismale instead of sex and store 0 => Female and 1 => male thus making it a little more easy to understand in raw database.
The table structure for benchmark is this:
CREATE TABLE `test_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gender` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
Only the type of the gender column is different in the 3 tables, the types are:
CHAR(1), VARCHAR(6), TINYINT
All 3 tables have 10000 entries.
A: It will be much faster than doing a string comparison, if you are doing any SELECTS on it.
SELECT * FROM User WHERE Gender = 'female'
Example:
Say I have female as a string. Its 6 characters long. So it has to do a comparison 6 times for every record, and that is using strict casing - it gets more costly to do case insensitive.
Now say I have 123456 as an int. Its one value, not 6 to compare, even though the human readable string is 6 characters long.
Aside
Ideally, Male and Female would be another table and your User table would have a FK to that table.
A: The benefit of storing as varchar is that the data can mostly speak for itself - however, it ends there and only manifests itself in queries against the raw data which will usually be done by a developer that knows the system anyway (exposing data querying functionality to users or others would generally use an application layer, which means you could format it as desired regardless.) And this data is OK to display, but consider having to constantly parse it!
As for storing as an integer, it is a little obfuscated, but so long as it is in the data specification and mappings laid out clearly, then you reap benefits of using the data more productively in your application (using a mapping of map an integer to an enum is a one off thing and exposes a more usable type in terms or branching logic, removing string parsing.) It will also be more efficient than storing strings.
There is of course the route of storing 'options' in a dedicated table and having other table fields reference it, but what I've found in many projects is that this is far from ideal in terms of utilisation, unless still using mappable types - which then the table only serves to obscure things a little more, potentially.
A: Integer are much faster than doing string comparison, but I think your better of using chars 'M' or 'F'. If people dump the table they'll know exactly what you intended and its better than maintaining a join table. Unless we're going to be running across new sexes soon.
A: it depends.. but generally yes.
ints take up less space on disk.
ints compare faster
ints travel over the network faster (smaller)
so if it is one row only, and you query it once a day - you'll never notice, but in general, you will benefit.
A: This is a non-brainer: use ISO 5218 values. Why reinvent the wheel and make your locale-specific and less portable?
Because the set of values is small and stable, you can get away with using a CHECK constraint... oops, I mean, for MySQL create a lookup table with a foreign key!
A: If this is for some homebrew website or application that will serve 10 people, then do whatever you want, performance won't make a difference.
If this is for something real then skip rolling your own implementation of gender and follow the ISO standard for sex. Or at least adhere to standards wherever they exist (thanks Joe Celko!)
0 = not known
1 = male
2 = female
9 = not applicable
Always rightsize your data type
*
*Disk space savings:
At my last job, the pedantic people in charge of designing tables created a column as decimal with 0 precision because it should only be N digits. The difference in storage cost between that and a whole number data type was 1 or 2 bytes. However, as this table was very large the aggregate cost savings of having the smaller data type was measure in gigabytes on the table alone.
*Access savings:
A second cost that most don't think about is the cost to read information from disk or to keep data in memory. In SQL Server, data is stored in 8K pages. If you are using fat data types, it will take more reads to get data off disk and then you can store subsequently fewer data pages in memory. Pulling data off of disk is where you will incur the biggest performance cost. If you want to speed up things that use a database, don't bone the physical implementation.
Implement as the smallest allowable type in your system that will cover the problem domain. For something like gender, use a tinyint (MySQL, SQL Server) or number(5,0) in Oracle and you'll be spending 1 bye of storage for each gender.
Internationlization
M = Male, F = Female, that seems obvious. ¿Verdad? Aqui, nosotros hablamos español. And that's about as far as my Spanish caries me, but my point is that if you ever need to be multi-lingual, 1 will serve males, gentes, mannlich, masculin, etc. M or Male will only serve an English speaking audience. Further more, then you run into weird presentation logic of "We need to translate everything unless it's going to $culture." It is a far cleaner design to have presentation logic is the UI and keep it out of the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Extjs4 set tooltip on each column hover in gridPanel I am getting tooltip on mouse hover by each row for current column but I am unable to get next column tooltip on continue hover on same row.
But I can get it if I hover on another row & again hover any column of the previous row by using:
listeners:{
'itemmouseenter': function (view, record, item, index, e, eOpts) {
var gridColums = view.getGridColumns();
var column = gridColums[e.getTarget(this.view.cellSelector).cellIndex];
Ext.fly(item).set({ 'data-qtip': 'Des:' + column.dataIndex });
}
}
Can anyone show me what I'm missing or point me in the right direction?
A: I was looking through this. I could manage to get the tool tip for each cell by doing something like this:
Ext.getCmp('DynamicDemandGrid').getView().on('render', function(view) {
view.tip = Ext.create('Ext.tip.ToolTip', {
// The overall target element.
target: view.el,
// Each grid row causes its own seperate show and hide.
delegate: view.cellSelector,
// Moving within the row should not hide the tip.
trackMouse: true,
// Render immediately so that tip.body can be referenced prior to the first show.
renderTo: Ext.getBody(),
listeners: {
// Change content dynamically depending on which element triggered the show.
beforeshow: function updateTipBody(tip) {
var gridColums = view.getGridColumns();
var column = gridColums[tip.triggerElement.cellIndex];
var val=view.getRecord(tip.triggerElement.parentNode).get(column.dataIndex);
tip.update(val);
}
}
});
});
Let me know if it helps
A: I have an easy one, using the renderer function:
{
xtype : 'gridcolumn',
dataIndex : 'status',
text : 'Status',
renderer : function(value, metadata) {
metadata.tdAttr = 'data-qtip="' + value + '"';
return value;
}
}
A: {
text: name,
width: 80,
dataIndex: dataIndex,
sortable: true,
listeners: {
afterrender: function ()
{
Ext.create('Ext.ToolTip',
{
target: this.getEl(),
anchor: direction | "top",
trackMouse: true,
html: this.text
});
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Running program in Python [ActiveState Python on Windows] I just started learning python and was writing programs in Python GUI Shell IDLE. The code is the following:
>>> def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string. """
return ";".join(["%s=%s" % (k,v) for k,v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpligrim",\
"database":"master",\
"uid":"sa",\
"pwd":"secret"
}
print(buildConnectionString(myParams))
I am facing a problem while I I try to run this program. In IDLE, when I click on Run Module, a new windows opens up saying "Invalid Syntax"
Here's the screenshot:
I am not able to find how to run this and would appreciate the help in proceeding further with this.
Link: http://i.imgur.com/UzAfY.png
A: It looks like you've copied the header output from a shell window into your module window: You don't want your file to look like this:
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print "Hello World"
You just want this:
print "Hello World"
Delete all that other stuff.
A: Move the if __name__ == "__main__": back by four spaces; your spacing in IDLE is different from that which you've copied and pasted here, the code works fine:
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string. """
return ";".join(["%s=%s" % (k,v) for k,v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpligrim",\
"database":"master",\
"uid":"sa",\
"pwd":"secret" }
print(buildConnectionString(myParams))
Open up a new window in idle and create this as a .py script. Then press F5 to execute, or go to run -> run module
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vDSP_ztoc producing odd results I'm trying to figure out the vDSP functions and the results I'm getting are very strange.
This is related to this question:
Using std::complex with iPhone's vDSP functions
Basically I am trying to make sense of vDSP_vdist as I start off with a vector of std::complex< float >. Now AFAIK I should be able to calculate the magnitude by, simply, doing:
// std::abs of a complex does sqrtf( r^2 + i^2 ).
pOut[idx] = std::abs( pIn[idx] );
However when I do this I see the spectrum reflected around the midpoint of the vector. This is very strange.
Oddly, however, if I use a vDSP_ztoc followed by a vDSP_vdist I get exactly the results I expect. So I wrote a bit of code to try and understand whats going wrong.
bool VecMagnitude( float* pOut, const std::complex< float >* pIn, unsigned int num )
{
std::vector< float > realTemp( num );
std::vector< float > imagTemp( num );
DSPSplitComplex dspsc;
dspsc.realp = &realTemp.front();
dspsc.imagp = &imagTemp.front();
vDSP_ctoz( (DSPComplex*)pIn, 1, &dspsc, 1, num );
int idx = 0;
while( idx < num )
{
if ( fabsf( dspsc.realp[idx] - pIn[idx].real() ) > 0.0001f ||
fabsf( dspsc.imagp[idx] - pIn[idx].imag() ) > 0.0001f )
{
char temp[256];
sprintf( temp, "%f, %f - %f, %f", dspsc.realp[idx], dspsc.imagp[idx], pIn[idx].real(), pIn[idx].imag() );
fprintf( stderr, temp );
}
}
return true;
}
Now whats strange is the above code starts failing when idx = 1 and continues to the end. The reason is that dspsc.realp[1] == pIn[0].imag(). Its like instead of splitting it into 2 different buffers that it has straight memcpy'd half the vector of std::complexes into dspsc.realp. ie the 2 floats at std::complex[0] then the 2 floats in std::complex[1] and so on. dspsc.imagp is much the same. dspsc.imagp[1] = pIn[1].real().
This just makes no sense. Can someone explain where on earth I'm failing to understand whats going on?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to set attribute in image map using JFreeChart How can I set an attribute of an image map using JFreeChart in servlet?
Example:
<map id="imageMap" name="imageMap">
<area shape="rect" coords="98,200,155,328" title="(Section, First Section) = 9" alt="" href="index.html?series=Section&category=First+Section"/>
<area shape="rect" coords="50,301,674,643" title=" axisType='XAXIS' " alt=""/>
<area shape="rect" coords="0,0,50,342" title=" axisType='YAXIS' " alt=""/>
</map>
I want to set the id or the class attribute for each area tag for it to look like this:
<map id="imageMap" name="imageMap" class="sectionImageMap">
<area id="sec_1" class= "section" shape="rect" coords="98,200,155,328" title="(Section, First Section) = 9" alt="" href="javascript:getReports('this')"/>
<area id="sec_2" class= "section" shape="rect" coords="50,301,674,643" title=" axisType='XAXIS' " alt="" href="javascript:getReports('this')"/>
<area id="sec_3" class= "section" shape="rect" coords="0,0,50,342" title=" axisType='YAXIS' " alt="" href="javascript:getReports('this')"/>
</map>
A: You should be able to use org.jfree.chart.annotations.XYAnnotation; several are shown here and in the samples/demos.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot find an element in the window I use these elements - jQuery window. http://fstoke.me/jquery/window/
I create the window and I have a website created div. This div is hidden. When I open the window the div is visible. This works correctly.
When I click on the picture(#imgChatSend) - I want to get value from input(#txtChatInput). Entry is always empty. Why?
This is my code:
HTML
<div id="ChatForm" style="display:none;">
<input id="txtChatInput"name="txtChatInput" type="text" />
<img id="imgChatSend" src="images/btn-send.png" alt="Send" />
</div>
JS
windowchat = $.window({
title: "Chat",
height: 300,
width: 300,
content: $("#ChatForm").html(),
minWidth: 300,
minHeight: 300,
maxWidth: 800,
maxHeight: 800
});
$('#imgChatSend').live('click', function() {
alert($("#txtChatInput").val()); //$("#txtChatInput").val() is ""
return false;
});
A: It seems the window plugin creates a clone of the content you are showing in the window, resulting in 2 inputs with the id txtChatInput.
Using $("#txtChatInput") will refer to the first element found with that specific id (id's are supposed to be unique).
A workaround would be to give your selector a context in which it will start looking for the input:
$('#imgChatSend').live('click', function() {
var $parent = $(this).closest("div"); // get the div the button we just clicked is in
alert($("#txtChatInput", $parent).val()); // tell jquery to only look in this div for the element with id txtChatInput
return false;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create your own security provider with some crypto algorithm? Using official tutorial i understood the main principles of Java Cryptography Architecture.
But neither the officials nor internet gives me anything distinct about creating my own provider and implementing some crypto algorithms.
I wonder if anyone can give me the source code of a simple security provider and/or a source code of some algorithm, which is used by this provider.
Overall, the main target is : a provider class ( simple one, not the complicated like SunJCE ) and a bunch of classes ( or one class ) with cryptography algorithm implementation ( with all it's doFinal and other method, whatever the implementation class needs )
A: Try How to Implement a Provider for the JavaTM Cryptography Extension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I stop a jQuery loop animation? I have an image which is rotated 90 degress right and left continuously and I'm trying to stop it but I can't figure out how.
I tried to put the function in an If statement so I can call function = false; or true but it doesn't work.
Here is a fiddle: http://jsfiddle.net/gpPcU/
A: You can change the callback function to false
$("img").rotate({angle:0, callback:function(){ false; }});
A: You can use the JQuery stop method( http://api.jquery.com/stop/ )
Ex:
$('.img').stop(true, true)
A: This will do it: http://jsfiddle.net/gpPcU/3/
I'm not sure what you tried with the If statement you mentioned because that's not in your fiddle, but you were probably on the right track. Here are the main changes I made:
rotate() callback within test():
function(){
if(!$('img').hasClass('stop')){
rotation()
}else{
$('img').rotate({angle:0});
}
}
Button click event:
$(".btn").click(function(){
$("img").addClass('stop');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Collision of files when doing the "svn up" command via ssh I've been trying to update the server with the "svn up" command via ssh connection, and there was a notification saying that there is a collision of files - it was a jobs_controller file (cakephp).
So I've chosen the postpone option. But the update crashed the server so I reversed the changes by putting back again the old ones, but the job section on the site still doesn't work.
How can I fix it?
A: I assume that your site is in SVN and you check it out onto your server to run it? In which case it sounds like either you still have differences between the copy you are running and what is in SVN, or that what is in SVN doesn't work (ie. Is missing changes that you had locally before reverting). You can use:
svn -u status
to get a list of the files that are different between your local copy and the latest copy in SVN. Also use:
svn diff <filename>
To see differences between that file locally and the same file in SVN.
A: Problem solved, the file on the server was corrupted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Page renders IE6, IE8 but not IE7? I have constructed this page: http://www.letstalkmarketing.co.uk/print
It works fine in IE6 and IE8 but doesn't seem to render anything below the red help and advice block in IE7.
I cannot see what is wrong and frankly without Firebug (Firebug Lite just doesn't really cut it) I am struggling to figure it out.
Thank you for any help you can offer.
A: IE7 and position:relative never were very happy bedfellows. Where you have
.info_boxes {
position: relative;
top: -20px;
}
You would probably do better with
.info_boxes {
position: static;
margin-top: -20px;
}
Alternatively, you could add a width. e.g.
.info_boxes {
width: 630px;
}
You can map this into a ie7 only stylesheet in a similar way as you've already done with iframe_ie6.css, but specifying the IE version in the conditional comment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best Practices for developing a multi-tenant application with Symfony2 and Doctrine2 I am working on an application that needs to support the multi-tenant model. I am using the symfony2 php framework and doctrine2.
I'm not sure the best way to go about architecting this requirement. Does Symfony's ACL functionality provide a part of the solution?
What recommendations or ideas could you provide? Are there any sample symfony2 applications or open source applications that are available which have implemented this strategy?
My first thought is to use a tenant_id column in all the tables and have this relate to the account object in the application. I'm not sure though if ACL is supposed to take care of what i'm wanting to do, or if your still responsible for all of the queries against your objects so they don't return un-authorized data.
If I wasn't using Doctrine, it might be easy to say just append Where tenant_id = @accountid to each query, but i'm not sure that is the right approach here.
Thanks
A: We've been doing this for some time now (although not with symfony and doctrine but the problems remain the same)
- we started with one huge database and implemented a 'environment identifier' per row in each of the tables. This way schema migrations were easy: all the code was unified thus a schema change was a single change to code and schema.
This however lead to problems with speed (large tables), agility (moving/backuping etc large datasets is alot more intensive than alot of smaller ones) and of course more easily breakable environments since a single failure will pull down every dataset in the system...
We then switched to multiple databases; each environment its own schema. By utilizing the migrations provided with Doctrine (1 in our case) we're able to quickly update the entire app or just a single environment. Also the ability to move specific changes between tentants allows for better precision in speed and optimization.
My advice would be: create a single core which is extended into the different tenants and keep the local customized database configuration per tentant. (in a app.ini-like structure)
i.e.
/
apps/
tentant1/
models/ <--- specific to the tenant
libraries/ <--- specific to the tenant
config/
app.ini <--- specific configuration
tentant2/
/**/ etc
core/
models/ <--- system wide models
libraries/ <--- system wide libraries (i.e. doctrine)
core.ini <--- system wide configuration
This could keep everything organized. We are even going as far as having the comeplete structure of core available per tentant. Thus being able to override every aspect of the 'core' specific to the tenant.
A: We do this with one of our main solutions at work, and it's certainly possible. We use Symfony2's bundles to create a "base" bundle which is then extended by other per-client bundles.
That said, we're looking at moving away from doing things this way in the future. The decision to go multi-tenant was not the right one for us, as many of our clients are uncomfortable with their data being in the same database tables as everyone else's data. This is completely aside from the potential issues of slow performance as the tables grow.
We've also found that Doctrine 2 has some pretty serious issues unless it's kept well under control. Whilst this may be a side effect of poorly structured code and database logic, I feel it's a bit of a hole for an ORM to be able to get to the point where it throws a fatal error because it's used too much memory - particularly when the only reason it's using so much memory is because it's batching up SQL queries so that they can be made "more efficient".
This is purely my opinion, of course :) What doesn't work for us may well work for you, but I do feel you'd be better off keeping separate databases per-client, even if they're all stored on the same server.
A: I think that, To manage multi-tenant multi-database with symfony 2/3.
We can config auto_mapping: false for ORM of doctrine.
file: config.yml
doctrine:
dbal:
default_connection: master
connections:
master:
driver: pdo_mysql
host: '%master_database_host%'
port: '%master_database_port%'
dbname: '%master_database_name%'
user: '%master_database_user%'
password: '%master_database_password%'
charset: UTF8
tenant:
driver: pdo_mysql
host: '%tenant_database_host%'
port: '%tenant_database_port%'
dbname: '%tenant_database_name%'
user: '%tenant_database_user%'
password: '%tenant_database_password%'
charset: UTF8
orm:
default_entity_manager: master
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
master:
connection: master
auto_mapping: false
mappings:
AppBundle:
type: yml
dir: Resources/master/config/doctrine
tenant:
connection: tenant
auto_mapping: false
mappings:
AppBundle:
type: yml
dir: Resources/tenant/config/doctrine
After that, we cannot handle connection of each tenant by override connection info in request_listener like article: http://mohdhallal.github.io/blog/2014/09/12/handling-multiple-entity-managers-in-doctrine-the-smart-way/
I hope that, this practice can help someone working with multi-tenant
Regards,
Vuong Nguyen
A: BEST builds different notices in different mind. Please be more specific to ask questions. One of the way to develop multi-tenant system is to put a common primary key in all the tables to build the relationship. The type and nature of the primary key is dependable project wise.
A: Why not to try different databases for each client to keep the data separated and give them unique entry point to your app. Ex: http://client1.project.net which with the routing system will map to client1 database.The bad side of this: more complex database changes, because all databases for each client needs to be upgraded.
A: This is something I've been trying to figure out as well. Best I could come up with (not in an implementation yet, but in theory) is this: give each tenant their own database login and use views to keep them from seeing other people's data.
I ran across this link that describes a way of doing this for just plain old MySQL (not with Symfony/Doctrine).
Basically, you have your actual database tables, but each table has a column that stores the name of the database user that made the row. Views are then created that always filter by this column so whenever a user logs in to the database (via an admin tool or even connecting through Symfony/Doctrine), they are only ever returned records directly associated with them. This allows you to keep the data "separate", but still in one database. When pulling data (say for an entity in Symfony), you are pulling data from a filtered view vs. the actual database table.
Now, this solution isn't exactly Symfony/Doctrine friendly. I was able to get a very quick and rudimentary test of this running before; Doctrine was able to use the database views just fine (it could insert, edit, and delete entries from a view no problem). However, when doing things like creating/updating schema, it's not fun. Granted, Symfony/Doctrine seems pretty extensible, so I'm confident there is a way to have it automated, but this kind of setup isn't supported out-of-the-box. Doctrine would need to be told to update the tables, always append the column for holding the username to the entity tables it creates, update the views as well, etc. (You would also need a way to load up the proper database config in your Symfony app, mainly the different logins as the server and other stuff would be the same.) But, if this can be overcome, your app itself could run these multiple tenants completely "ignorant" of the fact that other people's data is sitting in the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Java multiple arguments dot notation - Varargs I've just acknowledged dot notation for method declaration with multiple arguments
like this:
public function getURLs(URL... urls){
for(int i = 0; i < urls.length; i++){
// walk through array of arguments
}
}
And using like this
getURLs(url1, url2, url3);
where those method arguments are converted implicitly into URL[] urls
*
*Did I understand its behavior properly?
*Where is documentation to this syntax?
*From which version of JRE (J2ME,J2SE,Dalvik) is this supported?
A: Yes, that is how it works. The arguments are automatically put into an array. The argument "urls" behaves like a URL[]. Varargs are documented here. They were introduced in Java 1.5, so, are available in J2SE 1.5+, and all of Android since it supports Java 1.5+ language features. No version of JavaME/J2ME supports it.
A: The syntax was introduced in Java 5 and is called varargs:
http://download.oracle.com/javase/1,5.0/docs/guide/language/varargs.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
} |
Q: Why do I have an empty (but working) table index band in UITableView? Using MonoTouch to develop my very first iPhone application for a customer, I've overridden the UITableViewDataSource.SectionIndexTitles function to provide a string[] array with what I thought would make the letters in the vertical band.
Currently I'm facing a working index band but without any characters displayed:
(I do think the UITableViewDataSource.SectionIndexTitles has the native counterpart sectionIndexTitlesForTableView).
My question:
Can someone give me a hint on what I might be doing wrong here?
I do not have all A-Z characters but some characters missing, maybe this could be an issue?
A: This is a bug in MonoTouch. A workaround is to create a new method in your table source class and decorate it with the Export attribute, passing the native ObjC method to override (sectionIndexTitlesForTableView:):
string[] sectionIndexArray;
//..
[Export ("sectionIndexTitlesForTableView:")]
public NSArray SectionTitles (UITableView tableview)
{
return NSArray.FromStrings(sectionIndexArray);
}
A: I would like to get back to my point...
can you show the way you build the returned value for sectionIndexTitlesForTableView? I just tried with SimpleSectionedTableView sample app from apple http://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007318
with this code:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSMutableArray *a = [[NSMutableArray alloc]initWithCapacity:10];
for (int i = 0; i<[regions count]; i++) {
Region *r = [regions objectAtIndex:i];
NSString *s = r.name;
[a addObject:s];
}
NSArray *ax = [NSArray arrayWithArray:a];
return ax;
}
And everything works fine...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XML data types specification While there is plenty of documentation about XML document structure, there are very few links to how non textual data (eg. integer and decimal numbers, boolean values) should be managed.
Is there a consolidated standard? Could tell me a good starting point?
POST SCRIPT
I add an example because the question is actually too generic.
I've defined a document structure:
<rectangle>
<width>12.45</width>
<height>23.34</heigth>
<rounded_corners>true</rounded_corners>
</rectangle>
Since I'm using DOM, the API is oriented to textual data. Say doc is an instance of Document. doc.createTextNode("takes a string"). That is: API doesn't force towards a particular rapresentation.
So two question arise:
1) saving bolean true as 'true' instead of uhm, 1/0 is a standard?
2) i have to define simple methods that write and parse from and to this string representations. Example. I may use java wrappers to do this conversion:
Float f = 23.34;
doc.createTextNode(f.toString());
but does it adhere to the xml standard for decimal numbers? If so, i can say that a non-java programs can read this data because the data representation is xml.
why not jaxb
This is just an example, my xml is made up of a big tree of data and i need to write and read just a little part of it, so JAXB seems not to fit very well. Binding architecture tends to establish a tight copuling between xml structure and class structure. Good implementations like moxy let you loosen this coupling, but there are cases in wich the two structures simply don't match. In those cases, the DTO used to adapt them would be more work than using DOM.
A: Of course, there are dozens of official standards related to core XML. Some of the important ones:
*
*XML schema 1.1 overview
*XML schema 1.1 - datatypes ('XSD')
*XML schema 1.1 - structures
*Core XML overview
*XML 1.0
*XML 1.1
Further specification like XPath, XQuery are available at www.w3.org/standards/xml/. As you tagged this question with java you may be interested in JAXB as well, which defines a standard approach for mapping XML to Java and vice versa.
A: You can leverage the javax.xml.bind.DatatypeConverter class to convert simple Java types to a String that conforms to the XML Schema specification:
Float f = 23.34f;
doc.createTextNode(DatatypeConverter.printFloat(f));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trigger an Event in javascript before objects finish to load I was trying to write a global JavaScriptfunction which overrides any HTML object (img, iframe, links and so on) before it being loaded by the page. The purpose of the overiding action was to to change the SRC and HREF of these objects using the DOM to any other link.
Unfortunately I didn't find any solution to that without firstly loading the object and only then changing it by the onload event.
My second option was to change the SRC and HREF by matching these attributes with a regular expression and replacing the resultant values. I prefer not to do so because it's slow and consumes a lot of time.
I would be glad if someone can share with his/her experience and help me solve this out.
A: JavaScript only works within the DOM.
You could however, load the page via AJAX, get the content and do any string manipulation on it.
A: If you are trying to modify items that exist in the static HTML of the page, you cannot modify them with javascript until they are successfully loaded by the browser. There is no way to modify them before that. They may or may not be visible to the viewer before you have a chance to modify them.
To solve this issue, there are a couple of options.
*
*Put CSS style rules in the page that causes all items that you want to modify to initially be hidden and then your javascript can modify them and then show them so they will not be seen before your modification.
*Don't put the items that you want to modify in the static part of your HTML page. You can either create them programmatically with javascript and insert them into the page or you can load them via ajax, modify them after loading them via ajax and then insert them into the page.
For both of these scenarios, you will have to devise a fallback plan if javascript is not enabled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: how to check internet connection in java in blackberry I want to check whether internet connection is there or not in blackberry device so that depending on the result I can call webservices to get data or upload data from my application
I have tried this one
CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS))) ||
(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) != false
A: If you want to check the internet connection, then send any url to the web service and check the HTTP Response. If HTTPResponse is 200 then only you are having internet connection. Do like this.......
try
{
factory = new HttpConnectionFactory();
url="Here put any sample url or any of your web service to check network connection.";
httpConnection = factory.getHttpConnection(url);
response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
callback(response);
}else
{
callback(response);
}
} catch (Exception e)
{
System.out.println(e.getMessage());
callback(0);
}
Here "response"=200 then you have an internet connection. otherwise it is a connection problem. You can check this like below...........
public void callback(int i)
{
if(i==200)
{
//You can do what ever you want.
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
int k=Dialog.ask(Dialog.D_OK,"Connection error,please check your network connection..");
if(k==Dialog.D_OK)
{
System.exit(0);
}
}
});
}
}
Here System.exit(0); exit the application where ever you are.
Take these two classes
1)HttpConnectionFactory.java
2)HttpConnectionFactoryException.java
from this link:HttpConnection Classes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: c evaluation order let's assume I have the followin code
#define CHECK(result) do{ \
if(result == 0) \
return false; \
} while(0)
int sum(int a, int b){
return (a + b);
}
int main(){
int a = b = 0;
CHECK(sum(a + b));
reutnr 0;
}
my question is what is an order of evaluation in C, I mean:
result = sum(a, b)
//and only after checking
if(result == 0)
return false;
or
if(sum(a + b) == 0)
return false;
thanks in advance
A: The macro substitution will be done before the actual compiler even sees the code, so the code that is compiled will read
int main(){
int a = b = 0;
do {
if(sum(a+b) == 0)
return false;
} while(0);
reutnr 0;
}
There will never be a variable called result.
Also note that C does not have a keyword called false.
A: C macros are plain text substitutions. The compiler will see exactly:
do {
if(sum(a + b) == 0)
return false;
} while(0);
Your macro does not "generate" a result variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mupdf utilities compiled on Win8 with VS2010: are the exe's executable on every Win system? I compiled the mupdf command line utilities on Windows8 with Visual Studio 2010 Professional with the included VS projects. They work. If I want to move them to another system (any Windows) is it enough to move the exe's?
A: My guess is: yes. Provided that you don't move a 64bit-exe to a 32bit Windows. And provided you move any *.dll files which were compiled alongside the *.exe with them. -- Why don't you just try it?
A: You can move them as long as they are compiled in Release mode. If they are in Debug mode the target machine will need Debug VC libraries installed. Release libraries are usually present on all machines.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Delphi client and ASMX service. Data not received by Operation I have a built a simple ASMX service using Visual Studio 2010. I am have build a simple service client application (form) using Delphi 7. I have used WSDLImport to create a proxy file that contains all type definitions and service operations. Here is the code for the WebService11.pas file.
unit WebService1;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
WebService1Soap = interface(IInvokable)
['{3392229C-09D2-6D56-CE62-6850ABB2629D}']
function Add(const a: Integer): Integer; stdcall;
function Subtract(const a: Integer; const b: Integer): Integer; stdcall;
end;
function GetWebService1Soap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): WebService1Soap;
implementation
function GetWebService1Soap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): WebService1Soap;
const
defWSDL = 'http://localhost/DelphiTest/WebService1.asmx?wsdl';
defURL = 'http://localhost/DelphiTest/WebService1.asmx';
defSvc = 'WebService1';
defPrt = 'WebService1Soap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as WebService1Soap);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(WebService1Soap), 'http://tempuri.org/', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(WebService1Soap), 'http://tempuri.org/%operationName%');
end
.
Following is the file that is contained in the Unit1.pas file that is the actual code of the Form.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, WebService1, InvokeRegistry, Rio, SOAPHTTPClient;
type
TForm1 = class(TForm)
Button1: TButton;
HTTPRIO1: THTTPRIO;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var c : integer;
begin
c := GetWebService1Soap(False,'',HTTPRIO1).Add(10);
ShowMessage(IntToStr(c));
end;
end.
The delphi client is hitting the ASMX service as expected. However, I do not see the data sent as parameter in the "Add" operation. I put a break in the ASMX service source code and inspected the parameter value, which is null.
I have used fiddler to read the message sent by the delphi client, but I cannot see the incoming SOAP message. I can see the SOAP data sent back by the ASMX service, which is an integer value. This integer value is not received by the SOAP client.
I need to understand the following:
1) Is there any other way to read what is sent and received by delphi client. I know that there is a component HTTPRIO1 in Delphi, but I do not know how to I get the request and response data from it.
2) What am I doing wrong here.
*Please not that I am not an expert in Delphi 7 yet. I am basically trying to get a delphi client talk to an ASMX service. I could have used WCF but there is some complexity I am facing, therefore needs to understand if I can get the delphi client talk to a ASMX service based on SOAP 1.1
Added Later:
I have somehow gathered the Request and Response SOAP messages through fiddler 2.
Request SOAP message:
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<NS1:Add xmlns:NS1="http://tempuri.org/">
<a xsi:type="xsd:int">10</a>
</NS1:Add></SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Response SOAP message:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<AddResponse xmlns="http://tempuri.org/">
<AddResult>2</AddResult>
</AddResponse>
</soap:Body>
</soap:Envelope>
A: I have fixed the issue. This was basically due to the SOAP format which wasn't compatible with WCF. I converted the SOAP format to 'Document/Literal'. Please read my other thread How to set THTTPRio.Converter.Options to soLiteralParams in OnBeforeExecuteEvent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3 - how to make a crossing? (routing) I created a controller names. I have a model that contains a names of boys and girls (gender=0 for boys, 1 for girls).
If I set to URL the address localhost:3000/names, so will be rendered the view index.html.erb. In this view is an overview of data that are stored in database.
I am trying to edit it - I want to have on the address localhost:3000/names a crossing - here will be 2 links - BOYS and GIRLS. And after click on one of these links I would like to go on the address localhost:3000/names/girls (or boys) and here I would like to have an overview of data from database...
I am newbie still and I don't know, how to realize it... mainly how to edit my routes.rb - I would like to ask you about a help, how to do it...
Thank you in advance
A: So you want a names_controller with actions boys and girls, and you want routes to those?
How about something like this:
resources(:names) do
collection do
get :boys
get :girls
end
end
Routes collection is documented here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Silverlight databinding doesn't work Below you can see a part of my class definitions:
public class Package {
public int PackageId { get; set; }
public string Name { get; set; }
}
public class Member {
public int MemberId { get; set; }
public string DisplayName { get; set; }
}
public class MemberPackage {
public int PackageId { get; set; }
public int MemberId { get; set; }
public DateTime DateSold { get; set; }
public Member Member { get; set; }
public Package Package { get; set; }
}
These are EF 4 model classes. I pull MemberPackage objects from WCF RIA services and bind them to a DataGrid on the UI. To show the package names I use a binding syntax shown below:
<sdk:DataGridTextColumn Header="Package Name" Binding="{Binding Path=Package.Name}" />
<sdk:DataGridTextColumn Header="Date Sold" Binding="{Binding DateSold}" />
Nothing comes up under the Package Name column but I can see the Date Sold values. What's going on here, doesn't it supposed to work this way?
Thanks in advance.
A: It is something to do with the data context of the view - are you sure Package is a property on your view model (data context) and do the models implement INotifyPropertyChanged?
A: Simply remove the Path= and have this:
<sdk:DataGridTextColumn Header="Package Name" Binding="{Binding Package.Name}" />
You don't need to specify the path.
If that doesn't work then you should need to make sure that the Package member of MemberPackage has the [Include] attribute in the server side definition. This will ensure that the whole hierarchy is serialised to the client. I didn't suggest this at first as I assume that your code was edited.
A: The problem could be that when you get the MemberPackages in the service/factory, make sure you have the .Include("Package") as below:
return this.ObjectContext.MemberPackages
.Include("Package");
This should bring back the Package details as part of the MemberPackage and then your binding to Package.Name should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How should we pass a data to a view in a big ASP.NET MVC web site First of all, I have been a php programmer for a long time and I am a mvc programmer newly. I did a few minor web sites that each have one or two controller at most. But I've started a website that will be very major web site. There will be a lot of data to pass to views.
Now, normally I try to use model approach every time instead of ViewBag or ViewData approach. If the view demands more data, then I change the model class and then recompile the project. Especially, if the topic is an index page, the data to pass to the index's view changes every time. In a big web site, I'll use a lot of partial view that uses different models. So every time, I will have to change the index's model to support those partial views in the index view. if I add a new partial view into index view, I have to add the partial's model into the index's model.
I implement an IndexModel class for an index view every time when I start a website. Then I add properties to this model every time when I add a new partial view to the index.
Now is this a correct approach or should I use ViewBag or ViewData for partials' models. I think the real question is when we should use the model approach and when we shouldn't...
If you share your experiences, I would be grateful.
A: The MVC approach you should use always, especially for simple sites, it's save your time and make application more understandable.
If you write something larger than two pages, you need to use MVVM pattern (growth of MVC), in that case you will escape from using "partial models" with ViewModels.
Model must contain only busines logic.
Be better if you will always use ViewModel (not a Model) for returning data from a view and pass it to view, because it provides some safety.
For facilitate the procedure of copy data from Models to ViewModels use the things like AutoMaper and EmitMapper.
ViewBag and ViewData you should use only for additional data's like item colections for DropDown, or some view-text like page title.
One more advantage of MVVM pattern is better testability. If you write and support really hugh site you may write tests for some responsible parts of code.
For more details you can look at google - MVVM, ASP-MVC.
If i something not understad in you question or miss, write it in the comment ("add comment" ref).
A: I personally prefer to keep my sites consistant and always use Model + Viewmodel (no matter how big the site is) despite the extra work (which isn't much anyway).
It helps with maintainability. I know where and how everything is stored and coded into the site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Image/binary data not being parsed from XMPP vCard Please help, I am stuck with this issue.
Basically I am getting a AVATAR BASED VCARD i can see that in debug mode, but ASMACK is not parsing image properly. Its just dropping the tag which contains the image value.
Logcat shows the XML being received:
DEBUG/SMACK(1336): <NICKNAME>TC</NICKNAME>
DEBUG/SMACK(1336): <PHOTO><TYPE>im
DEBUG/SMACK(1336): age/jpeg</TYPE><BINVAL>iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAACHklEQVR42u2Zv64BQRSH9xmUCrUHEAUShUqlshWJxhOIECJ0oqIQL6BTK
DEBUG/SMACK(1336): 1AKrcYDkEgkKq3/9ya/5DQnTmaxbnb2zkm+Yu1a51szs2dmrJ8vxf1+BzxutxtwK6x/LyAlSvF4PACP6/UKjMBfNR2VqBF4N6QmQgnzxN0WMQIqkXevMwLvdlqe4G63A
DEBUG/SMACK(1336): 5fLBXiuE2svoGoalmWB0WgEtOvE2ghIxVoymQSFQgEUi0VgBF4VOB6PYDqdgslkAmazGaDPicViAYLBIKBotVognU6DT5us/wToBHU2Oq7X68C2bdDtdkGn03lKu90GJ
DEBUG/SMACK(1336): Mjv3+/3QTweB+fzGagGBd5E9RfgiUpfqNVqYLVaAacTlNPpBKQYDocgHA4D/gBVL1D9BaQTXKharYL5fA5IjP+ldKyaMvJye7PZgEAgAKR8uJj+AqpijIKa0HK5BE6HO
DEBUG/SMACK(1336): UmQx3g8BpFIBPDrxFJFewFVUUY3ajQagDoxF3e6TMK/V6lUQCwWA7zslvLxj4DTKV65XAaJRAJQcZbL5UA+nwd0nM1mwWAwADwhuq5UKgFJkI6lpqe/wKsLVNvtFhwOB
DEBUG/SMACK(1336): 7Df759CL7BQKAQoMpkMaDabgIT4g5R+n1/nXwG3IhqNglQqBXq9HvD8/oB2AryT0XBIk/r1eg08u6yirYCqFPnWgpYRkMpd1YvRs5t82grwxKmo+/bGhhF4VcyzGxy+E
DEBUG/SMACK(1336): aDhUhpWnU5djYBbGxtuD5e+FfgFV75bC/jUS/sAAAAASUVORK5CYII=</BINVAL></PHOTO>
DEBUG/SMACK(1336): <EMAIL><HOME/><INTERNET/><PREF/><USERID>test@test.com</
DEBUG/SMACK(1336): USERID>
Here, outputting the packet in my message listener, you can see that the photo tag is dropped. I don't know why asmack doesn't show this.
class MyPacketListener implements PacketListener{
public void processPacket(Packet packet){
System.out.println("IQ Received XML : " + packet);
Log.i("Packet IQ", packet.toString());
}
}
Here is the logcat output:
INFO/System.out(1336): <NICKNAME>TC</NICKNAME>
INFO/System.out(1336): <TITLE></TITLE>
INFO/System.out(1336): <EMAIL><HOME/><INTERNET/><PREF/><USERID>test@test.com</USERID>
A: In org/jivesoftware/smackx/provider/VCardProvider.java, circa line 117, there is this line:
vCard.setEncodedImage(getTagContents("BINVAL"));
which is incorrect. BINVAL is a child of PHOTO, not of vCard. Therefore, the image is getting set to NULL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to use available skins in flex How to use the skins shown on various sites e.g
flex skin site
into my flex project. Please help.
A: Take a look at the source for one of the samples.
Start here to load the first sample.
Then right click and select "View Source" from the context menu, to bring up the source.
You'll see this line of code in the main application file:
<mx:Style source="AeonGraphical.css" />
And that is how you include a css file in a Flex application.
Depending on the content of the CSS file; Flex may pick up the design automatically. Or you may have to specify a styleName on individual components.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery .load() function does not work under phonegap jquery .load() function is not working under phonegap on iPad. it works in mobile safari very well. But it's not working in Phonegap app. Any help would be appreciated.
UPDATE: Here is what the code looks like:
this.image_container.load( function(response, status, xhr) {
var dis = this;
var imgWidth = dis.image_container.width();
var imgHeight = dis.image_container.height();
dis.containerEl.css({
//some css addition
}).animate( { "opacity": "1" }, 400, "linear" );
});
While debugging server response is
{"responseText":"","status":404,"statusText":"error"}
But I only get this in iPad phonegap. In mobile safari it just works fine.
Thanks in advance.
It still is not working. Here is code snippet:
this.image_container.load( function(response, status, xhr) {
var dis = this;
var imgWidth = dis.image_container.width();
var imgHeight = dis.image_container.height();
dis.containerEl.css({
//some css addition
}).animate( { "opacity": "1" }, 400, "linear" );
});
While debugging server response is
{"responseText":"","status":404,"statusText":"error"}
But I only get this in iPad phonegap. In mobile safari it just works fine.
Thanks in advance.
A: Try using a full URL.
AFAIK PhoneGap is actually served as local files. If you want to access external assets or Ajax, then include the protocol, domain and port (if necessary) in the URL.
A: I tried this and it worked fine in both the Android emulator and the iOS simulator.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Remote</title>
<link href="jquery-mobile/jquery.mobile-1.0b3.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0b3.min.js" type="text/javascript"></script>
<script src="phonegap.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#test1').load('index2.html'); // Local Call - This is just a file in the same project called index2.html with the word "Test" in it
$('#test2').load('http://www.twitter.com/help/test.json'); // Remote call
$('#test3').load('http://www.12robots.com/index.cfm .body'); // Another remote call
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1>Page One</h1>
</div>
<div data-role="content">
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
</div>
</div>
</body>
</html>
I did notice that when I tried to load an entire HTML document (including head, body, html tags) that I only got a white screen. But when I only try to load part of a document (like just a div within the body, like my third example below) it works fine. I suspect that the browser just does not like the structure:
<html>
<head>
</head>
<body>
<div>
<html>
<head>
</head>
<body>
</body>
</html>
</div>
</body>
</html>
I don't blame it, I don't like it either.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery plugin call methods Hi i have this little plugin installed:
(function($) {
$.fn.tagfield = function(options) {
if (options && options.add) {
this.each(function(i, elem) {
add_tags(elem, options.add);
});
} if (options && options.remove) {
this.each(function(i, elem) {
remove_tags(elem, options.add);
});
} else {
this.each(function(i, elem) {
var initial_tags = $(elem).val();
$(elem).val('');
tagfield(this, $(elem));
$(initial_tags.split(',')).each(function(i, v) {
v = $.trim(v);
if (v !== '') add_tags(elem, v);
})
});
}
};
var KEYS = {
"enter": "\r".charCodeAt(0),
"space": " ".charCodeAt(0),
"comma": 188,
"backspace": 8
};
var tagfield_id_for = function(real_input) {
return $(real_input).attr('id') + '_tagfield';
};
var add_tags = function(real_input, text) {
remove_tags(real_input, text);
var tag = $('<span class="tag">').append('<span class="text">' + text +'</span>'),
close = $('<a class="close" href="#">X</a>');
close.click(function(e) {
remove_tags(real_input, text);
});
tag.append(close);
$('#' + tagfield_id_for(real_input) + " .tags").append(tag);
real_input = $(real_input);
real_input.val(($.trim(real_input.val()) === '' ? [] : real_input.val().split(',')).concat([text]).join(','));
};
var remove_tags = function(real_input, text) {
$('#' + tagfield_id_for(real_input) + " .tags .tag").each(function(i, v) {
v = $(v);
if (v.find('.text').html() === text) {
v.remove();
real_input = $(real_input);
var tags = $(real_input.val().split(',')).filter(function(i, v) {
return v !== text;
});
real_input.val(Array.prototype.join.call(tags));
}
});
};
var tagfield = function(real_input, elem) {
var tagfield = $('<div class="tagfield">').attr('id', tagfield_id_for(real_input)),
input = $('<input type="text"/>'),
buffer = $('<span class="buffer">'),
tags = $('<span class="tags">');
tagfield.append(tags);
tagfield.append(buffer);
tagfield.append(input);
tagfield.click(function(e) {
input.focus();
});
var check_add_tag = function() {
if (buffer.html()) {
var tag_text = buffer.html();
buffer.html('');
add_tags(real_input, tag_text);
}
};
var add_tag = function(text) {
};
input.keydown(function(e) {
if (e.which === KEYS.enter || e.which === KEYS.space || e.which === KEYS.comma) {
e.preventDefault();
check_add_tag();
}
if (e.which === KEYS.backspace) {
if (buffer.html() === "") {
remove_tags(real_input, tagfield.find('.tag').last().find('.text').html());
} else {
var s = buffer.html();
buffer.html(s.slice(0, s.length-1));
}
}
});
input.blur(check_add_tag);
input.keyup(function(e) {
buffer.append(input.val());
input.val('');
});
$(real_input).hide().after(tagfield);
};
})(jQuery);
does anyone can show me how can i call the methods add_tags() and remove_tags() ?
thanks
A: $("selector").tagfield({remove:someobject});
$("selector").tagfield({add:someobject});
but the "remove" thing will not work i think, since the second "if" in fn.tagfield watches for "options.remove" but removes the "options.add" ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Download a file from a form post I have a c# script that does 2 things
This script connects a my web server to get a pin number generated,
It then makes a connection where its post a form with that pin number it gets from my web server,
The problem is when the form is posted it responds with an application now i need to run this application i don't care if i have to save the exe then run it or if i can run it from memory
Here is my script sofar
string[] responseSplit;
bool connected = false;
try
{
request = (HttpWebRequest)WebRequest.Create(API_url + "prams[]=");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
connected = true;
}
catch(Exception e)
{
MessageBox.Show(API_url + "prams[]=");
}
if (!connected)
{
MessageBox.Show("Support Requires and Internet Connection.");
}
else
{
request = (HttpWebRequest)WebRequest.Create(API_url + "prams[]=");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string responceString = reader.ReadToEnd();
responseSplit = responceString.Split('\n');
WebRequest req = WebRequest.Create("https://secure.logmeinrescue.com/Customer/Code.aspx");
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes("Code=" + responseSplit[1]);
req.ContentLength = bytes.Length;
Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
WebResponse responce = req.GetResponse();
hasDownloaded = true;
}
A: Well you could save the response into a file and then run it (assuming it's an executable of course):
using (var response = req.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var output = new FileStream("test.exe", FileMode.Create, FileAccess.Write))
{
var buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
Process.Start("test.exe");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Include a text or XML file via the script tag? For a little context I'm working on a site for a client and it has to run completely offline. It's just a set of html/css/js files that you run locally. The computers it will be used on are office computers and quite locked down so I can't even use java. Luckily the project isn't overly complicated and I've accomplished most of my goals with this limited platform. The issue I'm having is I want to create some easy to change files to load the data from. Right now I have all the data loading through script tags that point to js files that can be manually edited, however I've tried to make the javascript as simple and straight forward as I can but it's still not looking very friendly to someone who hasn't programmed before.
What I would like to do is include an xml file or text file in the HTML using a script tag or something similar and then use JS to read the contents but every time I try this it doesn't actually load the file. Here's a few things I've tried:
<script type="text/xml" src="myxml.xml"></script>
<script type="text/plain" src="myxml.xml"></script>
I've tried using XMLHttpRequest but most of these attempts end in the same result.. can't do a cross-site request. Even though I'm using a url "myxml.xml" and they're in the same folder, chrome is still convinced this is a XSS attempt. So I'm starting to run out of ideas. Can anyone think of any clever way to achieve this?
A: IF you're goal is to just run your web-app, even offline and you do not care about cross-browser compatibility, you can consider to convert you're application to Packaged App.
It will work only in google-chrome browser but setting the right permissions, you should not have problem with cross-site requests. At this point, you could download the xml content through a noraml XMLHttpRequest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Works as javascript, but doesn't work as a Greasemonkey script? I'm making a Greasemonkey script to add download links beside videos on cnn.com.
I used a saved version of the HTML page to test my script and was able to get it to work perfectly. Then when I put the javascript into Greasemonkey and tried it on the actual site, it didn't work.
This is the not the full script, but the part of the script with the problem. It is simply supposed to add a link at the bottom of every div with the "sec_video_box" class (as seen in the picture).
// ==UserScript==
// @name CNN Download
// @namespace Cool
// @description CNN Download
// @include http://*cnn.com/video/*
// ==/UserScript==
var getClass = function(clssName, rootNode /*optional*/){
var root = rootNode || document,
clssEls = [],
elems,
clssReg = new RegExp("\\b"+clssName+"\\b");
// use the built in getElementsByClassName if available
if (document.getElementsByClassName){
return root.getElementsByClassName(clssName);
}
// otherwise loop through all(*) nodes and add matches to clssEls
elems = root.getElementsByTagName('*');
for (var i = 0, len = elems.length; i < len; i+=1){
if (clssReg.test(elems[i].className)) clssEls.push(elems[i])
}
return clssEls;
};
function insertlinks() {
var boxes = getClass("sec_video_box");
for (i=0; i<boxes.length; i++) {
var theboxid = boxes[i].getAttribute("id");
document.getElementById(theboxid).innerHTML = document.getElementById(theboxid).innerHTML + '<a href="'+ theboxid +'">link</a>';
}
}
window.onload = insertlinks ();
Can someone tell me what I'm doing wrong?
A: window.onload = insertlinks;
Remove the (), they cause the function to run immediately and the return value (null in this case) is assigned to onload. Locally, this is fine since loading is near-instant. Online, however, it will fail.
A: The 3 biggest problems with that script are:
*
*You can't use window.onload that way; see GM Pitfall #2: Event Handlers. Always use addEventListener() or jQuery.
*Those video objects are AJAXed-in after the document loads, anyway.
*Those video objects can change, via AJAX; so you'll want to monitor for new objects.
There are some minor issues but first note that the entire existing script can be simplified to this, with jQuery:
// ==UserScript==
// @name CNN Download
// @namespace Cool
// @description CNN Download
// @include http://*cnn.com/video/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function insertlinks () {
var boxes = $(".sec_video_box");
boxes.each ( function () {
var theboxid = this.id;
$(this).append ('<a href="'+ theboxid +'">link</a>');
} );
}
$(window).load (insertlinks);
(Important: This sample code will still not work.)
Handling the AJAX issues, it becomes:
// ==UserScript==
// @name CNN Download
// @namespace Cool
// @description CNN Download
// @include http://*cnn.com/video/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function insertlink (jNode) {
var theboxid = jNode.attr ('id');
jNode.append ('<a href="' + theboxid + '">link</a>');
}
waitForKeyElements (".sec_video_box", insertlink, false);
function waitForKeyElements (
selectorTxt, /* Required: The jQuery selector string that
specifies the desired element(s).
*/
actionFunction, /* Required: The code to run when elements are
found. It is passed a jNode to the matched
element.
*/
bWaitOnce, /* Optional: If false, will continue to scan for
new elements even after the first match is
found.
*/
iframeSelector /* Optional: If set, identifies the iframe to
search.
*/
)
{
var targetNodes, btargetsFound;
if (typeof iframeSelector == "undefined")
targetNodes = $(selectorTxt);
else
targetNodes = $(iframeSelector).contents ()
.find (selectorTxt);
if (targetNodes && targetNodes.length > 0) {
/*--- Found target node(s). Go through each and act if they
are new.
*/
targetNodes.each ( function () {
var jThis = $(this);
var alreadyFound = jThis.data ('alreadyFound') || false;
if (!alreadyFound) {
//--- Call the payload function.
actionFunction (jThis);
jThis.data ('alreadyFound', true);
}
} );
btargetsFound = true;
}
else {
btargetsFound = false;
}
//--- Get the timer-control variable for this selector.
var controlObj = waitForKeyElements.controlObj || {};
var controlKey = selectorTxt.replace (/[^\w]/g, "_");
var timeControl = controlObj [controlKey];
//--- Now set or clear the timer as appropriate.
if (btargetsFound && bWaitOnce && timeControl) {
//--- The only condition where we need to clear the timer.
clearInterval (timeControl);
delete controlObj [controlKey]
}
else {
//--- Set a timer, if needed.
if ( ! timeControl) {
timeControl = setInterval ( function () {
waitForKeyElements ( selectorTxt,
actionFunction,
bWaitOnce,
iframeSelector
);
},
500
);
controlObj [controlKey] = timeControl;
}
}
waitForKeyElements.controlObj = controlObj;
}
(Which does work.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android: SurfaceView canvas size different from target device pixels I am new to Android programming. I have little game where I draw everything into offscreen canvas. When I want to present it I use calss derived from SurfaceView. It works OK. Problem is that offscreen canvas is 480x800 (target device resolution) pixels but SurfaceView canvas I get through getHolder().lockCanvas() is only 240x480. As a result it looks really ugly - it is first scaled down from offscreen canvas to SurfaceView canvas (loosing small details) and then enlarged to fit device screen (stretched back to original size).
As the emulator is running also 480x800 I have no idea why the SurfaceView is created so small. Why it is not created in the size of emulated device? I finally bypassed it with setting fixed size of holder (getHolder().setFixedSize(480, 800)) but is this correct way?
Is there any other way how to force device to create SurfaceView in size of its pixels?
A: Try adding this to your manifest outside the application tag.
<supports-screens android:anyDensity="true" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UserControl custom property grayed I'm quite sure this is a stupid question, but all my tries failed.
I have a custom control in which I'd like to have a complex property exposing many properties. I want to do this because I would have an expandable property in visual property manager, so I can set sub-properties easily because grouped together in parent property.
This is a schema of what I've done:
public partial class QViewer : UserControl
{
private Shortcuts toolsShortcuts = new Shortcuts();
private TestProp testProp = new TestProp();
public Shortcuts ToolsShortcuts { get { return toolsShortcuts; } }
public TestProp Test { get { return testProp; } }
}
public struct TestProp
{
public bool DoIt;
public DateTime Date;
}
public class Shortcuts
{
Keys toolArrow = Keys.None;
public Keys Arrow
{
get { return toolArrow; }
set { ... }
}
}
}
When I insert my custom control in a form (using another project inside same solution) and I open properties, both Shortcuts and Test are grayed, not expandable, so I can't set properties inside them.
What's wrong? Is there a better way to group properties than creating a class or a struct?
Thanks to everybody!
A: IIRC you need to write a TypeConverter to get the properties window to expand these properties.
Let's assume you use the following type for a complex property:
[DescriptionAttribute("Expand to see the spelling options for the application.")]
public class SpellingOptions
{
private bool spellCheckWhileTyping = true;
private bool spellCheckCAPS = false;
private bool suggestCorrections = true;
[DefaultValueAttribute(true)]
public bool SpellCheckWhileTyping
{
get { return spellCheckWhileTyping; }
set { spellCheckWhileTyping = value; }
}
[DefaultValueAttribute(false)]
public bool SpellCheckCAPS
{
get { return spellCheckCAPS; }
set { spellCheckCAPS = value; }
}
[DefaultValueAttribute(true)]
public bool SuggestCorrections
{
get { return suggestCorrections; }
set { suggestCorrections = value; }
}
}
Your properties probably look like this at the moment:
Notice that the Spell Check Options property is grayed out.
You need to create a TypeConverter to convert your object type so it can be displayed correctly. The .NET framework provides the ExpandableObjectConverter class to make this easier.
For example:
public class SpellingOptionsConverter:ExpandableObjectConverter
{
//...
}
You need to follow these steps to create a custom TypeConverter.
To implement a simple type converter that can translate a string to a Point
*
*Define a class that derives from ExpandableObjectConverter (or TypeConverter).
*Override the CanConvertFrom method that specifies which type the converter can convert from. This method is overloaded.
*Override the ConvertFrom method that implements the conversion. This method is overloaded.
*Override the CanConvertTo method that specifies which type the converter can convert to. It is not necessary to override this method for conversion to a string type. This method is overloaded.
*Override the ConvertTo method that implements the conversion. This method is overloaded.
*Override the IsValid method that performs validation. This method is overloaded.
Take a look at the following MSDN page for more information on how to implement a TypeConverter:
How to: Implement a Type Converter
After you've created the TypeConverter you can apply it to your custom type.
[TypeConverterAttribute(typeof(SpellingOptionsConverter)),
DescriptionAttribute("Expand to see the spelling options for the application.")]
public class SpellingOptions{ ... }
And all will be well:
I quickly summarized an elobarate example from MSDN. You can find an entire walkthrough here:
Getting the Most Out of the .NET Framework PropertyGrid Control
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is writing to tape drives any different? (Plain C and Objective-C) I understand that writing to tape (say floppy) drives using plain C (say the openf statement and subsequent standard C file-write functions) is fundamentally different than writing to regular hard drives. I understand that I have to be careful about what block sizes I use, etc. Can some C veteran confirm that I am right? If I'm right, some further info would be appreciated, such as how I determine the right block size at run-time, etc.
And for Objective-C programmers: Do the Foundation classes to write files abstract away such details in that I can just stop worrying about what kind of a physical media I'm writing to? I.e., do the, say, NSFileManager methods support tape drives without me having to worry about anything?
Note: I am writing a modern Mac app. However, even though tape drives are rare these days (right?), it seems imprudent to just assume them away. Agreed? If this is the case, and Foundation abstracts such details away (which I hope it does), I should much rather prefer Foundation over plain C, right?
A: openf? What OS is this? I always just used open, read, write, and close for writing to tape for the most part. I think there's some ioctl commands to do seeks, and they take a while, but that was it.
As for floppies, they have always just looked like small volumes without a partition map. vfat was the usual Linux volume type, IIRC. Nothing special about accessing them.
P.S. I can honestly say that, unless you need a tape drive, you can assume them away at this point. I got rid of my last one years ago, and at work the sysadmin only uses a few specialized programs (tar, mt, etc.) with them, and it's all scripted. Nobody uses tapes as secondary storage these days.
Further, I use hard drives, a la Time Machine, as backups these days. They are far faster and more cost effective.
A: I don't think the unix concept of filesystems goes all the way to tape drives. Normally, tapedrives are accessed in a completely different manner (using special programs) than mountable media. Foundation will probably help you with mountable media, but not with tape drives that are anyway just used for backup.
A little googleing on tape drives for mac turns up this: LTO4 Tape Archiving on the Mac - and it's from 2009. I haven't found any info about tape drives in snow leopard or lion.
So really, I wonder how you would got about accessing one if you can't even test your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Trying to queue build in TFS server - Calling a target in TFSBuild.Proj I have been using a msbuild file that builds and packages my solution to 'Client' and 'Server'. So far I have been using the below cmd to build from VS cmd prompt:
msbuild.exe MyBuildFile.proj /t:Build
(I have a target called 'Build' which will kick start build and do the rest).
Now, my team wants to queue builds in TFS build server. I read about TFSBuild.proj file. Should I once again write all the scripts in to TFSBuild.Proj or is there a way by which I can call my 'MyBuildFile.proj /t:Build' from TFSBuild.Proj.
Any help is appreciated.
Thanks, Mani
A: You can just include your existing MyBuildFile.proj in a TFS 2010 build:
*
*Create a new build definition
*In the Process page, choose the UpgradeTemplate.xaml workflow
*Select the directory of your checked-in MSBuild.proj file of choice (checked-in under the name TFSBuild.proj)
There might be some subtle differences between your development system and the build server that you need to take care of, but above steps should take you 85%. Enable Diagnostic level build information verbosity (also to be set on the Process page) to troubleshoot loose ends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What runtime is used by most Windows Viruses? Most applications created with Microsoft developer tools need some kind of runtime to be installed first.
However most viruses never need any kind of runtime to work. Also they also seem to use undocumented core/kernel APIs without have lib files etc.
So what runtime/application do most virus /virus writers use ?
A: If the runtime is statically linked in (as opposed to dynamically), then an EXE will be self-contained and you won't need a runtime DLL. However, really, you don't even need a runtime library at all if your code can do everything without calling standard library functions.
As for Windows APIs, in many cases you don't strictly need an import library either -- particularly if you load addresses dynamically via GetProcAddress. Some development tools will even let you link directly against the DLLs (and will generate method stubs or whatever for you). MS tries to ensure that names for documented API calls stay the same between versions. Undocumented functions, not so much...but then, compatibility typically isn't the foremost of concerns anyway when you're deliberately writing malicious software.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Characters Matching Multiple Lexer Rules in ANTLR I've defined multiple lexer rules that potentially matches the same character sequence. For example:
LBRACE: '{' ;
RBRACE: '}' ;
LPARENT: '(' ;
RPARENT: ')' ;
LBRACKET: '[' ;
RBRACKET: ']' ;
SEMICOLON: ';' ;
ASTERISK: '*' ;
AMPERSAND: '&' ;
IGNORED_SYMBOLS: ('!' | '#' | '%' | '^' | '-' | '+' | '=' |
'\\'| '|' | ':' | '"' | '\''| '<' | '>' | ',' | '.' |'?' | '/' ) ;
// WS comments*****************************
WS: (' '|'\n'| '\r'|'\t'|'\f' )+ {$channel=HIDDEN;};
ML_COMMENT: '/*' .* '*/' {$channel=HIDDEN;};
SL_COMMENT: '//' .* '\r'? '\n' {$channel=HIDDEN;};
STRING_LITERAL: '"' (STR_ESC | ~( '"' ))* '"';
fragment STR_ESC: '\\' '"' ;
CHAR_LITERAL : '\'' (CH_ESC | ~( '\'' )) '\'' ;
fragment CH_ESC : '\\' '\'';
My IGNORED_SYMBOLS and ASTERISK match /, " and * respectively. Since they're placed (unintentionally) before my comment and string literal rules which also match /* and ", I expect the comment and string literal rules would be disabled (unintentionally) . But surprisely, the ML_COMMENT, SL_COMMENT and STRING_LITERAL rules still work correctly.
This is somewhat confusing. Isn't that a /, whether it is part of /* or just a standalone /, will always be matched and consumed by the IGNORED_SYMBOLS first before it has any chance to be matched by the ML_COMMENT?
What is the way the lexer decides which rules to apply if the characters match more than one rule?
A:
What is the way the lexer decides which rules to apply if the characters match more than one rule?
Lexer rules are matched from top to bottom. In case two (or more) rules match the same number of characters, the one that is defined first has precedence over the one(s) later defined in the grammar. In case a rule matches N number of characters and a later rule matches the same N characters plus 1 or more characters, then the later rule is matched (greedy match).
Take the following rules for example:
DO : 'do';
ID : 'a'..'z'+;
The input "do" would obviously be matched by the rule DO.
And input like: "done" would be greedily matched by ID. It is not tokenized as the 2 tokens: [DO:"do"] followed by [ID:"ne"].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Deleting a doublepointer (matrix) I am solving a quantum-mech problem which requires me to find some eigenvalues by manipulating some matrices. The specifics of this problem is not relevant, I just need help with the c++ problem, I am new to this language and after a couple of hours I figured any more attempts at solving it myself would be futile and so I turn to you for help.
I have this problem where glibc detects an error at the end of my program and I cannot deallocate properly, it is far too big to copypaste here so I will just replicate the part that actually gives the error.
void hamiltonian(int, double **&);
int i,j;
int main()
{
int N = 1000; double **A;
hamiltonian(N, A);
//Physics here
.
.
.
.
.
//Delete
for(i=0; i<N; i++){delete []A[i];}
delete []A;
return 0;
}
void hamiltonian(int N, double **&A)
{
A = new double *[N];
for(i=0; i<N; i++)
{
A[i] = new double[N];
for(j=0; j<N; j++)
{
if(i==j)A[i][j] = 2;
if(i==j+1 || i==j-1){A[i][j] = 1;}
}
}
}
According to my professor I have to deallocate in the same function as I allocate but I didn't even think about deallocation after being nearly done with my project and so I have to rewrite a lot of code, the problem is that I cannot deallocate A inside the hamiltonian function as I need it in other functions (inside //Physics).
Surely there must be a way around this? Might sound a bit ignorant of me but this sounds like a less efficient design if I have to deallocate in the same function as I allocate.
A: delete A;
Needs to be
delete[] A;
If you new[] it, you MUST delete[] it. Also, use a vector- they take care of themselves.
vector<vector<double>> matrix;
A:
According to my professor I have to deallocate in the same function as I allocate
That is pure silliness. Sometimes (almost always) you need to use the allocated struct outside the function. Definitely false for objects, since constructors and destructors are different functions.
Any way, you can get away without using classes, if you make a Matrix struct and associated newMatrix and deleteMatrix functions :)
#include <cstddef>
#include <iostream>
using namespace std;
struct Matrix
{
int n;
int m;
double** v;
};
Matrix newMatrix (int n, int m)
{
Matrix A;
A.n = n;
A.m = m;
A.v = new double*[n];
for( int i = 0; i < n; i++ ){
A.v[i] = new double[m];
}
return A;
}
Matrix newHamiltonianMatrix (int n, int m)
{
Matrix A = newMatrix(n, m);
for( int i = 0; i < A.n; i++ ){
for( int j = 0; j < A.m; j++ ){
A.v[i][j] = 0.0;
if( i == j ){
A.v[i][j] = 2.0;
}
if( i == j + 1 or i == j - 1 ){
A.v[i][j] = 1.0;
}
}
}
return A;
}
void deleteMatrix (Matrix A)
{
for( int i = 0; i < A.n; i++ ){
delete [] A.v[i];
}
delete [] A.v;
A.v = NULL;
}
int main ()
{
Matrix A = newHamiltonianMatrix(10, 20);
for( int i = 0; i < A.n; i++ ){
for( int j = 0; j < A.m; j++ ){
cout << A.v[i][j] << " ";
}
cout << endl;
}
deleteMatrix(A);
}
A: There are couple of problems with your code.
(1) You are not allocating memory to the pointer members of A. i.e. A[i] are not allocated with new[]. So accessing them is an undefined behavior.
(2) You must do delete[] for a pointer if it was allocated with new[]. In your other function delete A; is wrong. Use delete[] A;
(3) Using new/new[] is not the only way of allocation. In fact you should use such dynamic allocation when there is no choice left. From your code it seems that you are hard coding N=1000. So it's better to use an 2D array.
const int N = 1000; // globally visible
int main ()
{
double A[N][N];
...
}
void hamiltonian (double (&A)[N][N])
{
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL query optimisation - to alias or not? Is there any major difference from an optimisation point of view between the following two alternatives? In the first option I alias the table, so the total_paid calculation is only run once. In the second option, there is no table alias, but the SUM calculation is required a few times.
Option 1
SELECT tt.*, tt.amount - tt.total_paid as outstanding
FROM
(
SELECT t1.id, t1.amount, SUM(t2.paid) as total_paid
FROM table1 t1
LEFT JOIN table2 t2 on t1.id = t2.t1_id
GROUP BY t1.id
) as temp_table tt
WHERE (tt.amount - tt.total_paid) > 0
LIMIT 0, 25
Option 2
SELECT t1.id, t1.amount, SUM(t2.paid) as total_paid
, (t1.amount - SUM(t2.paid)) as outstanding
FROM table1 t1
LEFT JOIN table2 t2 on t1.id = t2.t1_id
WHERE (t1.amount - SUM(t2.paid)) > 0
GROUP BY t1.id
LIMIT 0, 25
Or perhaps there is an even better option?
A: if you run the queries with EXPLAIN, you'll be able to see what's going on 'inside'.
Also, why don't you just run it and compare the execution times?
Read more on explain here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to construct a defaultdict from a dictionary? If I have d=dict(zip(range(1,10),range(50,61))) how can I build a collections.defaultdict out of the dict?
The only argument defaultdict seems to take is the factory function, will I have to initialize and then go through the original d and update the defaultdict?
A: You can construct a defaultdict from dict, by passing the dict as the second argument.
from collections import defaultdict
d1 = {'foo': 17}
d2 = defaultdict(int, d1)
print(d2['foo']) ## should print 17
print(d2['bar']) ## should print 1 (default int val )
A: Read the docs:
The first argument provides the initial value for the default_factory
attribute; it defaults to None. All remaining arguments are treated
the same as if they were passed to the dict constructor, including
keyword arguments.
from collections import defaultdict
d=defaultdict(int, zip(range(1,10),range(50,61)))
Or given a dictionary d:
from collections import defaultdict
d=dict(zip(range(1,10),range(50,61)))
my_default_dict = defaultdict(int,d)
A: You can create a defaultdict with a dictionary by using a callable.
from collections import defaultdict
def dict_():
return {'foo': 1}
defaultdict_with_dict = defaultdict(dict_)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "110"
} |
Q: List of densities for different android devices Is there a list of density values for different android devices? I know how to check it programmatically but I this doesn't work if I don't have a specific device.
A: As a general rule, if you know the screen resolution of the device you can determine what density bucket it's going to fall into. This is because density is a function of resolution and physical size, and manufacturers tend to pick a screen size that fits the display resolution. As such, here is a list I use of all the common resolutions found on the market.
LDPI: QVGA (320x240), WQVGA (432x240)
MDPI: HVGA (480x320), WXGA (1280x800), SVGA (1024x600)
HDPI: WVGA (800x480), FWVGA (854x480)
The reason those two really high resolutions exist in MDPI is because they are only used on tablets, which have a larger screen size...so the dpi rating works out to still be in the midrange.
Also, you may find this information on Screen Sizes and Densities useful, from the Developer portal.
HTH!
A: use this code for it frnd: scale gives you density:
for low scale:0.75
for medium scale:1.0
for large scale:1.5
float scale;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
scale =getApplicationContext().getResources().getDisplayMetrics().density;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Data types where precision level means range of tolerance What existing terminology and art is there for data types that have values implying ranges of tolerance, not specific points?
An example: time values. In ISO 8601 notation, the value 1964 encompasses the values 1964-05, 1964-05-02, 1964-05-02T18, 1964-05-02T18:27, 1964-05-02T18:27:43, 1964-05-02T18:27:43.0613.
That is, each one of those values is not a zero-dimensional point, but an interval encompassing a range of more-precise values.
The more precise values in that set should compare equal to the less-precise ones:
1964 < 1964-05-02 → False
1964 > 1964-05-02 → False
1964 = 1964-05-02 → True
and ‘greater than’ and ‘less than’ should be both false for values encompassed within a less-precise value. The intervals don't overlap, so that's not a concern.
1964-05-02T18:27:43 < 1964-05-02T18:30:11 → True
1964-05-02T18:27:43 < 1964-05-02 → False
1964-05-02T18:27:43 < 1964-05-04 → True
But how should such types be implemented? What kind of comparison am I talking about? What about arithmetic on such values?
In short, what existing body of knowledge should I be looking to for exploration of these concepts?
A: As your italics managed to work out, this is called interval arithmetic.
You're specifically interested in order and equality relationships between interval values. The wikipedia article doesn't talk about that, but i assume it has been worked on, as it's a fairly basic thing to want to do with numbers, even fuzzy ones.
I would imagine that you would say that two intervals are not equal if their ranges do not overlap at all, and that an interval is greater than another interval if the former's range lies entirely above the latter's.
However, i don't think you can have a sensible definition of equal; you might need several different kinds of quasi-equality. You could say two ranges which are not not equal are equal, but i don't think that really helps. That's more like possibly equal. Then there's your idea of one range containing another, in which case you might say that the larger was roughly equal to the smaller. However, since the roughly equal relationship is not symmetric, it's not an equivalence relation, and so it doesn't make a good kind of general-purpose equality.
Or maybe this whole thing is just a generalised case of the idea of significant figures? I suppose interval arithmetic is just the arithmetic you use to deal with numbers that have significant figures.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java - Select object by int How do I select an object by the an int inside it?
Here is code:
String FolderName = result.getString ("name");
String FolderId = result.getString ("category_id");
String ParentId = result.getString ("parent_id");
int intFolderId = Integer.parseInt(FolderId);
int intParentId = Integer.parseInt(ParentId);
System.out.println( FolderId+" "+FolderName+" "+ParentId );
Map<Integer, Folder> data = new HashMap<Integer, Folder>();
Folder newFolder = new Folder(FolderName, intFolderId, intParentId);
data.put(newFolder.getId(), newFolder);
for(Folder folder : data.values())
{
int parentId = folder.getParentFolderId();
Folder parentFolder = data.get(parentId);
if(parentFolder != null)
parentFolder.addChildFolder(folder);
}
How can I select an object with a parentID of 0 for example?
A: Your question is not very clear. You should edit it and try to better explain what you're trying to do.
I'll make the assumption that you have a collection of objects, and you want to select the object using some sort of an ID. If that is the case you can use a java.util.Map implementation to store your objects.
For example:
Map<Integer, MyObject> map = new HashMap<Integer, MyObject>();
map.put(object1.getId(), object1);
map.put(object2.getId(), object2);
//... and so on ...
And you can retrieve the objects using:
MyObject object = map.get(id);
EDIT:
How can I select an object with a parentID of 0 for example?
Maintain a list of children in each Folder. I think you are already doing that, since you have used an addChildFolder() method. Then you simply get the Folder with ID 0 from the map. Its list of children will have parentID 0.
The best way to organize your data structure will depend ultimately on what you're trying to do. You may find this interesting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can I target all tags with a single selector? I'd like to target all h tags on a page. I know you can do it this way...
h1,
h2,
h3,
h4,
h5,
h6 {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
but is there a more efficient way of doing this using advanced CSS selectors? e.g something like:
[att^=h] {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
(but obviously this doesn't work)
A: If you're using SASS you could also use this mixin:
@mixin headings {
h1, h2, h3,
h4, h5, h6 {
@content;
}
}
Use it like so:
@include headings {
font: 32px/42px trajan-pro-1, trajan-pro-2;
}
Edit: My personal favourite way of doing this by optionally extending a placeholder selector on each of the heading elements.
h1, h2, h3,
h4, h5, h6 {
@extend %headings !optional;
}
Then I can target all headings like I would target any single class, for example:
.element > %headings {
color: red;
}
A: SCSS+Compass makes this a snap, since we're talking about pre-processors.
#{headings(1,5)} {
//definitions
}
You can learn about all the Compass helper selectors here:
A: Here is my attempt to solve this problem with (modern) CSS only.
Context : Inside of Joplin (very nice note taking app, link), there is an userfile.css in which you can write your custom CSS for display and export of markdown notes.
I wanted to target all headings directly after (adjacent sibling) certain tags, namely p, ul, ol and nav to add a margin in between. Thus :
p + h1,
p + h2,
p + h3,
p + h4,
p + h5,
p + h6,
ul + h1,
ul + h2,
ul + h3,
ul + h4,
ul + h5,
ul + h6,
ol + h1,
ol + h2,
ol + h3,
ol + h4,
ol + h5,
ol + h6,
nav + h1,
nav + h2,
nav + h3,
nav + h4,
nav + h5,
nav + h6 {
margin-top: 2em;
}
WOW. Very long. Such selectors.
I then came here, learnt, and tried :
p + :is(h1, h2, h3, h4, h5, h6),
ul + :is(h1, h2, h3, h4, h5, h6),
ol + :is(h1, h2, h3, h4, h5, h6),
nav + :is(h1, h2, h3, h4, h5, h6) {
margin-top: 2em;
}
Hmm. Much shorter. Nice.
And then, it struck me :
:is(p, ul, ol, nav) + :is(h1, h2, h3, h4, h5, h6) {
margin-top: 2em;
}
Yay, this also works! How amazoomble!
This might also work with :where() or other CSS combinators like ~ or even (space) to create "matrix" of CSS selectors instead of very long lists.
Credits : all the answers on this page referencing the :is() selector.
A: Stylus's selector interpolation
for n in 1..6
h{n}
font: 32px/42px trajan-pro-1,trajan-pro-2;
A: July 2022 update
The future came and the :is selector is what you're looking for as described in this answer given in 2020 by @silverwind (now the selected answer).
Original answer
To tackle this with vanilla CSS look for patterns in the ancestors of the h1..h6 elements:
<section class="row">
<header>
<h1>AMD RX Series</h1>
<small>These come in different brands and types</small>
</header>
</header>
<div class="row">
<h3>Sapphire RX460 OC 2/4GB</h3>
<small>Available in 2GB and 4GB models</small>
</div>
If you can spot patterns you may be able to write a selector which targets what you want. Given the above example all h1..h6 elements may be targeted by combining the :first-child and :not pseudo-classes from CSS3, available in all modern browsers, like so:
.row :first-child:not(header) { /* ... */ }
In the future advanced pseudo-class selectors like :has(), and subsequent-sibling combinators (~), will provide even more control as Web standards continue to evolve over time.
A: The jQuery selector for all h tags (h1, h2 etc) is " :header ". For example, if you wanted to make all h tags red in color with jQuery, use:
$(':header').css("color","red")
A: It's not basic css, but if you're using LESS (http://lesscss.org), you can do this using recursion:
.hClass (@index) when (@index > 0) {
h@{index} {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
.hClass(@index - 1);
}
.hClass(6);
Sass (http://sass-lang.com) will allow you to manage this, but won't allow recursion; they have @for syntax for these instances:
@for $index from 1 through 6 {
h#{$index}{
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
}
If you're not using a dynamic language that compiles to CSS like LESS or Sass, you should definitely check out one of these options. They can really simplify and make more dynamic your CSS development.
A: The new :is() CSS pseudo-class can do it in one selector.
For example, here's how you could target all headings inside a container element:
.container :is(h1, h2, h3, h4, h5, h6)
{
color: red;
}
Most browsers now support :is(), but keep in mind that most browsers made before 2020 didn't support it without a prefix, so be careful about using this if you need to support older browsers.
In some cases, you may instead want to use the :where() pseudo-class, which is very similar to :is() but has different specificity rules.
A: Plain CSS
With plain css you have two ways. This targets all the heading elements wherever they are inside the page (as asked).
:is(h1, h2, h3, h4, h5, h6) {}
This one does the same but keeps the specificity to 0.
:where(h1, h2, h3, h4, h5, h6) {}
With PostCSS
You can also use PostCSS and the custom selectors plugin
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
:--headings {
margin-top: 0;
}
Output:
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 0;
}
A: No, a comma-separated list is what you want in this case.
A: You could .class all the headings in Your document if You would like to target them with a single selector, as follows,
<h1 class="heading">...heading text...</h1>
<h2 class="heading">...heading text...</h2>
and in the css
.heading{
color: #Dad;
background-color: #DadDad;
}
I am not saying this is always best practice, but it can be useful, and for targeting syntax, easier in many ways,
so if You give all h1 through h6 the same .heading class in the html, then You can modify them for any html docs that utilize that css sheet.
upside, more global control versus "section div article h1, etc{}",
downside, instead of calling all the selectors in on place in the css, You will have much more typing in the html, yet I find that having a class in the html to target all headings can be beneficial, just be careful of precedence in the css, because conflicts could arise from
A: Using scss you can loop through 6 and append to an empty variable $headings using a comma separator
$headings: ();
@for $index from 1 through 6 {
$headings: list.append($headings, h#{$index}, $separator: comma);
}
#{$headings} {
--default: var(--dark);
color: var(--default);
}
Thanks @steve
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "215"
} |
Q: Go to particular revision I cloned a git repository of a certain project. Can I turn the files to the initial state and when I review the files go to revision 2, 3, 4 ... most recent? I'd like to have an overview of how the project was evolving.
A: To go to a particular version/commit run following commands. HASH-CODE you can get from git log --oneline -n 10
git reset --hard HASH-CODE
Note - After reset to particular version/commit you can run git pull --rebase, if you want to bring back all the commits which are discarded.
A: Using a commit's SHA1 key, you could do the following:
*
*First, find the commit you want for a specific file:
git log -n <# commits> <file-name>
This, based on your <# commits>, will generate a list of commits for a specific file.
TIP: if you aren't sure what commit you are looking for, a good way to find out is using the following command: git diff <commit-SHA1>..HEAD <file-name>. This command will show the difference between the current version of a commit, and a previous version of a commit for a specific file.
NOTE: a commit's SHA1 key is formatted in the git log -n's list as:
commit <SHA1 id>
*
*Second, checkout the desired version:
If you have found the desired commit/version you want, simply use the command: git checkout <desired-SHA1> <file-name>
This will place the version of the file you specified in the staging area. To take it out of the staging area simply use the command: reset HEAD <file-name>
To revert back to where the remote repository is pointed to, simply use the command: git checkout HEAD <file-name>
A: To get to a specific committed code, you need the hash code of that commit. You can get that hash code in two ways:
*
*Get it from your github/gitlab/bitbucket account.
(It's on your commit url, i.e: github.com/user/my_project/commit/commit_hash_code), or you can
*git log and check your recent commits on that branch. It will show you the hash code of your commit and the message you leaved while you were committing your code. Just copy and then do git checkout commit_hash_code
After moving to that code, if you want to work on it and make changes, you should make another branch with git checkout -b <new-branch-name>, otherwise, the changes will not be retained.
A: You can get a graphical view of the project history with tools like gitk. Just run:
gitk --all
If you want to checkout a specific branch:
git checkout <branch name>
For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)
git log has a whole set of options to display detailed or summary history too.
I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.
A: I was in a situation where we have a master branch, and then another branch called 17.0 and inside this 17.0 there was a commit hash no say "XYZ". And customer is given a build till that XYZ revision.
Now we came across a bug and that needs to be solved for that customer. So we need to create separate branch for that customer till that "xyz" hash.
So here is how I did it.
First I created a folder with that customer name on my local machine. Say customer name is "AAA"
once that folder is created issue following command inside this folder:
*
*git init
*git clone After this command you will be on master branch. So switch to desired branch
*git checkout 17.0 This will bring you to the branch where your commit is present
*git checkout This will take your repository till that hash commit. See the name of ur branch it got changed to that commit hash no. Now give a branch name to this hash
*git branch ABC This will create a new branch on your local machine.
*git checkout ABC
*git push origin ABC This will push this branch to remote repository and create a branch on git server.
You are done.
A: Before executing this command keep in mind that it will leave you in detached head status
Use git checkout <sha1> to check out a particular commit.
Where <sha1> is the commit unique number that you can obtain with git log
Here are some options after you are in detached head status:
*
*Copy the files or make the changes that you need to a folder outside your git folder, checkout the branch were you need them git checkout <existingBranch> and replace files
*Create a new local branch git checkout -b <new_branch_name> <sha1>
A: One way would be to create all commits ever made to patches. checkout the initial commit and then apply the patches in order after reading.
use git format-patch <initial revision> and then git checkout <initial revision>.
you should get a pile of files in your director starting with four digits which are the patches.
when you are done reading your revision just do git apply <filename> which should look like
git apply 0001-* and count.
But I really wonder why you wouldn't just want to read the patches itself instead? Please post this in your comments because I'm curious.
the git manual also gives me this:
git show next~10:Documentation/README
Shows the contents of the file Documentation/README as they were current in the 10th last commit of the branch next.
you could also have a look at git blame filename which gives you a listing where each line is associated with a commit hash + author.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "806"
} |
Q: Expression Engine CSS Changes My CSS is located at below location
<link rel="stylesheet" href="/site/css/style.css" />
I ant see from where should i edit that CSS from admin
I checked on Googled no use, i checked all the files under
CP Home >> Design >> Template Manager
But it didnt help am i missing something ?
A: Your templates are likely calling the CSS from a flat file, stored outside of ExpressionEngine entirely. Many developers prefer this approach, and it is arguably more performant as well.
Look in your site's web root via FTP for the site folder, and then the css folder inside of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CakePHP controller name in behavior I created relation Post hasMany Photos, Photos actsAs ImageBehavior.
How put to $data['Photo']['model'] = 'Post'? Automated?
A: I'm not sure what you are asking about but when you have a form, you can simply add to your $this->data['Photo']['model'] any value you want with hidden fields.
// photo/add.ctp:
$this->Form->create('Photo');
$this->Form->input('model', array('type' => 'hidden', 'value' =>'yourvalue'));
$this->Form->end('Submit');
Update
You can set this value after the form was submitted, so even if someone will replace the hidden field value you can just check it.
function add(){
if(!empty($this->data['Photo']['model']){
$this->data['Photo']['model'] = "yourvalue";
$this->Photo->save($this->data));
}
else
rest of the code...
}
rest of the code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Avoid a Newline at End of File - Python I'd like to avoid writing a newline character to the end of a text file in python. This is a problem I have a lot, and I am sure can be fixed easily. Here is an example:
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
for i in list:
fileout.write('%s\n' % (i))
This prints a \n character at the end of the file. How can I modify my loop to avoid this?
A: fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
fileout.write('\n'.join(list))
A: Here's a solution that avoids creating an intermediate string, which will be helpful when the size of the list is large. Instead of worrying about the newline at the end of the file, it puts the newline before the line to be printed, except for the first line, which gets handled outside the for loop.
fileout = open('out.txt', 'w')
mylist = ['a', 'b', 'c', 'd']
listiter = iter(mylist)
for first in listiter:
fileout.write(first)
for i in listiter:
fileout.write('\n')
fileout.write(i)
A: In my opinion, a text file consists of lines of text. Lines are terminated with a line feed sequence, the exact details of which is platform-specific. Thus, a proper text file must always contain exactly 1 line feed sequence per line.
Anyway, you could probably solve this by either treating the last line differently, or building up the entire file in-memory and writing it as binary data, taking care to omit the final one or two bytes, depending on your platform's line feed sequence's exact format.
A: If you have really long lists that you don't want to convert into one string with join(), good old flag varaibles come to rescue:
is_first_line = True
for s in my_list:
if is_first_line:
# see, no write() in this branch
is_first_line = False
else:
# we've just written a line; add a newline
output.write('\n')
output.write(s)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: data is not being inserted from this insert query I am using this code to insert the data in my database
but it is not working..
My data is not being inserted in the table ..
what can be the problem??
in function.h
+(BOOL)insertStudentinfoData:(NSString *)first_name last_name:(NSString *)last_name phone_num:(NSString *)phone_num;
in function.m
+(BOOL)insertStudentinfoData:(NSString *)first_name last_name:(NSString *)last_name phone_num:(NSString *)phone_num
{
NSString *sql = [NSString stringWithFormat:@"insert into add_data
values(NULL,'%@','%@','%@')",first_name,last_name,phone_num];
return [DBOperation executeSQL:sql];
}
And I am giving the data from this
[Function insertStudentinfoData:@"hello" last_name:@"w3qrq" phone_num:@"efew"];
but my data is not being inserted in the table
////In DBOperation.h
+(BOOL) executeSQL:(NSString *)sqlTmp {
if(conn == SQLITE_OK) {
NSLog(@"\n\n%@",sqlTmp);
const char *sqlStmt = [sqlTmp cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *cmp_sqlStmt1;
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt1, NULL);
returnValue == SQLITE_OK ? NSLog(@"\n Inserted \n") :NSLog(@"\n Not Inserted \n");
sqlite3_step(cmp_sqlStmt1);
sqlite3_finalize(cmp_sqlStmt1);
if (returnValue == SQLITE_OK) {
return TRUE;
}
}
return FALSE;
}
A: I guess you are passing the NULL value for PRIMARY KEY, first reset the simulator
if you are not specifying the column name and inserting the values then you should pass the value for each column in particular order of column created otherwise its a good idea to specify column
NSString *sql = [NSString stringWithFormat:@"INSERT INTO add_data
(first_name,last_name,phone_num) VALUE('%@','%@','%@')",first_name,last_name,phone_num];
or
NSString *sql =[NSString stringWithFormat:@"INSERT INTO add_data
(first_name,last_name,phone_num,email,address,city,zip) VALUES
('%@','%@','%@','%@','%@','%@','%@');",first_name,last_name,phone_num,email,address,city,zip];
A: are you sure that the database is initialized correctly? I always had trouble with the DB not actually there. Which DB Framework are you using?
[EDIT] do you see this log statement?
NSLog(@"\n\n%@",sqlTmp);
Did you write the DBOperations class yourself? I think there is some issue there with the static variable you're using. I'd suggest to either use an existing db framework like fmdb or something, or else modify your class so that it uses the Singleton Pattern.
Oh, and one thing: Are you calling all methods from the same thread? SQlite DBs are not thread safe!
[edit2] You can use the link provided here: SQLite3 error - iOS to check what the value in returnValue actually states - and then figure out the underlying error.
It's probably best for now to modify your not inserted statement like this:
returnValue == SQLITE_OK ? NSLog(@"\n Inserted \n") :NSLog(@"\n Not Inserted with code: %i\n",returnValue);
A: What if you provide the names of the columns to be inserted:
insert into T (foo, bar, baz)
values( ....)
A: Try it this way to see full error code and message:
The sql comes as NSString *, do not convert it into a cstring.
int rc;
sqlite3_stmt *sel;
if ((rc = sqlite3_prepare_v2(db_handle, [sql UTF8String], -1, &sel, NULL)) != SQLITE_OK) {
NSLog(@"cannot prepare '%@': %d (%s)", sql, rc, sqlite3_errmsg(db_handle));
return;
}
if (sqlite3_step(sel) != SQLITE_DONE) {
NSLog(@"error insert/update: '%s'", sqlite3_errmsg(db_handle));
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I inherit javascript functions ? // Don't break the function prototype.
// pd - https://github.com/Raynos/pd
var proto = Object.create(Function.prototype, pd({
"prop": 42
}));
var f = function() { return "is a function"; };
f.__proto__ = proto;
console.log(f.hasOwnProperty("prop")); // false
console.log(f.prop); // 42
console.log(f()); // "is a function"
.__proto__ is non-standard and deprecated.
How am I supposed to inherit prototypically creating an object but having that object be a function.
Object.create returns an Object not a Function.
new Constructor returns an Object not a Function.
Motivation: - A cross-browser finherit
var finherit = function (parent, child) {
var f = function() {
parent.apply(this, arguments);
child.apply(this, arguments);
};
f.__proto__ = parent;
Object.keys(child).forEach(function _copy(key) {
f[key] = child[key];
});
return f;
};
I don't believe this is possible, so we should probably propose a Function.create to the es-discuss mailing list
/*
Creates a new function whose prototype is proto.
The function body is the same as the function fbody.
The hash of propertydescriptors props is passed to defineproperties just like
Object.create does.
*/
Function.create = (function() {
var functionBody = function _getFunctionBody(f) {
return f.toString().replace(/.+\{/, "").replace(/\}$/, "");
};
var letters = "abcdefghijklmnopqrstuvwxyz".split("");
return function _create(proto, fbody, props) {
var parameters = letters.slice(0, fbody.length);
parameters.push(functionBody(fbody));
var f = Function.apply(this, parameters);
f.__proto__ = proto;
Object.defineProperties(f, props);
return f;
};
})();
Related es-discuss mail
As mentioned in the es-discuss thread there exists a ES:strawman <| prototype operator which would allow for this.
Let's see what it would look like using <|
var f1 = function () {
console.log("do things");
};
f1.method = function() { return 42; };
var f2 = f1 <| function () {
super();
console.log("do more things");
}
console.log(f1.isPrototypeOf(f2)); // true
console.log(f2()); // do things do more things
console.log(f2.hasOwnProperty("method")); // false
console.log(f2.method()); // 42
A: I hope that I'm understanding this right.
I believe you want a functor that's both an instance of a predefined prototype (yes, a class, just not a classic class) as well as directly callable? Right? If so, then this makes perfect sense and is very powerful and flexible (especially in a highly asynchronous environment like JavaScript). Sadly there is no way to do it elegantly in JavaScript without manipulating __proto__. You can do it by factoring out an anonymous function and copying all of the references to all of the methods (which seems to be the direction you were heading) to act as a proxy class. The downsides to this are...
*
*It's very costly in terms of runtime.
*(functorObj instanceof MyClass) will never be true.
*Properties will not be directly accessible (if they were all assigned by reference this would be a different story, but primitives are assigned by value). This can be solved with accessors via defineProperty or simply named accessor methods if necessary (it appears that that is what you're looking for, just add all properties to the functor with defineProperty via getters/setters instead of just functions if you don't need cross-engine support/backwards compatability).
*You're likely to run into edge cases where final native prototypes (like Object.prototype or Array.prototype [if you're inheriting that]) may not function as expected.
*Calling functorObj(someArg) will always make the this context be the object, regardless of if it's called functorObj.call(someOtherObj, someArg) (this is not the case for method calls though)
*Because the functor object is created at request time, it will be locked in time and manipulating the initial prototype will not affect the allocated functor objects like a normal object would be affected (modifying MyClass.prototype will not affect any functor objects and the reverse is true as well).
If you use it gently though, none of this should be a big deal.
In your prototype of your class define something like...
// This is you're emulated "overloaded" call() operator.
MyClass.prototype.execute = function() {
alert('I have been called like a function but have (semi-)proper access to this!');
};
MyClass.prototype.asFunctor = function(/* templateFunction */) {
if ((typeof arguments[0] !== 'function') && (typeof this.execute !== 'function'))
throw new TypeError('You really should define the calling operator for a functor shouldn\'t you?');
// This is both the resulting functor proxy object as well as the proxy call function
var res = function() {
var ret;
if (res.templateFunction !== null)
// the this context here could be res.asObject, or res, or whatever your goal is here
ret = res.templateFunction.call(this, arguments);
if (typeof res.asObject.execute === 'function')
ret = res.asObject.execute.apply(res.asObject, arguments);
return ret;
};
res.asObject = this;
res.templateFunction = (typeof arguments[0] === 'function') ? arguments[0] : null;
for (var k in this) {
if (typeof this[k] === 'function') {
res[k] = (function(reference) {
var m = function() {
return m.proxyReference.apply((this === res) ? res.asObject : this, arguments);
};
m.proxyReference = reference;
return m;
})(this.asObject[k]);
}
}
return res;
};
Resulting usage would look something like...
var aobj = new MyClass();
var afunctor = aobj.asFunctor();
aobj.someMethodOfMine(); // << works
afunctor.someMethodOfMine(); // << works exactly like the previous call (including the this context).
afunctor('hello'); // << works by calling aobj.execute('hello');
(aobj instanceof MyClass) // << true
(afunctor instanceof MyClass) // << false
(afunctor.asObject === aobj) // << true
// to bind with a previous function...
var afunctor = (new MyClass()).asFunctor(function() { alert('I am the original call'); });
afunctor() // << first calls the original, then execute();
// To simply wrap a previous function, don't define execute() in the prototype.
You could even chain bind countless other objects/functions/etc until the cows came home. Just refactor the proxy call a bit.
Hope that helps. Oh, and of course you could change the factory flow so that a constructor called without the new operator then instantiates a new object and returns the functor object. However you prefer (you could surely do it other ways too).
Finally, to have any function become the execution operator for a functor in a bit more elegant of a manner, just make the proxy function a method of Function.prototype and pass it the object to wrap if you want to do something like (you would have to swap templateFunction with this and this with the argument of course)...
var functor = (function() { /* something */ }).asFunctor(aobj);
A: With ES6 it's possible to inherit from Function, see (duplicate) question
javascript class inherit from Function class
default export Attribute extends Function {
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
} |
Q: MATLAB: Center displayed text? How can I center the text printed by display('the text')?
Eg, like the text you get when entering matlab.
A function to get the width of the current terminal will do to (I'll figure it out from there).
A: with a fairly new version of matlab you can do:
sz=get(0, 'CommandWindowSize');
command_line_width = sz(1);
Otherwise, you'll have to use a mex file:
see this link http://www.mathworks.com/matlabcentral/newsreader/view_thread/25315
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ Windows font size question First i'm using the windows api.
So I have an edit control, that needs to be able to fit 22 characters max.
Currently only 12 fit with the font I'd like to use.
Is there any way to resize the font well the user is typing to allow for more text to fit without creating a bunch of fonts?
A: Well, you could. Implement a message handler for EN_CHANGE so you know the text was changed. Use GetWindowDC and DrawTextEx with the DT_CALCRECT and DT_EDITCONTROL flags to measure the size of the text. Send WM_SETFONT to change the font for the control if it doesn't fit and repeat.
The user being pleased with the end result is however very unlikely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android EditText input Okey, I have EditText where user inputs some mathematical expression, and I want to calculate result. It sounds pretty esay at first, but I dont know how to do it in just one EditText?
In regular java, its possible with javax.script, is there any way to do it on Android?
Another issue that is connected to the previous, is that I have 5 TextView where computer put some random numbers, and I want forbid to enter in EditText all other numbers except that 5 numbers that are placed in TextView's.
A: *
*you can make your own calculator. postfix calculator would be enough if expression is not that complex. you can find many postfix calculator implementations on the web and here's mine ( http://kingori.egloos.com/2945966 ). Well, it's written in Korean but you can see my source code.
*second requirement is somewhat complex. you can find numbers from expression by regular expression. so, get numbers first and then compare with 5 nunbers. it's very hard to catch numbers while user types expression.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: escaping html markup I'm building a html table using javascript on the fly and I want to add a cell that may contain html markup. I do not want that markup interpreted but simply displayed.
LogHTML += "<tr><td>" + data + "</td></tr>";
How can I do that? Is there some function or html markup that will accomplish that?
I tried pre but then I get extra spaces.
A: LogHTML += "<tr><td>"+data.replace(/</g,"<")+"</td></tr>";
That's all you need.
A: The best solution is to use DOM instead of innerHTML and to create text node for data.
But you can try this as a quick solution or
function htmlentities(s){
var div = document.createElement('div');
var text = document.createTextNode(s);
div.appendChild(text);
return div.innerHTML;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dynamic rails helpers (eg. link_to method, method) I was wondering how to get some dynamic abilities for my rails helpers:
<h3><%= link_to object.name, ("#{object.class_path.to_s}")_path(object) %></h3>
In this case, throwing it the object's class into a link to. I'm getting confused on how to throw a method within a helper method.
Any advice would be greatly appreciated!
A: You're trying to link to the instance of the object?
<%= link_to object.name, object %>
Rails can construct a #show link from that.
You can use polymorphic_path for more complicated/nested situations:
<%= link_to object.name, polymorphic_path([:edit, @user, object]) %>
...as a synonym for edit_user_#{object.class}_path(@user,object)
A: I seem to have solved this by doing this instead:
<%= link_to object.name, url_for(object) %>
Are there any performance or usability issues using url_for instead of something_path? Is there any difference at all?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Like-box doesn't show wall pictures I have 661 people on my page, but only one appears on my wall.
Anyone know why?
A: You have to set OpenGraphs for your pages.
Then facebook will know which image to set as a thumbnail, title and description.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>The Rock (1996)</title>
<meta property="og:title" content="The Rock"/>
<meta property="og:type" content="movie"/>
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
<meta property="og:site_name" content="IMDb"/>
<meta property="fb:admins" content="USER_ID"/>
<meta property="og:description"
content="A group of U.S. Marines, under command of
a renegade general, take over Alcatraz and
threaten San Francisco Bay with biological
weapons."/>
...
</head>
...
</html>
this is an example of an OpenGraph
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should I _really_ remove dylibs after installing homebrew? I just installed homebrew and saw a message from the install script that said I should consider removing the following "evil" dylibs as they might break builds. Has anyone done this? And if so, did you later find out that you actually needed them?
Here's the dylib list:
/usr/local/lib/CHBrowserView.dylib
/usr/local/lib/libgnsdk_musicid_file.dylib
/usr/local/lib/libgnsdk_sdkmanager.dylib
/usr/local/lib/libjson.0.0.1.dylib
/usr/local/lib/libmusicid_osx.dylib
/usr/local/lib/libpcre.0.0.1.dylib
/usr/local/lib/libpcrecpp.0.0.0.dylib
/usr/local/lib/libpcreposix.0.0.0.dylib
A: NO. If you have something in /usr/local/lib, in all likelihood its because you built it and installed it.
It's an annoying and egotistical error message for Brew to assume that any libraries in /usr/local/lib are 'evil' simply because Brew doesn't know about them.
It is possible that you might have an 'older' version that conflicts with something Brew builds, but.. guh. It'll be painfully obvious when the program dies. And more likely than not if the application tries to dyload it, it also means that when Brew is building things it'll try to link against the old lib anyway. As long as it's arch / version compatible it's no biggie.
It'll also be painfully obvious when something you built pre-Brew can't find the shared library you removed. And given that you may not have the source laying around (or remember how you configured it in the first place..)
I strongly suggest keeping the old libraries around.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How to query by time in MongoDB with PHP? I want to query a collection and get documents which have created less than 3 hours ago.
$realtime = date("Y-m-d H:i:s");
$mongotime = New Mongodate(strtotime($realtime));
$mongotime = $mongotime - 3 hours; //PSEUDOCODE
$some_condition = array('time' => array('$lt'=>$mongotime) );
$result = $db->collection->find( $some_condition );
Is there an effective way to put
$some_condition
part without using IF statement in PHP?
A: I have found the solution.
$diff = 60 * 60 * 3; //3 hours in seconds
$mongotime = New Mongodate(time()-$diff);
$condition = array('time' => array('$lt'=>$mongotime) );
$result = $db->collection->find( $condition );
A: First get the time three hours before now. Then query larger than that time:
define('SECONDS_PER_HOUR', 3600);
$mongotime = New Mongodate(time()-3*SECONDS_PER_HOUR);
$condition = array('time' => array('$lt'=>$mongotime));
$result = $db->collection->find($condition);
There is no need to do some timestamp -> string -> timestamp conversion (as you suggested it) and you should name the constants you use so it's clear what they represent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: JFrame invisible border issue I´ve a little issue I would like to get solved.
On my JFrame there seems to be like an invisible border around the frame. So when something should be invisible or stop at ykoord = 0 e.g., it becomes invisible/stops like 20 pixels from the borders you see. Although the background is painted correctly...
Maybe I need to add something here:
public Game()
{
add(new Board());
setTitle("Game");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(BOARD_WIDTH, BOARD_HEIGTH);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
Please help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to add a page to Multipage Editor from outside the FormEditor? I have a multipage editor to which I want to add a page if the user double cliks on a box in another page of the multipage editor (which is a graphical editor). Is this possible?
without multipage editor, I can do that using the following code:
public void performRequest(Request req) {
if(req.getType() == RequestConstants.REQ_OPEN) {
try {
MyInput input = new MyInput("");
IWorkbenchPage page=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.openEditor(input, MyEditor.ID);
}
catch (PartInitException e) {
e.printStackTrace();
}
}
}
I would really appreciate any help, thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Facebook Linter - Page Admin URI Facebook's Linter used to give me the admin uri when I was logged in with an admin account. Also, it would show what the like button would look like on the page which would have another link to the admin page. Were these features taken away with the new Facebook changes?
How can I find the amin uri of website pages that are liked without the lint feature?
A: What is the og:type of page? This is true only for real-life types, page with og:type article does not have its own "voice".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Prevent selection of a particular item in spark list I have a Spark List which has a custom itemRenderer for rendering each item in the List.
I wish to prevent an item in that list from being selected (based on some custom logic) by the user.
What is the best way I can achieve this?
Here's how my List is defined:
<s:List id="myList" itemRenderer="com.sample.MyItemRenderer" />
and of course, I have a item renderer defined as the class com.sample.MyItemRenderer.
A: The selection of items is handled by the list alone as far as I know, so I would say that you can manage it from there. I would have a field on the Objects that are in the list called "selectable" or something like that and when the list item is changing check to see if the new item is actually selectable and if it isn't then you can either have it clear the selection or reset to the previous selection. You can accomplish that by reacting to the "changing" event on the list component and calling "preventDefault" on the IndexChangeEvent as follows:
protected function myList_changingHandler(event:IndexChangeEvent):void {
var newItem:MyObject = myList.dataProvider.getItemAt(event.newIndex) as MyObject;
if(!newItem.selectable) {
event.preventDefault();
}
}
// Jumping ahead ...
<s:List id="myList" changing="myList_changingHandler(event)" // ... continue implementation
The relevant part of the MyObject class is as follows:
public class MyObject {
private var _selectable:Boolean;
public function MyObject(){
}
public function set selectable(value:Boolean):void {
_selectable = value;
}
public function get selectable():Boolean {
return _selectable;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Divide set into subsets with equal number of elements For the purpose of conducting a psychological experiment I have to divide a set of pictures (240) described by 4 features (real numbers) into 3 subsets with equal number of elements in each subset (240/3 = 80) in such a way that all subsets are approximately balanced with respect to these features (in terms of mean and standard deviation).
Can anybody suggest an algorithm to automate that? Are there any packages/modules in Python or R that I could use to do that? Where should I start?
A: If I understand correctly your problem, you might use random.sample() in python:
import random
pool = set(["foo", "bar", "baz", "123", "456", "789"]) # your 240 elements here
slen = len(pool) / 3 # we need 3 subsets
set1 = set(random.sample(pool, slen)) # 1st random subset
pool -= set1
set2 = set(random.sample(pool, slen)) # 2nd random subset
pool -= set2
set3 = pool # 3rd random subset
A: I would tackle this as follows:
*
*Divide into 3 equal subsets.
*Figure out the mean and variance of each subset. From them construct an "unevenness" measure.
*Compare each pair of elements, if swapping would reduce the "unevenness", swap them. Continue until there are either no more pairs to compare, or the total unevenness is below some arbitrary "good enough" threshold.
A: You can easily do this using the plyr library in R. Here is the code.
require(plyr)
# CREATE DUMMY DATA
mydf = data.frame(feature = sample(LETTERS[1:4], 240, replace = TRUE))
# SPLIT BY FEATURE AND DIVIDE INTO THREE SUBSETS EQUALLY
ddply(mydf, .(feature), summarize, sub = sample(1:3, 60, replace = TRUE))
A: In case you are still interested in the exhaustive search question. You have 240 choose 80 possibilities to choose the first set and then another 160 choose 80 for the second set, at which point the third set is fixed. In total, this gives you:
120554865392512357302183080835497490140793598233424724482217950647 * 92045125813734238026462263037378063990076729140
Clearly, this is not an option :)
A: Order your items by their decreasing Mahalanobis distance from the mean; they will be ordered from most extraordinary to most boring, including the effects of whatever correlations exist amongst the measures.
Assign X[3*i] X[3*i+1] X[3*i+2] to the subsets A, B, C, choosing for each i the ordering of A/B/C that minimizes your mismatch measure.
Why decreasing order? The statistically heavy items will be assigned first, and the choice of permutation in the larger number of subsequent rounds will have a better chance of evening out initial imbalances.
The point of this procedure is to maximize the chance that whatever outliers exist in the data set will be assigned to separate subsets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Clear a group of cache in asp.net mvc 3 I am saving a list to cache. so that there is no need to go to the database eache time when the list needs.
here is the code
public IEnumerable<SelectListItem> GetCategoriesByParentId(int parentCategoryId)
{
string cacheKey = "PC" + parentCategoryId.ToString();
DateTime expiration = DateTime.Now.AddDays(1);
IEnumerable<SelectListItem> categoryList ;
categoryList = HttpContext.Current.Cache[cacheKey] as IEnumerable<SelectListItem>;
if (categoryList == null)
{
categoryList = GetCategoryList(parentCategoryId); // getting category from database
HttpContext.Current.Cache.Add(cacheKey, categoryList, null, expiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
return categoryList;
}
My problem is when a new category is added to the database ,i am still gettting old category list .the list do not contain new category..How can clear the cache ( only category cache) after adding or changing a category
Any ideas?
A: When you insert a new category to the database I suppose you have the parent category id into which this category was inserted so you could remove it from the cache:
HttpContext.Current.Cache.Remove("PC" + parentCategoryId);
Now if the adding of a new category is not done by your application and you have no control over it you may take a look at cache expiration with SQL dependency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Force plaintext copy from a Cocoa WebView I have a Cocoa Webview subclass, and I need to make all text copied from it be plaintext only. I have tried overriding -copy and -pasteboardTypesForSelection, but no luck, and debugging code seems to indicate that those methods are never called. I've also tried setting -webkit-user-modify to read-write-plaintext-only in the css (this would also work in this situation) but that seemed to have no effect.
Any ideas?
A: Okay this seems to work (with the subclass instance as its own editing delegate):
- (BOOL)webView:(WebView *)webView doCommandBySelector:(SEL)command
{
if (command == @selector(copy:)) {
NSString *markup = [[self selectedDOMRange] markupString];
NSData *data = [markup dataUsingEncoding: NSUTF8StringEncoding];
NSNumber *n = [NSNumber numberWithUnsignedInteger: NSUTF8StringEncoding];
NSDictionary *options = [NSDictionary dictionaryWithObject:n forKey: NSCharacterEncodingDocumentOption];
NSAttributedString *as = [[NSAttributedString alloc] initWithHTML:data options:options documentAttributes: NULL];
NSString *selectedString = [as string];
[as autorelease];
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
NSArray *objectsToCopy = [NSArray arrayWithObject: selectedString];
[pasteboard writeObjects:objectsToCopy];
return YES;
}
return NO;
}
Not sure if this is the best way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery FadeIn one element after FadeOut the previous div? jQuery(document).ready(function(){
$(".welcome").fadeOut(9500);
$(".freelance").fadeIn(10000);
$(".freelance").fadeOut(4500);
});
I want the welcome message to fadeOut slowly and then the other div to fadeIn its place and then fadeOut - obviously when the welcome box no longer exists.
<header>
<h1 class="left"><a href="index.html"></a></h1>
<div class="left yellowbox welcome"><p>Welcome to my portfolio.</p></div>
<div class="left greenbox freelance"><p>I am currently available for for work, contact me below.</p></div>
</header>
A: You need to call the additional fadeIn() and fadeOut inside of a callback function to the first one. All animation methods (and many others) in jQuery allow for callbacks:
jQuery(document).ready(function(){
$(".welcome").fadeOut(9500,function(){
$(".freelance").fadeIn(10000, function(){
$(".freelance").fadeOut(4500);
});
});
});
This will cause .welcome to fade out first. Once it's done fading out, .freelance will fade in. Once it's done fading in, it will then fade out.
A: jQuery(document).ready(function(){
$(".welcome").fadeOut(9500, function() {
$(".freelance").fadeIn(500, function () {
$(".freelance").fadeOut(4500);
});
});
});
A: I believe that this code might work
$(".welcome").fadeOut(9500).queue(function(next) {
$(".freelance").fadeIn(10000).queue(function(next) {
$(".freelance").fadeOut(4500);
});
});
A: You probably want .delay()
jQuery(document).ready(function(){
$(".welcome").delay(9000).fadeOut(9500);
$(".freelance").delay(10000).fadeIn(10000);
$(".freelance").delay(145000).fadeOut(4500);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Whats the cost of recursivity in Ruby? I have a ruby service that keeps running forever and I wonder whats the cost of recursivity. When I ctrl-c the service after some time, I get the following error printed:
^Cff.rb:169:in `sleep': Interrupt
from ff.rb:169:in `fetch'
from ff.rb:170:in `fetch'
from ff.rb:187:in `fetch'
from ff.rb:180:in `fetch'
from ff.rb:170:in `fetch'
from ff.rb:187:in `fetch'
from ff.rb:177:in `fetch'
from ff.rb:170:in `fetch'
.... and continue for each recursive call
This makes me wonder if this has a memory cost or if it eventually will fail? Is it bad to use recursive in Ruby like this? Would another solution be better? Ty.
A: AFIAK, Ruby never turns tail call recursion into loops. If you keep calling a function recursively, eventually you'll run out of memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scala and .NET - runs well? some experiences? state of affairs There are a lot of threads about "Should we use scala + .net?" , "What are the benefits of using Scala in .Net?" and so on. But these questions are old (08,09,10).
I know scala is not a very old language and the .net support is new and not 100% supported. But where is scala today with .net? It is a good idea to make a windows .net application with scala? Where are the problems with scala and .net today? I mean a normal scala application runs on .net very well. But what about a big/complex project? Threading and so on... Is here somebody who worked a lot of with scala and .net and could give one's opinion?
Thank you
A: I don't have any experience with .NET & Scala but there is a ScalaDays 2011 video session about it. If you are interested check Scala.NET: What you can do with it today
A: Binaries and sources for the preview version of Scala.NET (library and compiler) can be obtained via SVN:
svn co http://lampsvn.epfl.ch/svn-repos/scala/scala-experimental/trunk/bootstrap
Bootstrapping has been an important step, and ongoing work will add support for missing features (CLR generics, etc). That's work in progress.
For now we're testing Scala.NET on Microsoft implementations only, but we would like our compiler to be useful for as many profiles and runtime implementations as possible.
A survivor's report on using Scala.NET on XNA at http://www.srtsolutions.com/tag/scala
Miguel Garcia http://lamp.epfl.ch/~magarcia/ScalaNET/
A: I suspect the problem with the .net version of Scala is that it's not what most people are using.
If you have a dependency on just a single .net component for your needs, then I'd personally recommend using JNA or another system to bridge across.
Alternatively if you require a .Net component and want to build it in Scala, potentially http://xmlvm.org/ would be better for your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: VBA copy data to Copy Data To New Workbook Based On Criteria I have 2 workbooks - Data file (Sheet: Andhra Pradesh) & Invoice file (new invoice to be added after the last invoice).
I want to use the pivot table in data workbook to create invoice in the invoice workbook. 1 PO number per 1 Invoice.
For example: row 9B DO3566521 will be copied into a new Invoice 300 in Invoice workbook with the following information:
*
*Order Closed Date (A9) to be copied into I16
*PO Number DO666 (B9) to be copied into B31,
*Order ID 1234 (C9) to be copied into A34,
*Spec Name - 3 items (E9:E11) to be copied into B34:B36,
*Invoice Qty (F9:F11) to be copied into G34:G36,
*Invoice Amount (G9:G11) to be copied into I34:36
*PO Number DO667 (B12) should be copied into another new Invoice 301 (a new worksheet 301 to be added in Invoice workbook)...
I can get the Invoice Workbook to add/copy a new worksheet but I'm having trouble copying over the data & writing the loop function. how to create a new invoice if it's a different PO? Any help would be much appreciated!!
BTW, I also have a macro (Sub Get_Spelling()) to convert numbers into words in invoice worksheet (A55). Just wondering how can I join them together so it gets updated automatically when invoice is created.
Data workbook - Sheet Name: Andhra Pradesh
A9 B9 C9 D9 E9 F9 G9
Order Closed Date PO Number Order ID Item Index Spec Name Qty Invoice Amt
15/09/11 DO666 1234 1 A 10 $100
2 B 20 $200
3 C 30 $300
DO667 567 1 L 40 $100
2 K 50 $200
Invoice workbook - Sheet name: Invoice Number (e.g Inv 300)
B31
PO Number DO666
A34 B34 G34 I34
Order ID Spec Name Qty Invoice Amt
1234 A 10 $100
B 20 $200
C 30 $300
Invoice 301
B31
PO Number: DO667
Here is my code:
Option Explicit
Sub Create_Invoice()
Dim oldsheet As Worksheet
Dim newSheet As Worksheet
Dim oldnumber As Integer
Dim newnumber As Integer
Dim databook As Workbook
Dim datasheet As Worksheet
Dim invbook As Workbook
Set databook = ActiveWorkbook
Set invbook = ActiveWorkbook
Application.Workbooks.Open ("C:\Users\Owner\Desktop\New folder\AP VAT Inv 201 -.xls")
'Set invbook = ActiveWorkbook
oldnumber = ActiveSheet.Name
newnumber = oldnumber + 1
ActiveSheet.Copy After:=ActiveWorkbook.ActiveSheet
Set newSheet = ActiveSheet
ActiveSheet.Name = newnumber
ActiveSheet.Range("I15").Value = newnumber
ActiveSheet.Range("I16") = databook.Sheets("Andhra Pradesh").Range("A9")
MsgBox "Invoices have been created successfully"
ActiveWorkbook.Save
End Sub
A: I'm kind of confused by some of what you're asking but something along the lines of the following should work. Just adapt it to your needs.
Sub Main()
Dim wkbook As Workbook
Set wkbook = Workbooks.Add
If Len(dir( ***Your Directory Path *****, vbDirectory)) = 0 Then
MkDir ***Your Directory Path *****
End If
With wkbook
.Title = "Workbook Title"
.Subject = "Workbook Subject"
.SaveAs FileName:= ***Your Directory Path *****\"Workbook Title.xls"
End With
With wkbook.Worksheets("Sheet1")
.Range("I16") = **Your Original Worksheet**.Worksheets("Sheet1").Range("A1").value
'repeat for all values
end with
wkbook.save
wkbook.close
end sub
If I were you I'd pass your values in the original workbook to a variant array and then read through them with a for loop. As in..
dim myValues as Variant
dim I as Integer
myValues = Worksheets("Sheet1").Range("A9:G11").Value
for I = LBound(myValues) to Ubound(myvalues)
'do work here (See the with wkbook statement above)
next I
That should get you started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: YouTube video in UIWebView I have set up a UIWebView to show my YouTube's Channel, I'm using this code
[youTube loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.youtube.com/v/user/MyChannel/"]]];
This work when I build and go on the simulator but when I want to play a video on my device, the video never show up...
The console say that when I compile with my device
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/5.0 (9A5313e)/Symbols/System/Library/Internet Plug-Ins/QuickTime Plugin.webplugin/QuickTime Plugin (file not found).
warning: No copy of QuickTime Plugin.webplugin/QuickTime Plugin found locally, reading from memory on remote device. This may slow down the debug session.
I think I have to install the QuickTime Plugin ? I don't really know what I have to do..
Thanks !
A: You're using a Simulator. Youtube videos are not supported on the simulator. Test yout code out on a device.
Please check this answer on how to embbed youtube videos correctly.
Embedding YouTube videos on
To actually read the channel, I think you can use either the RSS feed for your channel or the youtube data api and parse this, than let the user choose the sperate Videos
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Iterate string lines in NodeJS I get a buffer (and I can make it a string) from child_process.exec() in NodeJS. I need to iterate over the lines of the output string. How would I do this?
A: One way to avoid splitting the whole thing in memory is to process it one line at a time
var i = 0;
while (i < output.length)
{
var j = output.indexOf("\\n", i);
if (j == -1) j = output.length;
.... process output.substr(i, j-i) ....
i = j+1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can you animate a UIImage within a scrollview instead of just the screen In myh App for the iPhone I have a UIScrollView which is twice the height of the actual screen. In the scrollview there is a button which when pressed alternates between the top portion of the scrollview and the bottom (with a nice sliding animation).
In the bottom portion of the ScrollView is a UIImageView which moves from the top of the screen to the bottom of the screen using the built-in animation blocks. Note I said screen which means the bottom visible portion of the UIScrollView.
My problem is that when the user presses the button to change view during the UIImageView's animation the image does not stay on the bottom portion of the ScrollView, instead it keeps animating within the visible portion of the screen, which is not showing the top portion of the ScrollView.
Is there a way to specify the UIImageViews animation is within a ScrollView instead of having it be the visible portion of the screen?
I am using the
UIView animateWithDuration:<#(NSTimeInterval)#> animations:<#^(void)animations#>
code to perform the animation on the UIImageView.
A: Make the UIImageView a subview of your scroll view.
Set the enabled property of your button to NO during the animation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to pass xml while requesting Rest web service I want to pass xml to rest web service with request. I am unable to get how I can do this.
thanks in advance.
A: If you need a code sample:
String response = null;
httppost = new HttpPost(URL_STRING);
httppost.setParams(httpParams);
String s = your_XML_Data_As_String_Or_JSON_Or_Whatever;
try {
StringEntity entity = new StringEntity(s);
httppost.setEntity(entity);
httppost.addHeader("Content-Type", "SomeMIMEType");
response = httpclient.execute(httppost, handler);
} catch (Exception e){
e.printStackTrace }
A: You should not send a file through a request, you just convert that file to something you can send over. Here is an example: http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: mupdf utility pdfdraw output quality always the same whatever dpi and antialiasing parameter I feed it with I am using mupdf utility pdfdraw under Windows but I see that the output is the same for example between 60 and 96 dpi and whatever antialiasing bit parameter I put on the command-line. Processing time is different instead. What's wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSF form - submit > focus on selected input I have this theoretical situation:
*
*one view with one form [ID: frm]
*three components (e.g. h:inputText) [ID: inp1, inp2, inp3]
*three submit buttons [ID: btn1, btn2, btn3]
When I submit the form using btn1, I need to focus to inp1 (analogical btn2 to inp2, btn3 to inp3)
I'm able to use javaScript function like onclick="document.getElementById('frm:inp1').focus();" (it works)
Problem is, that submit button causes recreating of view and after that, javaScript setting is forgotten and component is not selected..
So how do I select a component which remains selected even after the view redraws?
A: You can include a script in your page which will update the focus after page is rendered. Update information about focused input on the server in action listeners. The script can look look like this with jquery:
<script>
$(document).ready(function() { document.getElementById('frm:#{focusInfo.componentId}').focus(); })
</script>
It is assuming you have set componentId property in focusInfo bean in action/actionListener executed on server upon button click. FocusInfo contains componentId with getter and setter and possibly methods switching componentId and registered as actionListeners with your buttons.
A: Use the PrimeFaces component:
<!-- Focus on first field, or first field with error -->
<p:focus context="feesboek"/>
Use this in combination with a focus component and you will rock!
<!-- Default button when pressing enter -->
<p:defaultCommand target="submit"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: recognize debug mode in eclipse how to do something like that in eclipse for c
#ifdef _DEBUG printf("debug mode is on\n");
#elif printf("debug mode is off\n");
I googled it and found that I need to use #ifdeb, but unfortunately it didn't work
thanks in advance for any help
A: The #ifdef and #elif use the whole line as the condition so the printf s are being interpreted as part of the #if. You need to put the code on separate lines and use a #endif to close the #if
e.g.
#ifdef _DEBUG
printf("debug mode is on\n");
#else
printf("debug mode is off\n");
#endif
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rubyMine 'Unable to attach test reporter to test framework' rubyMine 'MiniTest framework was detected' error when running all model tests.
I can run all model tests at the regular command line.
e.g. rake spec:models
When I use rubyMine:
I can run one model test ok.
However when I try to run all tests in model I get
MiniTest framework was detected. It is a limited version of original Test::Unit framework.
RubyMine/IDEA Ruby plugin test runner requires full-featured version of the framework,
otherwise default console tests reporter will be used instead.
Please install 'test-unit' gem and activate it on runtime.
I tried adding the 'test-unit' to my Gemfile and rebundling but now get:
`/home/durrantm/.rvm/rubies/ruby-1.9.2-p180/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)
/home/durrantm/Downloads/RubyMine-3.2.3/rb/testing/runner/tunit_in_folder_runner.rb
Testing started at 9:33 AM ...
Work directory: /home/durrantm/Dropbox_not_syncd/webs/3/rubyists/spec/models}
Loading files....
=========================================
0 files were loaded.
=========================================
Searching test suites...
=========================================
0 test suites, 0 tests, 0 assertions, 0 failures, 0 errors
Process finished with exit code 0`
Note: funny } in work directory. I still get the Unable to attach test_reporter to test fraemwork message.
Versions:
Ubuntu 11
RubyMine 3.2
A: I also had this problem but solved it differently than the other posters.
In rubymine I added the minitest-reporters gem. Then in my minitest_helper.rb I added the following:
require "minitest/reporters"
MiniTest::Unit.runner = MiniTest::SuiteRunner.new
MiniTest::Unit.runner.reporters << MiniTest::Reporters::RubyMineReporter.new
A: On my system, the problem was the "redgreen" gem. It automatically colors the progress marks (dots) and the Test::Unit summary messages based on success or failure. There must be something in RubyMine that's trying to parse the Test::Unit results (the output of "rake test", I imagine), and it's choking on the ANSI sequences.
I commented out "require 'redgreen'" in my test/test_helper.rb, and the problem went away. I really like redgreen for executing "rake test" from the shell, though, so I put this in test_helper to make it work for both "rake test" and within RubyMine:
require 'redgreen' if $stdin.tty?
It may not be redgreen that's causing your problem, but be suspicious of anything which might create unconventional Test::Unit output.
Good luck!
A: I finally got this to work.
Mostly by changing stuff under Menus:
Run -> Edit configurations -> Click on Rspec -> Create a new Configuration.
For the new configuration made sure specs folder points to the application specs models.
Final step (the one that actually that got it working) was to set the working directory (still on the run/debug configuration screen that is) to be my applications root!
The other thing I had also done was to add gem 'test-unit' to the Gemfile and bundled it of course. However later testing (removing it and unbundling) showed it not to be needed and in fact was making tests run multiple times with empty suites (maybe trying default unit::test as well as running rspec).
A: For me, I resolved this issue by making sure files are named correctly. Needed to start with the word test or end with the word test. This really depends your "Test File name mask" under test configurations. For me, mine was: */{_test,test_*}.rb
Ex: test_case_01.rb or case_01_test.rb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Stop windows from showing up as 'tasks' from task manager WPF c# I have a program that opens multiple windows. I have used this method to hide them from ALT+TAB. Now I need the new windows to stop showing up in the 'tasks' tab of task manager.
I don't need the process not to show up in task manager, I just don't want all the windows my program opens to show up in the 'task' tab.
Here is a picture of what I'm trying to get rid of: http://i1096.photobucket.com/albums/g324/thezaza101/Tasklist.jpg
-Thanks
A: Solved thanks to David Heffernan.
On my main window i added a static window field which references my main window.
public static Window main;
Public MainWindow()
{
main = this;
}
On the windows I need to hide from task manager and ALT+TAB, I made my main window its owner:
public HiddenWindow()
{
this.Owner = MainWindow.main;
}
Its really simple, it hides the window from the 'tasks' tab on task manager and also stop people from ALT+TABing into your program.
A: For WPF the only way I currently know of is to set your window's title to string.Empty or set WindowStyle to ToolWindow. Setting ShowInTaskBar to false does not hide your window from the applications list.
A: Another way is to use WindowInteropHelper.
public MainWindow()
{
InitializeComponent();
SourceInitialized += (s, e) =>
{
var win = new WindowInteropHelper(this);
win.Owner = GetDesktopWindow();
};
}
[DllImport("user32.dll", SetLastError = false)]
static extern IntPtr GetDesktopWindow();
A: I hvae the same problem(may some different), here is my code:
subWindow.hide();//this will hide the subWindow
subWindow.show();//if want to show again
you will not see window in task or AlT+TAB after use hide()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: ashx error http handler I'm getting the following error from the following http handler.
Other ashx files are working.
Tell me if you need more info...
Server Error in '/einUsername' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not create type 'WebApplication18.Handler1'.
Source Error:
Line 1: <%@ WebHandler Language="C#" CodeBehind="Handler.ashx.cs" Class="WebApplication18.Handler1" %>
Source File: /einUsername/Handler.ashx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
Code
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
public partial class csIPNexample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// logging ipn messages... be sure that you give write
// permission to process executing this code
string logPathDir = ResolveUrl("Messages");
string logPath = string.Format("{0}\\{1}.txt",
Server.MapPath(logPathDir), DateTime.Now.Ticks);
File.WriteAllText(logPath, "hi");
//
}
}
A: the class in the error info is "WebApplication18.Handler1", however it is "csIPNexample" in the code you provided. Are you sure you posted correct code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to remove Circular Dependency in FOLLOW set Consider a short gramma bellow
S -> Bc | DB
B -> ab | cS
D -> d | epsilon
The FIRST set is
FIRST(S) ={a,c,d}
FIRST(B) = { a,c }
FIRST(D)= { d, epsilon }
in it the
Follow(S)={ Follow(B) }
and
Follow(B) ={ c , Follow(S) }
my question is that how to resolve this circular dependency ?
A: This circular dependency shouldn't be there to start with. this is the algorithm for finding 'follow's:
Init all follow groups to {}, except S which is init to {$}.
While there are changes, for each A∈V do:
For each Y → αAβ do:
follow(A) = follow(A) ∪ first(β)
If β ⇒* ε, also do: follow(A) = follow(A) ∪ follow(Y)
So in your case, you should get:
Follow(S)={c,$}
Follow(B)={c,$}
Follow(D)={a,c}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Sanitizing urls using php for seo friendly I am in the process of turning my urls seo friendly.
My urls for my blog currently look like:
http://domain.com/news/view-article.php?id=23+category=qrops+title=moving-your-pension-abroad---what-are-the-benefits?
How can I ensure characters like @ ? >< don't appear in my url?
How can I avoid duplicate --- ?
Code to generate the url is as follows:
<a class="small magenta awesome" title="View full article" href="view-article.php?id='.$row['id'].'+category='.strtolower($row['category']).'+title='.strtolower(str_replace(" ","-",$row['title'])).'">View full article »</a>
Pretty sure I am doing something wrong but I'm trying...
Help appreciated..
I will move on to using the mod_rewrite in apache afterwards
A: I used to use this function
function SEO($input){
//SEO - friendly URL String Converter
//ex) this is an example -> this-is-an-example
$input = str_replace(" ", " ", $input);
$input = str_replace(array("'", "-"), "", $input); //remove single quote and dash
$input = mb_convert_case($input, MB_CASE_LOWER, "UTF-8"); //convert to lowercase
$input = preg_replace("#[^a-zA-Z]+#", "-", $input); //replace everything non an with dashes
$input = preg_replace("#(-){2,}#", "$1", $input); //replace multiple dashes with one
$input = trim($input, "-"); //trim dashes from beginning and end of string if any
return $input;
}
For an example, you can use this by
echo "<title>".SEO($title)."</title>";
A: I use this sweet function to generate SEO friendly URL
function url($url) {
$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url);
$url = trim($url, "-");
$url = iconv("utf-8", "us-ascii//TRANSLIT", $url);
$url = strtolower($url);
$url = preg_replace('~[^-a-z0-9_]+~', '', $url);
return $url;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Set hardware flow control to sierra wireless modem wismo228 I have a wismo228 modem which i can communicate with using hyperterminal. Currently i set the flow control to none so that this can work.
How can i change the flow control on this modem so i can communicate with it using hardware flow control on hyperterminal?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: c# 4.0 how to add layer to an image I want to embed some images to another image. This should be done as layers so transparency everything will be kept. Images are png. How can i do that ?
This is like using pngout and adding extra layers.
And the main issue with this is the new layer has to have specific position. For example i have 200x200 main image and 24x22 new layer image. I need to be able to start new layer adding point from lets say top 55px left 25px.
Thank you.
A: You can use GSI+ (http://www.codeproject.com/Articles/1355/Professional-C-Graphics-with-GDI), create a region and draw image on top of one another (using transparency for see through effects).
That said, most people these days use WPF and there is a great Stack Overflow answer posted here to that effect - How do I tile and overlay images in WPF?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: It is okay to install ASP.NET MVC 4 along ASP.NET MVC 3? It is okay to install ASP.NET MVC 4 along ASP.NET MVC 3 ? or will it break anything from MVC 3 already in place ?
Thanks.
A: From this page: http://www.asp.net/learn/whitepapers/mvc4-release-notes
Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4
ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the
same computer, which gives you flexibility in choosing when to upgrade
an ASP.NET MVC 3 application to ASP.NET MVC 4.
A: I did a comparison to my cs.proj file.
Change the ProjectGuid from C474BC22-B54A-4EF6-B4D5-C8277E1B0916, to F043A0B8-F6E1-47CE-9EE1-EBC6ACA61B15. Click reload project in Sln file.
I tried everything else, changing ProjectTypeGuids in the csproj file, repaired MVC4 From Programs, reinstalling MVC 3 after removing the Nuget Package Manager because of a conflict between the WebPlatForm installer. Then installing SP1 for VS2010. To no avail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can i convert a time (12:30 am) into timestamp using javascript? Can anyone tell me how to that? I would like to compare 2 times and find out which one is greater? like 12:30 pm and 5:30 pm
A: Use Date().parse()
Date.parse('24/09/2011 15:21:41')
A: If the input is always similar as mentioned at the question:
var time1 = "12:30 pm";
var time2 = "5:30pm";
var time1_higher_than_time2 = compareTime(time1, time2);
if(time1_higher_than_time2) alert("Time1 is higher than time 2");
else alert("Time1 is not higher than time 2. "); /* Time1 <= time2*/
/*Illustrative code. Returns true if time1 is greater than time2*/
function compareTime(time1, time2){
var re = /^([012]?\d):([0-6]?\d)\s*(a|p)m$/i;
time1 = time1.match(re);
time2 = time2.match(re);
if(time1 && time2){
var is_pm1 = /p/i.test(time1[3]) ? 12 : 0;
var hour1 = (time1[1]*1 + is_pm1) % 12;
var is_pm2 = /p/i.test(time2[3]) ? 12 : 0;
var hour2 = (time2[1]*1 + is_pm2) % 12;
if(hour1 != hour2) return hour1 > hour2;
var minute1 = time1[2]*1;
var minute2 = time2[2]*1;
return minute1 > minute2;
}
}
A: Turn the times into javascript dates, call getTime() on the dates to return the number of milliseconds since midnight Jan 1, 1970.
Compare the getTime() returned values on each date to determine which is greater.
For 12 Hour format the code below will work.
var date1 = new Date('Sat Sep 24 2011 12:30:00 PM').getTime(); //12:30 pm
var date2 = new Date('Sat Sep 24 2011 5:30:00 PM').getTime(); //5:30 pm
if(date1 > date2) {
alert('date1 is greater');
} else if(date2 > date1) {
alert('date2 is greater');
} else {
alert('dates are equal');
}
A: Just parse it in 12H time and compared them.
Running example in here
var date1 = Date.parse('01/01/2001 12:30 PM');
var date2 = Date.parse('01/01/2001 5:30 PM');
console.log(date1 > date2);
A: Check out the below link-
http://www.dotnetspider.com/forum/162449-Time-Comparison-Javascript.aspx
You can test out your javascript online here -
http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
<html>
<head>
<script type="text/javascript">
var start = "01:00 PM";
var end = "11:00 AM";
var dtStart = new Date("1/1/2007 " + start);
var dtEnd = new Date("1/1/2007 " + end);
var difference_in_milliseconds = dtEnd - dtStart;
if (difference_in_milliseconds < 0)
{
alert("End date is before start date!");
}
</script>
</head>
<body>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use a mask with QPainter? I have a shape (in blue) loaded from a PNG with transparency:
Then I'm drawing several circles on top of this shape (in red) with QPainter::drawEllipse.
The result of that is somewhat similar to the third picture with the red shape completely covering the blue one:
What I would like however is for the blue shape to act as a mask to the red one, with a result like this:
Is it possible to do that with QPainter?
A: It's possible. Assuming you're loading your PNG into a QImage, you can do something like this to create a mask from your image:
QImage img("your.png");
QPixmap mask = QPixmap::fromImage(img.createAlphaMask());
See the other to create*Mask functions in QImage for alternatives.
Then it's a simple matter of setting the painter's clip region:
QPainter p(this);
p.setClipRegion(QRegion(mask));
Here's a stupid demo (don't use that code as-is, the image loading, mask and region creation should be cached, they are potentially expensive):
#include <QtGui>
class W: public QWidget
{
Q_OBJECT
public:
W(): QWidget(0) { }
protected:
void paintEvent(QPaintEvent *)
{
QPainter p(this);
QImage img("../back.png");
QPixmap mask = QPixmap::fromImage(img.createAlphaMask());
// draw the original image on the right
p.drawImage(300, 0, img);
// draw some ellipses in the middle
p.setBrush(Qt::red);
for (int i=0; i<100; i+=10)
p.drawEllipse(i+150, i, 20, 70);
// and do the same thing, but with the mask active
p.setClipRegion(QRegion(mask));
for (int i=0; i<100; i+=10)
p.drawEllipse(i, i, 20, 70);
}
};
Which produces something like this:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: TabPage doesn't repaint the background image I have a TabControl and a TabPage inside it. BackgroundImage consists of lines attaching the points. So I have some polygon. All these points are kept in the storage. each point has the time property when it was drawn. So I want to repaint the picture using the delays between points. i have the next code
Page pg;
if (storage.book.TryGetValue(currTPage.Name, out pg))
{
currTPage.BackgroundImage = new Bitmap(currTPage.Width, currTPage.Height);
Graphics grap = Graphics.FromImage(currTPage.BackgroundImage);
grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
foreach (Sequence seq in pg.pageSeq)
{
Dot startDot = null;
Pen pen = new Pen(Color.FromArgb(seq.r, seq.g, seq.b), 1);
foreach (Dot dot in seq.seq)
{
int sX;
int sY;
if (filter.getPageParameters(currentPattern).orientation == Orientation.Landscape)
{
if (this.currTPage.Width / (double)this.currTPage.Height >= 1.4)
{
sX = (int)(dot.x * this.currTPage.Height / pageHeight) + (currTPage.Width - Convert.ToInt32(this.currTPage.Height * Math.Sqrt(2))) / 2;
sY = (int)(dot.y * this.currTPage.Height / pageHeight);
}
else
{
sX = (int)(dot.x * this.currTPage.Width / pageWidth);
sY = (int)(dot.y * this.currTPage.Width / pageWidth) + (currTPage.Height - Convert.ToInt32(this.currTPage.Width / Math.Sqrt(2))) / 2;
}
}
else
{
if (this.currTPage.Width / (double)this.currTPage.Height <= 1 / 1.4)
{
sX = (int)(dot.x * this.currTPage.Width / pageWidth);
sY = (int)(dot.y * this.currTPage.Width / pageWidth) + (currTPage.Height - Convert.ToInt32(this.currTPage.Width * Math.Sqrt(2))) / 2;
}
else
{
sX = (int)(dot.x * this.currTPage.Height / pageWidth) + (currTPage.Width - Convert.ToInt32(this.currTPage.Height / Math.Sqrt(2))) / 2;
sY = (int)(dot.y * this.currTPage.Height / pageWidth);
}
}
if (startDot == null)
{
startDot = new Dot(sX, sY, dot.time, dot.force);
continue;
}
Dot newDot = new Dot(sX, sY, dot.time, dot.force);
grap.DrawLine(pen, startDot.x, startDot.y, newDot.x, newDot.y);
Thread.Sleep((int)(newDot.time - startDot.time));
currTPage.Invalidate(new Rectangle(Math.Min(startDot.x, newDot.x) - 1, Math.Min(startDot.y, newDot.y) - 1, Math.Abs(startDot.x - newDot.x) + 1, Math.Abs(startDot.y - newDot.y) + 1));
startDot = newDot;
}
}
currTPage.Invalidate();
}
but the picture even doesn't vanish in the beginning of the repainting. it just flash in the end when i do "currTPage.Invalidate();"
What I do wrong?
A: Thread.Sleep((int)(newDot.time - startDot.time));
currTPage.Invalidate(new Rectangle(...));
Your code is fundamentally incompatible with the way painting works in Windows. This code runs on the main thread, like it should, but a thread can do only one thing at a time. It cannot paint the window at the same time it is sleeping or executing your loop. Painting happens after your event handler exits and execution resumes the message loop, the one started by Application.Run(). When there's nothing more important to do, like handling user input, Windows looks if any part of the window was marked invalid (your Invalidate()) call and generates the Paint event.
You can now probably see what happens, you didn't implement the Paint event. So it does the default drawing, it erases everything you drew and restores the default appearance of the tab page. The only reason you saw anything at all is because you used Sleep().
You'll need to completely rewrite this. Use a Timer with an Interval value that is the same as the Sleep(). And a class field that keeps track of the dot index. In the Tick event handler, call Invalidate() and increment the index. And implement the Paint event to do the drawing.
A: After you construct the new Graph you are not setting it to be the new background of the TabPage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does a TableViewCell have to have its own class? I have successfully used custom UITableViewCells using separate classes, but I keep thinking there is an easier way so I have tried the following. The table builds, but the cells are blank (so presumably my custom cell is not displaying correctly). Any ideas appreciated.
My files are:
@interface RemediesPopUp : UIViewController <UITableViewDataSource, UITableViewDelegate>{
UITableView *remediesDataTable;
UITableViewCell *remediesTableCell; // ** custom cell declared here **
NSArray *remediesArray;
}
The table controls are:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
remediesTableCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (remediesTableCell == nil) {
remediesTableCell = [[[UITableViewCell alloc] init] autorelease];
}
// Configure the cell.
return remediesTableCell;
}
I dragged a custom cell object into the XIB file pane (so I have the View and a separate custom cell displayed). I connected the custom cell to File Manager. To test, I pasted a couple of (static) labels onto the custom cell so I could see if it was loading.
The page and table loads just fine, but the cells are blank (white).
Any ideas?
A: First off, make sure that your custom cell is a custom subclass (subclass of UITableViewCell) and has its own nib file (for example, don't integrate it with your table view controller).
In the nib, select the identity inspector and ensure that your cell's class is CustomCell (or whatever you called it). Also make sure that under the attributes inspector you set its Identifier to "CustomCellIdentifier" or similar.
In your table view data source, your tableView:cellForRowAtIndexPath method should contain code similar to this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = @"CustomCellIdentifier"; // Same as you set in your nib
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id oneCell in nib) {
if ([oneObject isKindOfClass:[CustomCell class]]) {
cell = (CustomCell *)oneCell;
}
}
}
// Customise the labels etc...
return cell;
}
This ensures that your custom cell is loaded directly from its own nib, allowing you to visually lay out any views or labels. The text for these labels can then be set once the appropriate cell has been dequeued/created.
In your code, your 'custom' cell is just a plain UITableViewCell. To customise the cell using interface builder, you need to create your own custom subclass of this.
EDIT
For a custom cell that uses only a nib (and not a custom subclass), change the above code example to cast the cell to a plain UITableViewCell, i.e. change CustomCell to UITableViewCell. In Interface Builder assign each of your cell's custom views (labels etc) with a unique tag.
With that in place, the code should look something like this:
#define MyLabelTag 10 // These should match the tags
#define MyViewTag 11 // assigned in Interface Builder.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = @"CustomCellIdentifier"; // Same as you set in your nib
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id oneCell in nib) {
if ([oneObject isKindOfClass:[UITableViewCell class]]) {
cell = (UITableViewCell *)oneCell;
}
}
}
// Get references to the views / labels from the tags.
UILabel *myLabel = (UILabel *)[cell viewWithTag:MyLabelTag];
UIView *myView = (UIView *)[cell viewWithTag:MyViewTag];
// Customise the views / labels...
// ...
return cell;
}
A: What I usually do is put a UIView inside the UITableViewCell, and then put all your labels and other UI stuff in that UIView. If this doesn't work, let me know. I might have another solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check if string contains only combinations of array elements (numbers and words) I've searched for hours and can't find any example of what I'm trying to do. I can't even figure out what php function needs to be used, but I'm thinking probably a regex. I attempted to use in_array and it didn't work. I don't know enough about regexes to even set up a test. Here's the problem... Say my array is:
$sizeopts = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.5',
' Wide', ' Narrow', 'XS', 'Small', 'Medium', 'Large', 'XL');
The textbox name is "size", and I want to only allow combinations of the above to be submitted. Example valid input: "10.5 Wide" or "3XL". Invalid input: "1X" or "2Wide" (missing the space in front of Wide). I have several different size arrays I need to validate. I'm not just using drop-downs because there are two many different possible combinations. Thanks for any help you can offer!
A: Try this:
$valid = preg_match("/[0-9]+(?:\.5)?(?: Wide| Narrow|XS|Small|Medium|Large|XL)/",$input);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should I pass a jQuery or DOM object as arguments? (Performance Question) Which is better performance wise.
foo(this);
function foo(element) {
$(element).index();
}
Or should I do
foo($(this));
function foo($element) {
$element.index();
}
Obviously taking into account that I will be using the argument a fair few times inside the function.
Thanks!
Connor
A: It doesn't matter where you wrap an object on jQuery if you're going to wrap it anyway.
It only matters that you cache the wrapping result and don't wrap it twice.
For that matter the following rules apply to many plugins' code:
1) jQuery vars are all prefixed with $: var $this = $(this)
2) never wrap $-prefixed var in $
3) always cache (save to var) any jQuery-wrapped expression used more than once
4) if the same wrapped object (like var $items = $('ul li');) occurs more than once in several similar functions, move it to the outer scope and rely on closure.
A: If you're writing a function that's going to take one jQuery object as a parameter, you really should consider writing it as a jQuery plugin instead.
jQuery.fn.yourFunction = function(otherArg1, otherArg2, ...) {
// ...
};
Then instead of writing
yourFunction($(whatever));
you can write
$(whatever).yourFunction().someOtherJQueryFunction();
Inside the function, the this value will be the jQuery object itself. A pattern to use for most common DOM-related functions is:
jQuery.fn.yourFunction = function(otherArg1, otherArg2, ...) {
return this.each(function() {
var $element = $(this);
// do stuff ...
});
};
Note that in the outer level of the function, this is not wrapped as $(this) because it's already guaranteed to be a jQuery object. That is not the case in the body of an "each()" function, or anything else like that.
A: If you intend to only pass a single element to the function, then it doesn't really matter. I would design the function parameter depending upon what I was likely to already have handy at the time of calling. If I never had it in a jQuery object already at the time of calling, then I would just pass a DOM element and let the function make it into a jQuery object (if needed). If I always already had it in a jQuery object, then it will perform better to pass that object that I already have rather than extra the DOM element, then make it into another jQuery object inside the function.
If you intend to pass multiple elements to the function, then it's probably easier to just pass a jQuery object because it's a nice convenient wrapper for the multiple objects.
As Pointy said, the most elegant solution is to make your function a plugin and then it will automatically accept lots of different arguments including a selector, a DOM element, a DOM element array or a jQuery object (all handled for you by the jQuery infrastructure).
You will achieve the best performance if you only make the DOM element into a jQuery object once. Passing a DOM or passing a jQuery object as the argument will have the same performance (both are passing a reference to an object). The plug-in idea will actually have slightly worse performance because it is so general purpose and accepts lots of different arguments and thus it has to identify what type of argument was passed. That performance difference is perhaps not noticeable compared to the time that the .index() method takes itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Django: How can I find which of my models refer to a model I'd like to warn or prevent a user from deleting an object instance which is referred to by other instances. Is there a nice way to do this?
One way would be to get a list of models which include the referent and then try reverse look-ups on them. Is there a way to get that list of models? Or is there a better way?
While investigating the collector suggestion, I found some related information and wrote the following which finds the classes which have the referent as a foreign key:
def find_related(cl, app):
"""Find all classes which are related to the class cl (in app) by
having it as a foreign key."""
from django.db import models
all_models = models.get_models()
ci_model = models.get_model(app, cl)
for a_model in all_models:
for f in a_model._meta.fields:
if isinstance(f, ForeignKey) and (f.rel.to == ci_model):
print a_model.__name__
Based on suggestion to use the code in collect:
def find_related(instance):
"""Find all objects which are related to instance."""
for related in instance._meta.get_all_related_objects():
acc_name = related.get_accessor_name()
referers = getattr(instance, acc_name).all()
if referers:
print related
A: Django has something called Collector class. It is used by Django when performing a model deletion. What it does seems like exactly what you want. By calling collect() it finds all the references to the object in the model graph. Additionally it offers a way to delete all the found objects, with a delete() call.
That said I've never used this class myself, I just know it exists. The API is somewhat convoluted, but if you're willing to dig into the internals of Django a little bit, it might save you a lot of coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Is it possible to stub a method in a parent class so that all subclass instances are stubbed in rspec? Given a parent class Fruit and its subclasses Apple and Banana, is it possible to stub the method foo defined in Fruit, so that any calls to method foo on any instances of Apple and Banana are stubbed?
class Fruit
def foo
puts "some magic in Fruit"
end
end
class Banana < Fruit
...
end
class Apple < Fruit
...
end
Fruit.any_instance.stubs(:foo) did not work and it looks like it only stubs for instances of Fruit. Is there a simple way to achieve this other than calling stubs for every subclasses?
Found this link raising the similar question but it looks like it has not been answered yet.
http://groups.google.com/group/mocha-developer/browse_thread/thread/99981af7c86dad5e
A: This probably isn't the cleanest solution but it works:
Fruit.subclasses.each{|c| c.any_instance.stubs(:foo)}
A: If your subclasses have subclasses, you may have to traverse them all recursively. I did something like this:
def stub_subclasses(clazz)
clazz.any_instance.stubs(:foo).returns(false)
clazz.subclasses.each do |c|
stub_subclasses(c)
end
end
stub_subclasses(Fruit)
A: UPDATE of @weexpectedTHIS answer for Rspec 3.6:
Fruit.subclasses.each do |klass|
allow_any_instance_of(klass).to receive(:foo).and_return(<return_value>)
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Order of calling constructors/destructors in inheritance A little question about creating objects. Say I have these two classes:
struct A{
A(){cout << "A() C-tor" << endl;}
~A(){cout << "~A() D-tor" << endl;}
};
struct B : public A{
B(){cout << "B() C-tor" << endl;}
~B(){cout << "~B() D-tor" << endl;}
A a;
};
and in main I create an instance of B:
int main(){
B b;
}
Note that B derives from A and also has a field of type A.
I am trying to figure out the rules. I know that when constructing an object first calls its parent constructor, and vice versa when destructing.
What about fields (A a; in this case)? When B is created, when will it call A's constructor? I haven't defined an initialization list, is there some kind of a default list? And if there's no default list? And the same question about destructing.
A: *
*Construction always starts with the base class. If there are multiple base classes then, construction starts with the left most base. (side note: If there is a virtual inheritance then it's given higher preference).
*Then the member fields are constructed. They are initialized in the
order they are declared
*Finally, the class itself is constructed
*The order of the destructor is exactly the reverse
Irrespective of the initializer list, the call order will be like this:
*
*Base class A's constructor
*class B's field named a (of type class A) will be constructed
*Derived class B's constructor
A: Base classes are always constructed before data members. Data members are constructed in the order that they are declared in the class. This order has nothing to do with the initialization list. When a data member is being initialized, it will look through your initialization list for the parameters, and call the default constructor if there is no match. Destructors for data members are always called in the reverse order.
A: Base class constructor always executes first.so when you write a statement B b; the constructor of A is called first and then the B class constructor.therefore the output from the constructors will be in a sequence as follows:
A() C-tor
A() C-tor
B() C-tor
A: Assuming there is not virtual/multiple inheritance (that complicates things quite a bit) then the rules are simple:
*
*The object memory is allocated
*The constructor of base classes are executed, ending with most derived
*The member initialization is executed
*The object becomes a true instance of its class
*Constructor code is executed
One important thing to remember is that until step 4 the object is not yet an instance of its class, becuse it gains this title only after the execution of the constructor begins. This means that if there is an exception thrown during the constructor of a member the destructor of the object is not executed, but only already constructed parts (e.g. members or base classes) will be destroyed. This also means that if in the constructor of a member or of a base class you call any virtual member function of the object the implementation called will be the base one, not the derived one.
Another important thing to remember is that member listed in the initialization list will be constructed in the order they are declared in the class, NOT in the order they appear in the initialization list (luckily enough most decent compilers will issue a warning if you list members in a different order from the class declaration).
Note also that even if during the execution of constructor code the this object already gained its final class (e.g. in respect to virtual dispatch) the destructor of the class is NOT going to be called unless the constructor completes its execution. Only when the constructor completes execution the object instance is a real first class citizen among instances... before that point is only a "wanna-be instance" (despite having the correct class).
Destruction happens in the exact reverse order: first the object destructor is executed, then it loses its class (i.e. from this point on the object is considered a base object) then all members are destroyed in reverse declaration order and finally the base class destruction process is executed up to the most abstract parent. As for the constructor if you call any virtual member function of the object (either directly or indirectly) in a base or member destructor the implementation executed will be the parent one because the object lost its class title when the class destructor completed.
A: #include<iostream>
class A
{
public:
A(int n=2): m_i(n)
{
// std::cout<<"Base Constructed with m_i "<<m_i<<std::endl;
}
~A()
{
// std::cout<<"Base Destructed with m_i"<<m_i<<std::endl;
std::cout<<m_i;
}
protected:
int m_i;
};
class B: public A
{
public:
B(int n ): m_a1(m_i + 1), m_a2(n)
{
//std::cout<<"Derived Constructed with m_i "<<m_i<<std::endl;
}
~B()
{
// std::cout<<"Derived Destructed with m_i"<<m_i<<std::endl;
std::cout<<m_i;//2
--m_i;
}
private:
A m_a1;//3
A m_a2;//5
};
int main()
{
{ B b(5);}
std::cout <<std::endl;
return 0;
}
The answer in this case is 2531. How constructor are called here:
*
*B::A(int n=2) constructor is called
*B::B(5) constructor is called
*B.m_A1::A(3) is called
*B.m_A2::A(5) is called
The same-way Destructor is called:
*
*B::~B() is called. i.e m_i = 2, which decrement m_i to 1 in A.
*B.m_A2::~A() is called. m_i = 5
*B.m_A1::~A() is called. m_i = 3
4 B::~A() is called., m_i = 1
In this example, construction of m_A1 & m_A2 is irrelevant of order of initialization list order but their declaration order.
A: Output from the modified code is:
A() C-tor
A() C-tor
B() C-tor
~B() D-tor
~A() D-tor
~A() D-tor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: How do I paginate my custom query? I have a custom query like this
posts_per_page=5&category_name=space
and I am getting the results just fine...
But i want to paginate the result, So clicking the "next 5" will show other old 5 posts...
How can I do this?
Help me please
A: There are two parts to this. First, you need to let the query know that it's paged:
<?php
// This sets the page to 1 if the $paged global is empty
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wp_query = new WP_Query('posts_per_page=5&category_name=space&paged=' . $paged);
?>
Then you need to add pagination links at the bottom of the current page's template:
<?php if ($wp_query->max_num_pages > 1): ?>
<div id="nav-below" class="navigation">
<div class="nav-previous"><?php next_posts_link('← Older posts'); ?></div>
<div class="nav-next"><?php previous_posts_link('Newer posts →'); ?></div>
</div>
<?php endif; ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to link to a wordpress installation's latest articles from a rails app? I am creating a rails app and would like to incorporate a wordpress blog with it.
I have one area of my app that has recent stories. I would like to have it link to my blog and whenever I add a new story on my blog, the story will appear on my site in the area.
Are there any wordpress plugins that do that already, or would it be hard to create something like that since wordpress is PHP and the site is ruby on rails?
A: You cannot use a Wordpress plugin in a rails application as-is, but you can certainly have a section of your website that will be generated by Wordpress instead of rails. This blog post will help you with that.
To show the latest articles from the blog, you could fetch the RSS feed of the wordpress installation and display it in your rails application. This question will be a good start if you're going this way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i create a contact view interface in android? How can i create a view like Contact book in android phones. Alphabets list on one side and while i tap on any alphabet it should go to the contacts of that particular alphabet. Any built in mechanism to make that?
A: There is no built-in support from Android but you can do the same.
See this link sideindex
Hope this helps..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Two Tables With Effective Dates In Which Data Can Vary Independently I am developing a database in MS Access 2010. I have two tables, one for Deals (tblDeals), and one for the Deal Items (tblDealItems).
I need to track the history for the data in these tables, so I am using a DateEffective field and DateEnd field in each of them.
The problem is that the data in each of the two tables can vary independently on different dates, which makes it difficult (impossible for me, actually) to return a recordset which has the true history of the series of events which occur during the deal.
The tables have the following data for one particular deal, "Deal 3":
tblDeals:
DealID DealName AssetClassID DateEffective DateEnd
------ -------- ------------ ------------- -------
3 Deal 3 3 1 Jan 2010 1 Jul 2011
3 Deal 3 2 1 Jul 2011 1 Oct 2011
3 Deal 3 1 1 Oct 2011
tblDealItems:
DealItemID DealID CategoryID ParticipantID Amount DateEffective DateEnd
---------- ------ ---------- ------------- ------ ------------- -------
13 3 3 2 1500 1 Jan 2010 1 Jun 2011
13 3 1 2 1500 1 Jun 2011 6 Jun 2011
13 3 1 2 6000 6 Jun 2011 1 Sep 2011
13 3 3 2 6000 1 Sep 2011
So the actual history of the Deal is this (created manually - this (with the exception of the "Description" column - which is there so it is obvious what has changed in each row) is what I would like to return):
Date (Description) DealID DealName AssetClassID CategoryID ParticipantID Amount
---------- --------------------- ------ -------- ------------ ---------- ------------- ------
1 Jan 2010 (Deal 3 Created) 3 Deal 3 3 3 2 1500
1 Jun 2011 (Category Changed) 3 Deal 3 3 1 2 1500
6 Jun 2011 (Amount Changed) 3 Deal 3 3 1 2 6000
1 Jul 2011 (Asset Class Changed) 3 Deal 3 2 1 2 6000
1 Sep 2011 (Category Changed) 3 Deal 3 2 3 2 6000
1 Oct 2011 (Asset Class Changed) 3 Deal 3 1 3 2 6000
Obviously, if I join the two tables on their shared key, I get a table with twelve rows (3 * 4) instead of the six rows which describe the history.
I know that I need to be able to join the tables together in some way so that I can generate the true history of the deal, but I just don't know how! (I'm really an Excel guy, not a SQL one!)
I think I have worked out exactly what is required to solve the problem specified above:
For each date in qryDates, I need to find the largest tblDeals.DateEffective which is less than or equal to that date and the largest tblDealItems.DateEffective which is less than or equal to that date.
I the need to return the row from a query joining tblDeals and tblDealItems which has those two exact dates.
Any help gratefully received.
A: I'm omitting 'Description' for the moment because it adds quite a bit of complexity (and might be better suited to a report anyhow):
First
CREATE VIEW qryDates
AS
SELECT DISTINCT T1.DealID,
T1.DateEffective AS tblDeals_DateEffective,
(
SELECT MAX(T2.DateEffective)
FROM tblDealItems AS T2
WHERE T1.DealID = T2.DealID
AND T2.DateEffective <= T1.DateEffective
) AS tblDealItems_DateEffective
FROM tblDeals AS T1;
Second:
CREATE VIEW qryDates2
AS
SELECT DISTINCT T2.DealID,
T2.DateEffective AS tblDealItems_DateEffective,
(
SELECT MAX(T1.DateEffective)
FROM tblDeals AS T1
WHERE T1.DealID = T2.DealID
AND T1.DateEffective <= T2.DateEffective
) AS tblDeals_DateEffective
FROM tblDealItems AS T2
Then
SELECT T2.DateEffective AS [Date], '' AS Description,
T1.DealName, T1.AssetClassID,
T2.CategoryID, T2.ParticipantID, T2.Amount
FROM (
tblDeals AS T1
INNER JOIN
qryDates2 AS Q2
ON T1.DateEffective = Q2.tblDeals_DateEffective
AND T1.DealID = Q2.DealID
)
INNER JOIN tblDealItems AS T2
ON T2.DateEffective = Q2.tblDealItems_DateEffective
AND T2.DealID = Q2.DealID
UNION
SELECT T1.DateEffective AS [Date], '' AS Description,
T1.DealName, T1.AssetClassID,
T2.CategoryID, T2.ParticipantID, T2.Amount
FROM (
tblDeals AS T1
INNER JOIN
qryDates AS Q1
ON T1.DateEffective = Q1.tblDeals_DateEffective
AND T1.DealID = Q1.DealID
)
INNER JOIN tblDealItems AS T2
ON T2.DateEffective = Q1.tblDealItems_DateEffective
AND T2.DealID = Q1.DealID;
The quality of the data in your sample is good: in reality the joins may need to be outer to compensate for bad data. Note your tblDeals table is not fully normlized (hint: DealName is repeated).
Note:
Obviously, if I join the two tables on their shared key, I get a table
with twelve rows (3 * 4) instead of the six rows which describe the
history.
you can get the set of unique event dates for each deal using UNION:
SELECT DealID, DateEffective
FROM tblDeals
UNION
SELECT DealID, DateEffective
FROM tblDealItems;
Here's a repro: creates a new mdb in temp folder, creates tables and views (note CREATE VIEW does work in Access ;) , adds test data (as per question) then executes query and shows results in a messagebox; no references required, just copy+paste into any VBA module e.g. use a new Excel workbook :)
Sub NickNick2()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = "CREATE TABLE tblDeals (DealID INT, DealName VARCHAR(100), AssetClassID INT, DateEffective DATETIME, DateEnd DATETIME);"
.Execute Sql
Sql = "CREATE TABLE tblDealItems (DealItemID INT, DealID INT, CategoryID INT, ParticipantID INT, Amount INT, DateEffective DATETIME, DateEnd DATETIME);"
.Execute Sql
Sql = _
" CREATE VIEW qryDates " & _
" AS " & _
" SELECT DISTINCT T1.DealID, " & _
" T1.DateEffective AS tblDeals_DateEffective, " & _
" ( " & _
" SELECT MAX(T2.DateEffective) " & _
" FROM tblDealItems AS T2 " & _
" WHERE T1.DealID = T2.DealID " & _
" AND T2.DateEffective <= T1.DateEffective " & _
" ) AS tblDealItems_DateEffective " & _
" FROM tblDeals AS T1;"
.Execute Sql
Sql = _
" CREATE VIEW qryDates2 " & _
" AS " & _
" SELECT DISTINCT T2.DealID, " & _
" T2.DateEffective AS tblDealItems_DateEffective, " & _
" ( " & _
" SELECT MAX(T1.DateEffective) " & _
" FROM tblDeals AS T1 " & _
" WHERE T1.DealID = T2.DealID " & _
" AND T1.DateEffective <= T2.DateEffective " & _
" ) AS tblDeals_DateEffective " & _
" FROM tblDealItems AS T2;"
.Execute Sql
Sql = _
"INSERT INTO tblDeals VALUES (3, 'Deal 3', 3, '2010-01-01 00:00:00', '2011-07-01 00:00:00');"
.Execute Sql
Sql = _
"INSERT INTO tblDeals VALUES (3, 'Deal 3', 2, '2011-07-01 00:00:00', '2011-10-01 00:00:00');"
.Execute Sql
Sql = _
"INSERT INTO tblDeals VALUES (3, 'Deal 3', 1, '2011-10-01 00:00:00', NULL);"
.Execute Sql
Sql = _
"INSERT INTO tblDealItems VALUES (13, 3, 3, 2, 1500, '2010-01-01 00:00:00', '2011-06-01 00:00:00');"
.Execute Sql
Sql = _
"INSERT INTO tblDealItems VALUES (13, 3, 1, 2, 1500, '2011-06-01 00:00:00', '2011-06-06 00:00:00');"
.Execute Sql
Sql = _
"INSERT INTO tblDealItems VALUES (13, 3, 1, 2, 6000, '2011-06-06 00:00:00', '2011-09-01 00:00:00');"
.Execute Sql
Sql = _
"INSERT INTO tblDealItems VALUES (13, 3, 3, 2, 6000, '2011-09-01 00:00:00', NULL);"
.Execute Sql
Sql = _
"SELECT T2.DateEffective AS [Date], '' AS Description, " & _
" T1.DealName, T1.AssetClassID, " & _
" T2.CategoryID, T2.ParticipantID, T2.Amount " & _
" FROM ( " & _
" tblDeals AS T1 " & _
" INNER JOIN " & _
" qryDates2 AS Q2 " & _
" ON T1.DateEffective = Q2.tblDeals_DateEffective " & _
" AND T1.DealID = Q2.DealID " & _
" ) " & _
" INNER JOIN tblDealItems AS T2 " & _
" ON T2.DateEffective = Q2.tblDealItems_DateEffective " & _
" AND T2.DealID = Q2.DealID " & _
"UNION " & _
"SELECT T1.DateEffective AS [Date], '' AS Description, " & _
" T1.DealName, T1.AssetClassID, " & _
" T2.CategoryID, T2.ParticipantID, T2.Amount " & _
" FROM ( " & _
" tblDeals AS T1 " & _
" INNER JOIN " & _
" qryDates AS Q1 " & _
" ON T1.DateEffective = Q1.tblDeals_DateEffective " & _
" AND T1.DealID = Q1.DealID " & _
" ) "
Sql = Sql & _
" INNER JOIN tblDealItems AS T2 " & _
" ON T2.DateEffective = Q1.tblDealItems_DateEffective " & _
" AND T2.DealID = Q1.DealID " & _
" ORDER " & _
" BY 1;"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString
End With
Set .ActiveConnection = Nothing
End With
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: good macro practice in c what is the better way to use macro and why
1)
CHECK(foo());
#define CHECK(foo) do{ \
UCHAR status = foo; \
if(0 != status) \
// do some stuff \
return status; \
}while(0)
or
2)
UCHAR status = foo();
CHECK(status);
#define CHECK(status) do{ \
if(0 != status) \
// do some stuff \
return status; \
}while(0)
edited
thank You for all of You guys, a lot of people say that it is not good to use such piece of the code, but I have a lot of such pieces in my code (which I didn't write, only modify), what can You suggest?
A: I'd say the first one, since it takes care of avoiding multiple evaluation of foo, and who uses it doesn't need to remember to create the extra variable.
Still, personally I don't like macros that alter the execution flow like that, a programmer first seeing the codebase can easily miss a return point of the function.
A: Option 1 is easier to use since there is no need for the caller to worry about multiple evaluations of foo(). Option 1 also keeps the scope of the status variable as small as possible. Option 2 leaks the status variable into the scope of the caller.
Option 3 which doesn't use a macro at all is even better!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: choice mode multiple modal + onLongClickListener I started implementing drag and drop into my application but got stuck right away. The onLongClickListener wich triggers the drag and drop operation does not seem to work well together with the CHOICE_MODE_MULTIPLE_MODAL flag.
This kind of interaction is present in the gmail app for honeycomb where users can drag list items as well as selecting multiple list items and triggering the action mode.
So the question is, what is to be done to get this kind of interaction to work?
thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gson (Json) parse exception I'm getting an exception while parsing a JSON with Gson.
The following is the exception :
com.google.gson.JsonParseException: The JsonDeserializer StringTypeAdapter failed to deserialize json object {"CGLIB$BOUND":true,"CGLIB$CONSTRUCTED":true,"CGLIB$CALLBACK_0":{"interfaces":[{}],"constructed":true,"persistentClass":{},"getIdentifierMethod":{"clazz":{},"slot":0,"name":"getmId","returnType":{},"parameterTypes":[],"exceptionTypes":[],"modifiers":1,"annotations":[0,3,0,67,0,0,0,68,0,0,0,69,0,1,0,70,115,0,71],"root":{"clazz":{},"slot":0,"name":"getmId","returnType":{},"parameterTypes":[],"exceptionTypes":[],"modifiers":1,"annotations":[0,3,0,67,0,0,0,68,0,0,0,69,0,1,0,70,115,0,71],"override":false},"override":false},"setIdentifierMethod":{"clazz":{},"slot":1,"name":"setmId","returnType":{},"parameterTypes":[{}],"exceptionTypes":[],"modifiers":1,"root":{"clazz":{},"slot":1,"name":"setmId","returnType":{},"parameterTypes":[{}],"exceptionTypes":[],"modifiers":1,"override":false},"override":false},"overridesEquals":false,"initialized":false,"entityName":"com.domain.Hotel","id":1,"unwrap":false},"mId":0,"mHotelLatitude":0.0,"mHotelLongitude":0.0,"mHotelRating":0.0,"mHotelAvgPrice":0.0} given the type class java.lang.String
JSON:
{
"CGLIB$BOUND": true,
"CGLIB$CONSTRUCTED": true,
"CGLIB$CALLBACK_0": {
"interfaces": [
{}
],
"constructed": true,
"persistentClass": {},
"getIdentifierMethod": {
"clazz": {},
"slot": 0,
"name": "getmId",
"returnType": {},
"parameterTypes": [],
"exceptionTypes": [],
"modifiers": 1,
"annotations": [
0,
3,
0,
67,
0,
0,
0,
68,
0,
0,
0,
69,
0,
1,
0,
70,
115,
0,
71
],
"root": {
"clazz": {},
"slot": 0,
"name": "getmId",
"returnType": {},
"parameterTypes": [],
"exceptionTypes": [],
"modifiers": 1,
"annotations": [
0,
3,
0,
67,
0,
0,
0,
68,
0,
0,
0,
69,
0,
1,
0,
70,
115,
0,
71
],
"override": false
},
"override": false
},
"setIdentifierMethod": {
"clazz": {},
"slot": 1,
"name": "setmId",
"returnType": {},
"parameterTypes": [
{}
],
"exceptionTypes": [],
"modifiers": 1,
"root": {
"clazz": {},
"slot": 1,
"name": "setmId",
"returnType": {},
"parameterTypes": [
{}
],
"exceptionTypes": [],
"modifiers": 1,
"override": false
},
"override": false
},
"overridesEquals": false,
"initialized": false,
"entityName": "com.domain.Hotel",
"id": 1,
"unwrap": false
},
"mId": 0,
"mHotelLatitude": 0,
"mHotelLongitude": 0,
"mHotelRating": 0,
"mHotelAvgPrice": 0
}
Does anybody have an idea about why this exception would come?
Regards
A: I can get this JSON to parse in Gson. The error above is generated when you have incorrectly mapped a JSON property type to Java member type in your POJO (an array type in JSON is declared as a String type in your POJO for example).
The error is a little curious to me as Gson will usually print out the JSON from the property that couldn't be mapped. In your case that would be CGLIB$BOUND which is a boolean, but Gson behaves nicely in this case, giving you a String value "true". We can more accurately identify your problem if you provide the POJO you are trying to deserialise to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using RGB colors in Assembly Language I am Plotting a pixel on the screen from the following code using Assembly Language of x86 processor in C++. I dont want to use any function or method from C++ as I use this code for the boot loader program. here is the code:
/**********************************
* Mainvainsoft 2011. *
* Writen By: Farid-ur-Rahman *
* On: 24 Sep At: 1:34 AM. *
**********************************/
#include <conio.h>
void main ()
{
// Setting Video mode to 256 colours at 320 X 200
_asm {
mov ah , 0x00 // Setting Video mode or Clear Screen
mov al , 0x13 // Setting Video mode to 256 Color Mode
int 0x10 // Call the Registor
mov ah , 0x0c // Plot the Pixel
mov al , 4 // Color
mov cx , 160 // X-Axis
mov dx , 100 // Y-Axis
int 0x10 // Call the Registor
}
getch(); // Wait for the key press
}
I want to use the RGB colors to display on the pixel.
A: Mode 13h uses a palette with 256 18-bit RGB (6 bits for each) entries. So you can set for example entry 4 to the RGB color you want and the plot the pixel as you are doing with color 4.
See here for an example of how to set a palette entry. After setting the video mode you can do something like:
// Set entry 4
mov dx, 0x3c8
mov al, 4
out dx, al
inc dx
mov al, Red
out dx, al
mov al, Green
out dx, al
mov al, Blue
out dx, al
// draw pixel
A: In the video mode you're using, VGA mode 0x13, each byte of the framebuffer points into the palette. So if you have 24 bits of RGB color information, you can't write that directly into a pixel, since the pixels just contain palette indices.
You can of course quantize your colors into the palette, but that can be quite complicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Design DAL/DataSet/Business Objects I am currently designing an application (.Net WinForms) that needs to access a database (SQL Server).
Using the datasource wizard, Visual Studio automatically creates the dataset, tables and classes for rows:
For example if I have the Customers table the wizard will create “CustomersRow” class that inherits from Global.System.Data.DataRow with the corresponding fields as properties.
In my application I need to implement other methods and attributes for the Customers class.
How to deal with these generated classes, modify them by adding methods.. or ignoring them and implement my own business classes?
A second question:
How to populate my objects (eg list of customers?)
Do you suggest using datatables / dataset and their methods or build my own data access layer and I meet the client list (of customers)?
I found some patterns when searching the net but it is not precise.
Thanks
A: I would say design pattern depends entirely on the scale of the project and how "future proof" you want it to be. How many users would be using the software? Is the data to be accessed by many concurrent users? How "up-to-date" should the data be when accessed by a user?
If it's a small project keep it simple but allow yourself place to modify it without having to change entire application. In bigger projects it's useful to ask above questions before deciding on design pattern.
Regardless of the scale it's useful to create at least following separate layers:
DAL -responsible solely for updating and retrieving data
Business logic - a set of objects and methods that represent the process software is responsible for (only business logic has access to DAL)
UI - serving the purpose of presenting the data to the user and taking user's input based on business logic (UI references BL layer and only through it's rules it can access and modify the data)
This way you can modify any of the layers without affecting the others and as the project grows it can become very useful.
A: I'm new to the design patterns too but i think the best solution would be to put a Business layer on top of your generated classes and DAL. Then in this layer you could implement your custom methods and attributes for your classes, maybe you should consider using POCO objects for that.
A: When it comes to layers and tiers, keep it simple. Some developers get very academic when it comes to business tiers but all they are doing is adding unnecessary complexity (beware architecture astronauts). So my first advice is to keep it simple and easy to maintain for your particular application.
The goal is to hit a balance between maintenance complexity and flexibility. You want your app to have the flexibility to grow without requiring a lot of changes but at the same time, you want to be able to have an application that is simple to understand.
Having at least one layer between your persistence and client is a good thing. This gives you the flexibility of putting a domain and/or service in-between the client and the database. I wouldn't go beyond this unless you are solving a specific problem.
As for loading from your persistence, you can use partial classes to extend the generated persistence classes. This is an easy way to add on additional functionality while keeping the original properties and methods in tact.
If you need to transform persistence objects to domain objects used by the application, I would recommend putting a constructor or static Create method on the domain objects that take a persistence object and then transforms it into a domain object. You can do the same thing going back to persistence.
using MyApp.Domain;
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
public int ID { get; set; }
public static MyApp.Domain.Customer Create( MyApp.Persistence.Customer pcustomer )
{
return new MyApp.Domain.Customer
{
Name = pcustomer.Name,
Address = pcustomer.Address,
ID = pcustomer.ID
}
}
public void Persist( MyApp.Persistence.Customer pcustomer )
{
pcustomer.ID = this.ID;
pcustomer.Name = this.Name;
pcustomer.Address = this.Address;
}
}
Here is what the partial class might look like. The key is to have the namespace of the class the same as the namespace of your generated persistence type.
using MyApp.Persistence;
public partial class Customer
{
public string FormatedAddress
{
// I now have access to all the generated members because
// I'm extending the definition of the generated class
get
{
return string.Format( "{0}\n{1},{2} {3}",
StreetAddress,
City,
State,
ZipCode );
}
}
}
A: look at my other answer here:
MVC3 and Entity Framework
basically MVC, WinForms, WPF or whatever you have as Presentation Layer the layering I described there is still valid.
the real shape of your Data Access Layer could change internally depending on what you use in there, like NHibernate, Entity Framework, no ORM at all but raw/pure SQL access, whatever you do is limited and contained in there and you will have great life if you abstract from that at the most and all your other layers are designed to be independent from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.