text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: getElementsByClassName doesn't work properly at Element nodes
Possible Duplicate:
getElementsByClassName returns [] instead of asynchronous appended node
I face the following problem:
<div class="testA" id="test1">
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</div>
The above written Tree is predefined. I now load a node tree via XMLHttpRequest & Co. that I append into the <div class="testA" id="test1">
When I now try to get the Element <div class="colorSelector" id="0-0"> using getElementById("0-0") I get the expected result. But using getElementsByClassName("colorSelector") returns [].
Did I miss something? Is it probably a leftover of the fact the nodes were of type Element and not HTMLElement?
I don't get it.
EDIT: I used the comments to visualize that the nodes are added later when processing the response
EDIT 2: http://lls-test.de/JS-Library/index.php is what I receive as a response and handle in a script to append the first DIV inside the response tag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tricky associative arrays in CodeIgniter I'm trying to make a bar chart for a mobile devices that submit data. Every minute, each mobile device sends a packet of data to the web server - where it's then stored in a MySQL database. Each mobile device is assigned an IP addresses, and each IP address can send data multiple times a minute (sometimes as many as 10). Here is what an example table would look like:
date_received | bytes | IP address
----------------------------------
1314831600 | 100 | 1482747555
1314831600 | 990 | 1482747555
1314831600 | 074 | 1482747555
1314831660 | 420 | 1482747555
1314831660 | 183 | 1482747555
So you can see that one IP address can submit multiple times a minute over a span of hours (therefore multiple minutes). How would I create an associative array that looked like this:
array
(
1314831600 = array
(
1482747555 => 100,
1482747555 => 990,
1482747555 => 074
);
1314831660 = array
(
1482747555 => 420,
1482747555 => 183
);
);
The first key would be the date_received value, and the the IP addresses which are sent for that time (with their corresponding bytes values). I'm using CodeIgniter and I thought about populating arrays in my foreach database loop, but wasn't quite sure how best to do this. Does anybody have any advice?
N.B: I need to keep database calls to a minimum because some tables contain hundreds of thousands of values.
A: You cannot share array keys like that (ip address) as they will be overwritten. You can do something like:
$packets = array();
while ($row = mysql_fetch_assoc($res)) {
$packets[$row['date_received']][] =
array('ip_address'=>$row['ip_address'],
'bytes'=>$row['bytes']
);
}
Then you can loop through the data with:
foreach ($packets as $date => $info) {
echo "date = $date, ip = $info[ip_address], bytes = $info[bytes]";
}
A: If you rewrite part of your array like this, the problem becomes much easier for you:
array
(
1482747555 => array(100,990,074)
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get db path outside of web app folder on server using Asp.Net I published a web app to a server and I would like to access a database file (.mdb) that is also stored on the server in a different location outside of mine. How can I do this in the web.config file of my Asp.Net app?
<add name="MyOleDbConnection" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source= **{?}** \inventory.mdb"/>
A: I don't believe you can do it from code, using anything like Server.MapPath() - and for good reason. This would allow developers to write apps that take over host operating systems on cloud servers. You're restricted from determining the path of files/folders outside of the control of IIS to prevent directory traversal attacks.
You'll need to ask a SysAdmin, or someone who has access what the path is on that machine. Once you have the full path, you can set the full path in the .config
c:\path\inventory.mdb
instead of
\inventory.mdb
You will also need to make sure that the SysAdmin grants you permissions to access the .mdb.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where could I find UML diagrams of an open source project? I'm going to start a project for my software engineering course, and I have to do a relatively hard one, something like a browser. Of course I'm not going to build a complete browser from scratch in 4 monthes, but in the first phases I have to give my analyze output to the TA. This includes use case diagrams, sequence diagrams and other UML diagrams.
since I've never done a project like this, I'm looking for diagrams of an open source project which I can get some ideas from them. Where could I find such open source projects that give me these diagrams?
A: If you just want to learn how the UML of a project is laid out, then one thing you could do is checkout any open source project written C#/Java/VB, import it to this tool called Altova Umodel. They have free trial version but the software itself is sold commercially.
Hope that helps..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: ListView scroll control - scroll to bottom if user isn't scrolling? I have a .NET 3.5 WinForm that has a ListView with the View set in Details mode. It functions as a scrollable list of status items on a long background task. I have the most recent ListViewItem (status entry) added to the bottom. To assure that it is seen, I ensure the visibility of the new item after adding. This all works fine; the list view automatically scrolls to the bottom to show the most recent item.
private void AddListItem(DateTime timestamp, string message, int index)
{
var listItem = new ListViewItem(timestamp.ToString());
listItem.SubItems.Add(message);
statusList.Items.Insert(index, listItem);
statusList.Items[statusList.Items.Count - 1].EnsureVisible();
}
The problem is if the user is scrolling up to look at older messages, the ListView will be scrolled down to make the new item visible as it comes in. Is there a way to control this behavior to check if the user is interacting with the scrollbar (specifically, if they're holding down the mouse button on the scrollbar)? It is probably also acceptable to detected if the scroll is always at the bottom. if it is not at the bottom, then I would not ensure the visibility of the latest item. Something like:
private void AddListItem(DateTime timestamp, string message, int index)
{
var listItem = new ListViewItem(timestamp.ToString());
listItem.SubItems.Add(message);
statusList.Items.Insert(index, listItem);
if (!statusList.IsScrollbarUserControlled)
{
statusList.Items[statusList.Items.Count - 1].EnsureVisible();
}
}
What's strange is that when the user is holding down the scrollbar "handle" in place, the handle doesn't move (implying that the view is not actually being scrolled down programatically), but in infact is.
Update: Is it possible to detect the position of the scrollbar, i.e., if i'ts at the bottom or not?
A: Two steps to solving this problem:
*
*The WinForms ListView doesn't have a Scrolled event. We'll need to define one.
*Determining when the ListView is idle, and calling EnsureVisible only when it's been idle for awhile.
For the first problem, inherit a new class from ListView, override the Windows message pump, and raise an event when the user scrolls it:
public class MyListView : ListView
{
public event EventHandler<EventArgs> Scrolled;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
const int wm_vscroll = 0x115;
if (m.Msg == wm_vscroll && Scrolled != null)
{
Scrolled(this, new EventArgs());
}
}
}
Now we know when the user scrolls the list view. Your next problem is to determine whether the list view is idle; that is, if the user hasn't scrolled it in awhile.
There are multiple ways to do that. For this purpose, I'm just going to use a time stamp to indicate the last scroll time:
private DateTime lastScrollTime;
...
listView.Scrolled += delegate { lastScrollTime = DateTime.Now };
...
private void AddListItem(DateTime timestamp, string message, int index)
{
var listItem = new ListViewItem(timestamp.ToString());
listItem.SubItems.Add(message);
statusList.Items.Insert(index, listItem);
// Scroll down only if the list view is idle.
var idleTime = TimeSpan.FromSeconds(5);
var isListViewIdle = DateTime.Now.Subtract(this.lastScrollTime) > idleTime;
if (isListViewIdle)
{
statusList.Items[statusList.Items.Count - 1].EnsureVisible();
}
}
A: Compare to, say, SysInternals' ProcMon. Add a checkbox labeled "Auto scroll" so the user can turn it off.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Rails 3.1 adding an object to an array returned by find_by_sql / can't show in erb file I'm porting a php app to rails so I have a set of sql statements that I'm converting to find_by_sql's. I see that it returns a collection of objects of the type that I called on it. What I'd like to do is then iterate through this collection (presumably an array) and add an instance of a specific object like this:
#class is GlobalList
#sql is simplified - really joining across 3 tables
def self.common_items user_ids
items=find_by_sql(["select gl.global_id, count(gl.global_id) as global_count from main_table gl group by global_id"])
#each of these items is a GlobalList and want to add a location to the Array
items.each_with_index do |value,index|
tmp_item=Location.find_by_global_id(value['global_id'])
#not sure if this is possible
items[index]['location']=tmp_item
end
return items
end
controller
#controller
@common_items=GlobalList.common_items user_ids
view
#view code - the third line doesn't work
<% @common_items.each_with_index do |value,key| %>
<%=debug(value.location) %> <!-- works -->
global_id:<%=value.location.global_id %> <!-- ### doesn't work but this is an attribute of this object-->
<% end %>
So I have 3 questions:
1. is items an Array? It says it is via a call to .class but not sure
2. I am able to add location these GlobalList items. However in the view code, I cannot access the attributes of location. How would I access this?
3. I know that this is pretty ugly - is there a better pattern to implement this?
A: I would get any data you need from locations in the sql query, that way you avoid the n+1 problem
@items=find_by_sql(["select locations.foo as location_foo,
gl.global_id as global_id,
count(gl.global_id) as global_count
from main_table gl
inner join locations on locations.global_id = gl.global_id
group by global_id"])
Then in the view:
<% @items.each do |gl| %>
<%= gl.location_foo %> <-- select any fields you want in controller -->
<%= gl.global_count %>
<%= gl.global_id %>
<% end %>
If you want to keep it close to as is, I would:
def self.common_items user_ids
items=find_by_sql(["select gl.global_id, count(gl.global_id) as global_count
from main_table gl group by global_id"])
items.map do |value|
[value, Location.find_by_global_id(value.global_id)]
end
end
Then in the view:
<% @common_items.each do |value,location| %>
<%=debug(location) %>
global_id:<%=value.global_id %>
<% end %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Version Control as a Web Application Couldnt find a Version Control system that I could simply install as a web application on a shared hosting provider. I wish for a simple REST based web application in PHP/Ruby with a backend of MySQL (or something).
Simply use GET and PUT to check-in check-out files.
*
*http://myServer/Repository/Files
*http://myServer/Repository/Revisions
*http://myServer/Repository/Users
This may be all I would need.
Database Backend wise 4/5 tables
Users
Repositories
Folders
Files
FileVersions
Revisions
Your thoughts?
A: I don't think such a thing exists. At least not in a form that is installable on PHP or Ruby shared hosting. (I researched this at one point pretty well.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C - Strange Prototype Argument What's going on in this function prototype? Obviously the void parameter with some sort of typecasting is confusing...
int *my_func(my_struct *m, void (*m_op)(my_struct *v, void arg));
A: The second argument to the function my_func is a pointer to a function that returns no value (void), but which takes two arguments, a my_struct pointer and ... and (an invalid) void. The latter should probably be void *arg; you cannot have a variable or argument of type void. As it stands, the code should not compile.
A: This prototype declares a function, my_func that returns int *. It takes two arguments, the first being of type my_struct * and the second of the strange type void (*)(my_struct *, void). This means that the second argument is a pointer to a function that returns void and takes 2 arguments itself, a pointer to my_struct and void (I assume that was a typo and it takes a void *).
A: My suggestion - always try to split declarations into smaller ones - in that case code will be more readable. In this case you could re-write code as:
typedef struct {} my_struct;
typedef void (* m_op_function)(my_struct * v, void * arg);
int * my_func(my_struct * m, m_op_function f);
And as everybody said- it's almost 99,99% typo here regarding second parameter to m_op_function- it is possible void* - so that you can pass any pointer to it - be it (char*), (int*), (my_struct*), or anything else. Simply just cast pointer.
A: This little article explains how to parse C declarations in a spiral-like motion. Constructing is done in the reverse.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Request dialog multiple friends I saw this on "Sims Social" , wondering how they do that
:
screenshot
A: It's just the standard app request dialog. You can read about it in the developer documentation for dialogs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: return null with query string whtn i use ajax-jquery this is my jquery code:
<script type="text/javascript">
$(document).ready(function () {
$("a").hover(function () {
$.ajax({
type: "POST",
url:"Dbread.aspx",
data: "name=salam",
success: function (result) {
alert(result);
} //end of success
});
}, function () {
});
});
</script>
in Dbread.aspx
i wrote:
string str= Request.QueryString["name"];
Response.Write(str);
but the problem is that query string result is null all times!!!
what is problem?
A: This is the best practice.
$.ajax({
type: "POST",
url:"Dbread.aspx",
data: {name:"salam",qs:"bla"}, //also i appended the qs parameter
success: function (result) {
alert(result);
} //end of success
});
A: You are using method "POST" and not providing actual query string. Query string is created only for "GET" method and should be the part of the URL, so the fix would be:
$.ajax({
type: "GET",
url:"Dbread.aspx?name=salam",
...
or
$.ajax({
type: "GET",
url:"Dbread.aspx",
data: "name=salam",
...
A: extra space can cause this problem
PrintPreview.NavigateUrl = "~/ReportViewer.aspx?ReviewID=" + Session["ArticleID"].ToString() + " & User=" + (Session["ID"]).ToString();
above is not working it returns null in ID
but in the below example it works fine just change of space character
PrintPreview.NavigateUrl = "~/ReportViewer.aspx?ReviewID= " + Session["ArticleID"].ToString() + "&User=" + (Session["ID"]).ToString();
http://afzal-gujrat.blogspot.com/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to override style inheritance? Q: How can I override the font size for custom table classes so that they don't pick up the inherited value?
table {
font-size: 1.09em;
/* other stuff... */
}
table.order
{
font-size: 0.75 em; /* font isn't getting set....it's picking up the 1.09em from the above table */
}
A: You've got a space between 0.75 and em. Remove it and the style should be set correctly (assuming the table actually has a class of order).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create custom data types in SQL Server 2008? I'm trying to create an unsigned short data type in SQL Server, but so far all I've managed is to get it to not allow any negative values, which wastes half of my storage space. There should be some way to create a custom data type where I manage it myself. I'd like to be able to tell the system that the data type has two bytes, and to read the value back in a certain way so that it reads it as a ushort. Any ideas?
Final Solution:
Ok, Nathan's answer below helped me to find a workable solution. So when I store my unsigned short value to the database, I just need to cast it as a signed short. The first half of the values will be correct. If the value is negative, I just need to add 65536 to the number. The final select case looks like:
SELECT case when i >= 0 then i else 65536+i end
FROM MyDatabase.dbo.testDB
This will properly display my incorrectly cast unsigned short. Thanks for the help.
A: Edit: Upon re-read I see you're looking to emulate an unsigned short (0 to 65,535) in a 2 byte datatype. I'm not seeing a way given the native types in MSSQL, unless you went with the smallint and performed the math yourself.
Is this just an exercise or are you hyper focused on storage space? Space is cheap!
edit: to show example of smallint adjusted:
drop table dbo.yak
create table dbo.yak (i smallint identity(-32768, 1), n varchar(1));
go
insert into dbo.yak(n)
values('a'),('b'),('c');
go
select i, (i+32768)+1, n
from dbo.Yak
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where can I download AjaxControlToolkit 4.1.50927? I was lead here:
http://nuget.org/List/Packages/AjaxControlToolkit/4.1.50927
but I can find no download links. Where can I download this? I've already downloaded NuGet. Now what?
A: Nevermind. Once you install NuGet and it becomes integrated into VS2010, you right-click on the project and click Manage NuGet Packages. You then have to search for what you want and install it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implementing SkipListener to write invalid records to a flat file I am working on setting a spring batch job that does the conventional READ > PROCESS > WRITE operation. However, I am trying to implement a listener which would capture records that are conisdered invalid during the PROCESS phase and write it out to an error log file.
My listener class uses an instance of FlatFileItemWriter to write the data. However, spring-batch is not instantiating the writer instance properly.
My listener class looks like this:
public class DTOProcessorListener extends SkipListenerSupport<AttributeReportGenerationDTO, AttributeValue> {
private static final Logger LOGGER = LoggerFactory.getLogger(DTOProcessorListener.class);
private FlatFileItemWriter<AttributeReportGenerationDTO> flatFileItemWriter;
@Override
public void onSkipInProcess(AttributeReportGenerationDTO item, Throwable t) {
try {
LOGGER.error("Record not processed for attribute value with ID : " + item.getAttributeValueId());
List<AttributeReportGenerationDTO> list = new ArrayList<AttributeReportGenerationDTO>();
list.add(item);
flatFileItemWriter.write(list);
} catch (Exception e) {
LOGGER.error("Unable to write to the error output file", e);
}
}
/**
* @param flatFileItemWriter
* the flatFileItemWriter to set
*/
public void setFlatFileItemWriter(FlatFileItemWriter<AttributeReportGenerationDTO> flatFileItemWriter) {
this.flatFileItemWriter = flatFileItemWriter;
}
}
and my job configuration XML looks like this:
<bean id="skipListener" class="something.DTOProcessorListener" scope="step">
<property name="flatFileItemWriter">
<bean id="errorItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="resource" value="file:#{jobParameters['error.filename']}" />
<property name="appendAllowed" value="true" />
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="fieldExtractor">
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names"
value="productTypeId, productTypeName, productId, productName, skuId, skuName, attributeValueId, attributeName, attributeValue, attributeType, nonEditableValueCheckSum, editableValueCheckSum" />
</bean>
</property>
</bean>
</property>
<property name="headerCallback">
<bean class="something.CsvHeaderImplementation">
<property name="headerString"
value="Product Type ID,Product Type,Product ID,Product Name,Sku ID,Sku Name,Attribute Value ID,Attribute Name,Attribute Value,Attribute Type,Check Sum 1,Check Sum 2" />
</bean>
</property>
</bean>
</property>
</bean>
I get the error
org.springframework.batch.item.WriterNotOpenException: Writer must be open before it can be written to
I am unable to set a stream entry in the job config as the bean for FlatFileItemWriter is internally specified (for the listener). If I create abean outside of the listener and refer to it, its returning a proxy instance of the FlatFileItemWriterClass.
Has anyone successfully wired up a writer to a flat file in the listener?
Thanks for the help
A: Well why don't you use the writer as a normal bean ? You could register it as a stream and to get around the step proxy you could use the PropertPlaceholderConfigurer
i created a working example under my github repo, but i think spring batch could need an improvement here, it should be easier to implement error-item logging
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Real-life examples of Generic Methods in .NET and ASP. NET MVC Could give me some reasonable real-life examples of
Generic Methods in .NET for some simple desktop application?
Which the scenarios are there available?
Thank you!
A: The most commonly used generic methods are probably the extension methods in Enumerable and Queryable, i.e. the ones forming LINQ.
To go back a bit earlier, List<T>.ConvertAll<TOutput> is a good example of converting a list of one type (T) to another type (TOutput). In this case the type is generic (the T of List<T> and the method is also generic (in TOutput).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Remove ThreadContext Properties I have set the ThreadContext.Properties and need to update its value during the life-cycle of my code. In the past I have used log4j MDC and had to:
MDC.remove(TRACKING);
and then add another value by:
MDC.put(TRACKING, trackingIdStr);
Now that I am using Log4Net, our app uses Properties:
log4net.ThreadContext.Properties["TrackingId"] = tracker;
Question: How do I remove the previous value and add a new value? Is it as easy as just:
log4net.ThreadContext.Properties["TrackingId"] = tracker2;
A: Yes, it is that easy. You can reassign as you have shown in your question or you can remove the value altogether when you are finished with it.
//set
ThreadContext.Properties["TrackingId"] = tracker1;
//reset
ThreadContext.Properties["TrackingId"] = tracker2;
//completely remove
ThreadContext.Properties.Remove("TrackingId");
If you want your context properties to be in effect for a specific section of code (via using) then you can try ThreadContext.Stacks:
using(ThreadContext.Stacks["TrackingId"].Push("hello"))
{
//messages logged here will be tagged with TrackingId="hello"
}
//messages logged here will not be tagged with TrackingId="hello"
A: Maybe this does not directly answer your question, but in your situation you might consider to use calculated context values. This is explained nicely here:
Log4Net Tutorial pt 6: Log Event Context
(scroll down a bit)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: mongodb and sql for document versioning system I'm a computer engineer student and i've got a basically simple assignment but i'd like to make it a little more interesting :). Basically I have to create a simple multiuser, online document versioning system using Java or .NET. Because I'm more a .NET guy I'm gonna use ASP.NET or Silverlight (it's not yet decided).
Anyway the intersting part: I want to use MongoDB to store the documents (they can be virtually anything, video, audio, simple MSOffice files, plain text), each version of them and the related metadata (which library, folder they're in etc). I'd like to put anything else, like users, permissions etc.(the specs are not yet completed) in to an ordinary relational database. The question is what do you think about this? Do you think this makes any sense or I'm just trying to over complicate the whole thing? Would it be simpler to use only mongodb for everything or leave the nosql thingy entirely out of it? Is there any conventions for this kind of stuff? :)
BTW. under any other circumstences I'd use some free, battle tested solution for doc versioning, but I have to design and implement this myself, and I'm trying to do it at least a little unconventionally :).
Thanks for every comment:), any help appreciated:)
Greets
A: Doing things unconventionnaly is usually a good way to discover new ways (better ways ?) so it's a good idea.
Using mongodb is a good idea too because of the schemaless property.
USing a relationa database for storing extra information is quite weird and will add more complexity without any advantage (IMO)
A: If you were using something like Mongoid on Rails, this would be trivial. http://mongoid.org/docs/extras.html Look for Versioning. The ODM has it built in for you. I've yet to use Mongo in the .NET world, it's always been something like Raven, so I'm not sure if the libraries for it easily work like Mongoid does.
Mongo handles relational data as well. Things you want normalized (e.q. user records) can have references to other documents in the DB. And of course what ever magic document you want to store works as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: COUNT (DISTINCT column_name) Discrepancy vs. COUNT (column_name) in SQL Server 2008? I'm running into a problem that's driving me nuts.
When running the query below, I get a count of 233,769
SELECT COUNT(distinct Member_List_Link.UserID)
FROM Member_List_Link with (nolock)
INNER JOIN MasterMembers with (nolock)
ON Member_List_Link.UserID = MasterMembers.UserID
WHERE MasterMembers.Active = 1 And
Member_List_Link.GroupID = 5 AND
MasterMembers.ValidUsers = 1 AND
Member_List_Link.Status = 1
But if I run the same query without the distinct keyword, I get a count of 233,748
SELECT COUNT(Member_List_Link.UserID)
FROM Member_List_Link with (nolock)
INNER JOIN MasterMembers with (nolock)
ON Member_List_Link.UserID = MasterMembers.UserID
WHERE MasterMembers.Active = 1 And Member_List_Link.GroupID = 5
AND MasterMembers.ValidUsers = 1 AND Member_List_Link.Status = 1
To test, I recreated all the tables and place them into temp tables and ran the queries again:
SELECT COUNT(distinct #Temp_Member_List_Link.UserID)
FROM #Temp_Member_List_Link with (nolock)
INNER JOIN #Temp_MasterMembers with (nolock)
ON #Temp_Member_List_Link.UserID = #Temp_MasterMembers.UserID
WHERE #Temp_MasterMembers.Active = 1 And
#Temp_Member_List_Link.GroupID = 5 AND
#Temp_MasterMembers.ValidUsers = 1 AND
#Temp_Member_List_Link.Status = 1
And without the distinct keyword
SELECT COUNT(#Temp_Member_List_Link.UserID)
FROM #Temp_Member_List_Link with (nolock)
INNER JOIN #Temp_MasterMembers with (nolock)
ON #Temp_Member_List_Link.UserID = #Temp_MasterMembers.UserID
WHERE #Temp_MasterMembers.Active = 1 And
#Temp_Member_List_Link.GroupID = 5 AND
#Temp_MasterMembers.ValidUsers = 1 AND
#Temp_Member_List_Link.Status = 1
On a side note, I recreated the temp tables by simply running (select * from Member_List_Link into #temp...)
And now when I check to see the difference between COUNT(column) vs. COUNT(distinct column) with these temp tables, I don't see any!
So why is there a discrepancy with the original tables?
I'm running SQL Server 2008 (Dev Edition).
UPDATE - Including statistics profile
PhysicalOp column only for the first query (without distinct)
NULL
Compute Scalar
Stream Aggregate
Clustered Index Seek
PhysicalOp column only for the first query (with distinct)
NULL
Compute Scalar
Stream Aggregate
Parallelism
Stream Aggregate
Hash Match
Hash Match
Bitmap
Parallelism
Index Seek
Parallelism
Clustered Index Scan
Rows and Executes for the 1st query (without distinct)
1 1
0 0
1 1
1 1
Rows and Executes for the 2nd query (with distinct)
Rows Executes
1 1
0 0
1 1
16 1
16 16
233767 16
233767 16
281901 16
281901 16
281901 16
234787 16
234787 16
Adding OPTION(MAXDOP 1) to the 2nd query (with distinct)
Rows Executes
1 1
0 0
1 1
233767 1
233767 1
281901 1
548396 1
And the resulting PhysicalOp
NULL
Compute Scalar
Stream Aggregate
Hash Match
Hash Match
Index Seek
Clustered Index Scan
A: FROM http://msdn.microsoft.com/en-us/library/ms187373.aspx
NOLOCK Is equivalent to READUNCOMMITTED. For more information, see READUNCOMMITTED later in this topic.
READUNCOMMITED will read rows twice if they are the subject of a transation- since both the roll foward and roll back rows exist within the database when the transaction is IN process.
By default all queries are read committed which excludes uncommitted rows
When you insert into a temp table the select will give you only committed rows - I believe this covers all the symptoms you are trying to explain
A: I think i have got the answer to your question but tell me first is userid a primary key in your original table ?
if yes,then CTAS query to create temp table would not copy any primary key of original table ,it only copy NOT NULL constraint that is not a part of primary key..fine?
now what happened your original table had a primary key so count(distinct column_name) doesnt include tuples with null records and while you created temp tables , primary key doesnt get copied and hence the NOT NULL constraint doesnt get to the temp table!!
is that clear to you?
A: It's hard to reproduce this behaviour, so I'm punching in the dark here:
The WITH (NOLOCK) statement enables reading of uncommitted data. I'm guessing you've added that to not lock anything for your users? If you remove those and issue a
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
Prior to executing the query, you should get more reliable results. But then, the tables may receive locks while executing the query.
If that doesn't work, my guess is that DISTINCT use an index to optimize. Check the queryplan, and rebuild indexes as necessary. Could be the source of your problem.
A: What result do you get with
SELECT count(*) FROM (
SELECT distinct Member_List_Link.UserID
FROM Member_List_Link with (nolock)
INNER JOIN MasterMembers with (nolock)
ON Member_List_Link.UserID = MasterMembers.UserID
WHERE MasterMembers.Active = 1 And
Member_List_Link.GroupID = 5 AND
MasterMembers.ValidUsers = 1 AND
Member_List_Link.Status = 1
) as m
AND WITH:
SELECT count(*) FROM (
SELECT distinct Member_List_Link.UserID
FROM Member_List_Link
INNER JOIN MasterMembers
ON Member_List_Link.UserID = MasterMembers.UserID
WHERE MasterMembers.Active = 1 And
Member_List_Link.GroupID = 5 AND
MasterMembers.ValidUsers = 1 AND
Member_List_Link.Status = 1
) as m
A: Ray, please try the following
SELECT COUNT(*)
FROM
(
SELECT Member_List_Link.UserID, ROW_NUMBER() OVER (PARTITION BY Member_List_Link.UserID ORDER BY (SELECT NULL)) N
FROM Member_List_Link with (nolock)
INNER JOIN MasterMembers with (nolock)
ON Member_List_Link.UserID = MasterMembers.UserID
WHERE MasterMembers.Active = 1 And
Member_List_Link.GroupID = 5 AND
MasterMembers.ValidUsers = 1 AND
Member_List_Link.Status = 1
) A
WHERE N = 1
A: when you use count with distinct column it doesn't count columns having values null.
create table #tmp(name char(4) null)
insert into #tmp values(null)
insert into #tmp values(null)
insert into #tmp values("AAA")
Query:-
1> select count(*) from #tmp
2> go
3
1> select count(distinct name) from #tmp
2> go
1
1> select distinct name from #tmp
2> go
name
NULL
AAA
but it works in derived table
1> select count(*) from ( select distinct name from #tmp) a
2> go
2
Note:- I tested it in Sybase
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: jQuery - Slide down div I have a table cell and what I want is that if the user clicks on the table cell a div collapses (div is in another table cell).
$(function slideDown(id) {
$("getdiv"+id).fadeIn();
});
The table row (hover function):
<tr class="odd" id="div96" onhover="slideDown(96)"><td>ZZZn ZZZ</td></tr>
The table cell (needs to fade in/slide down):
<tr><td id="getdiv95" class="divinside" style="display: none;">Text</td></tr>
I'm sorry for my poor English.
Demonstration image
A: You are doubling up the 'div' part.
var name = $(this).attr('id');
$("#" + name).slideDown();
The way you have it written now it would look like
$("#divdiv1")...
Instead of
$("#div1")...
Also, wrap all this in a $(document).ready(function(){}); so that it triggers the click binding after all the tr elements have loaded.
A: Slide down is a function, you must invoke it in order for it to be run:
$("#div" + name).slideDown();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Change registry settings for all users I am writing a small program using C# that needs to set set the power settings for all users. This means I will need to change the Hkey Current User, and all the profiles under the Hkey Users hive. I know how to change the power settings registry keys, but I do not know how to "cycle" through all the users "profiles" (for lack of a better word) and make this change under their settings. How do I do this, or is there a better way to do this. I apologize if the scenario is not clear.
Thanks
msindle
A: You can find a list of all profiles on the computer here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\
Each key is a profile. You can check the username by looking at the ProfileImagePath value.
Then use the keyname and go to HKEY_USERS\[keyname] for each user.
I'd be careful though, because you probably don't want to mess with the settings for the LocalService / NetworkService / etc users.
A: There is no general way to edit other users' Registry settings directly. Other users' Registry settings might not even be stored on your computer. For a taste of some of the problems, read Raymond Chen's blog post, "Beware of roaming user profiles". (Make sure you understand what he has to say -- some of it applies even if you're writing an internal tool on a network that doesn't have roaming profiles enabled.)
The best solution would probably be to make a small app that makes this change for the current user, and add it to everyone's login script. That would mean your utility would change the setting every time they log in, rather than making a one-time change (so they wouldn't be able to change it back permanently), but you would be sure it happened for every user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Which boost macro would allow me to do insert variable number of statements in the program Suppose I want to achieve the following example effect :
if (i) j--;
Now I want to insert that line in my program as many times as I want repeatedly. If I wanted to insert that statement 1000 times then I'd have to copy paste it manually.
The purpose is to insert statements in the program and not just achieve the same logical behaviour.
I would like to use a macro that given a statement and an n inserts the statement n times in the program. I think this is possible using some Boost library macro. But I have never used Boost and I don't know which one should I use. Also I am restricted to C and not C++, but I believe that this boost macro should work in C as well.
I want to what to use and how to use it to achieve this effect
A: You are looking for BOOST_PP_REPEAT.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Breaking out of a JavaScript for statement from within an if statement This is what I want to do: cycle through a complex data structure and if one of the elements meets some condition, return it. But I don't think it's possible to return from within an 'if' that's within my for loop. What's the best practice? Thanks.
function findIt(x) {
for (i in someDataArray) {
v = someDataArray[i];
if (*v meets some condition*) {
return v;
}
}
}
A: It's perfectly legal to issue return statement from within an if.
The only issue here is what happens if it's not found? Here the function will implicitly return undefined. It may be better to make this explicit. This is a matter of style though.
function findIt(x) {
for (i in someDataArray) {
v = someDataArray[i];
if (*v meets some condition*) {
return v;
}
}
return undefined;
}
A: you can return from anywhere you want.. with respect to best practice make sure that all your code paths return something and all the paths should return the same type of data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to implement datcontext per request/thread using factory pattern Using this sample project as a guideline, I am setting up a new project. My project will follow the same basic architecture, only in addition to an mvc project, I will also have a wcf web service project(or possibly servicestack.net)
Instead of using Unity for DI as in the sample, I am using Ninject. Currently I am configuring Ninject as follows to only instantiate one instance of Database factory per web request(and thus one datacontext class per request (using EF 4.1 code first btw))
kernel.Bind<IDatabaseFactory>()
.To<DatabaseFactory>()
.InScope(ctx => HttpContext.Current);
I am curious if this method is sufficient? Or would it be better to let the factory class handle the instantiation of datacontext per http request(and possibly per thread if I were design for non web based front-ends in the future)? If so, are there any examples out there of how to go about this?
Or is there a completely better solution to handle this?
A: You should use .InRequestScope() instead of .InScope(ctx => HttpContext.Current). It ensures that the appropriate scope is used depending on whether the instance is requested via WCF or via ASP.NET MVC. Unfortunately to take full advantage of this you'll have to use the current continous integration builds from http://teamcity.codebetter.com . See also
https://github.com/ninject/ninject.extensions.wcf
https://github.com/ninject/ninject.web.mvc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to unit test for backward and forward compatibility? I am working on developing an Plug-In API that uses Java serialization. The idea is similar to SmallTalk's system images. I was wondering how would to best to automate testing for whether changes I am making will break deserialization since some changes seem to be innocuous like adding a method to an interface that is implemented (as long as that is not called, otherwise it will result in a AbstractMethodException).
Yes, this is more for an experimental spike rather than production code so please do not suggest not using serialisation.
A: For backward compatibility of data, keep a lot of old messages in binary form, and see if you can still deserialize them with the new code.
For backward compatibility of code, you'll need some way of building your old code (e.g. one version per release) and testing that against data created from the newest version of the code. This is a slightly more challenging problem - you may want to build a small test jar on each appropriate release, and put that into source control at the same time to avoid having to build the same code again and again. Your tests would then try all the different jar files against the output of the new code.
To be honest, this all sounds like quite a lot of work for an experimental spike. For real work I'd just use protocol buffers of course :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Implementing an interface then calling the Initialize() function this wont be easy to explain clearly but here goes...
i have something that works fine in VB but not in C#.
i have 2 classes, each class implements a different interface. each interface exposes an Initialize() function that should get called automatically when the plugin loads. since each class has an Initialize() function, i can watch both functions get called in the log. this works fine in VB.
when i do this same thing in C#, only the Initialize() in the first class gets called. anyone have a clue as to why this might be happening?
vb code:
Public Class class1
Implements Interface1
Public Sub Initialize() Implements Interface1.Initialize
msgbox("initialize from class1")
End Sub
End Class
Public Class class2
Implements Interface2
Public Sub Initialize() Implements Interface2.Initialize
msgbox("initialize from class2")
End Sub
End Class
C# code:
public class class1 : interface1
{
public void Initialize()
{
messagebox.show("initialize from class1");
}
}
public class class2 : interface2
{
public void Initialize()
{
messagebox.show("initialize from class2");
}
}
as you can see the code is identical in both languages. why does it work in VB and not in C#?
A: Is the constructor of both classes called? Or is only the fist class initialized?
Please try adding a (static) constructor to check which classes are initialzed.
Static Constructor for one Class:
public class class2 : interface2
{
static class2(){
messagebox.show("Static Constructor from class2");
}
public void Initialize()
{
messagebox.show("initialize from class2");
}
}
A: Thanks everyone for your help! It turns out the problem was in the calling code. Long story short, each plugin has a command ID as part of the interface. In this case both have ID 1000. When the calling code loops through plugins to load, if it sees a duplicate ID it skips that plugin. My problem was that I was loading other plugins at the same time with the same ID. You all helped find a bug in the calling code (which is pretty well-known software) so thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Not being able to add a textView to LinearLayout through code I am a beginner of android, and was studying the layout.
What i am trying to do is i am trying to add a textView to a LinearLayout through code, and the application stops with the error that the application has stopped unexpectedly. The code is:
setContentView(R.layout.main);
LinearLayout abc = (LinearLayout)findViewById(R.id.cLayout);
TextView tv = new TextView(this);
tv.setText("Text Changed!!!!");
abc.addView(tv);
And in the xml, id is set like: android:id="@+id/cLayout".
I know there are better ways to do it, but i want to know why this doesn't work. Contents of textView are changing just fine. Also i have also tried
LinearLayout abc = (LinearLayout)findViewById(R.layout.main);
What am i doing wrong? One thing is clear that i am accessing uncreated items (unassigned pointer).
Edit
Main xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/cLayout"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World"
android:id="@+id/myTV"
/>
</LinearLayout>
A: I've tried to reproduce it, and it works for me, no exceptions.
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"/>
</LinearLayout>
MyActivity.java:
public class MyActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout) findViewById(R.id.cLayout);
TextView tv = new TextView(this);
tv.setText("Hello Again!");
ll.addView(tv);
}
}
UPD When I posted your code, I got an exception, too. Make sure you call super.onCreate().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Text renders inconsistently in Safari (5.0.5) I'm having a hard time resolving this.
I'm working on http://movingwineforward.com, but it renders text inconsistently, as you can see in this screenshot:
When the page loads, the text in the main menu looks thin (left), and is consistent with every other OS and Browser. But when clicked, it becomes a bit heavier as in the right side of the screenshot.
I checked every CSS property, both in the stylesheet and in Safaris (and Chrome) DOM Inspector, and they both are identical.
When I disable scripts in Safari, the text loads like heavier version (right), so I guess that is interfering. (I'm loading some Vimeo flash players, among other scripts).
For added mistery, this site is a copy of http://daf.cl, and they both have the exact same stylesheet, DOM (markup), font files, and Javascript. Only colors and content change. But in http://daf.cl the text loads initially in the heavier version and stays like that.
I've been able to reproduce this behaviour on Safari 505 running in OSX Leopard.
By clients request, the text has to look like the one on the right (heavier).
I've tried forcing -webkit-font-smoothing and text-rendering in CSS, but none did the trick. Font weight does not look good, as it forces the typeface.
Update 1:
I know now when this ocurrs: only when there is a Vimeo flash player behind the menu, the text renders thinner. If there is no video behind, it looks heavier (as it should). Perhaps this brings new light. (I tried disabling jQuery Froogaloop for Moogaloop, but didn't work)
A: First, do this:
opacity: .99;
Applying this to the object containing your text will initialize it looking 'lighter'. So it wont't fix the issue in your preferred way (stick to 'regular' thickness), but will instead prevent the subsequent 'bounce' to the lighter looking variant.
Now, let's do some tweaking:
text-shadow: 0 0 1px rgba(255, 255, 255, 0.75);
Additionally applying a subtle text-shadow in the exact same color as the font will result in the text looking almost exactly like you want.
A: Though not a real solution, you could try adding something like
text-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
to the text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: HttpPost Iphone Versus Android 1)On Iphone,
- (void) postData:(NSMutableData *)_body withAction:(NSString *)_action binary:(BOOL)_binary
{
[self stopProcess];
binary = _binary;
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:API_FORMAT, APP_SERVER, _action, [self getSession]];
if (debug_switch) {
NSLog(@"The action is %@", _action);
NSLog(@"The accessing server API call Datafeed is %@", url);}
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
//TRACE(@"url: %@", url);
if(_body != nil)
{
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
[request setHTTPBody:_body];
}
//con = [NSURLConnection connectionWithRequest:request delegate:self];
if(con != nil) {
[con release];
}
con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (con)
{
dataDict = nil;
loading = YES;
if(receivedData == nil) {
receivedData = [[NSMutableData data] retain];
}
[receivedData setLength:0];
}
}
static NSString *boundary = @"---------------------------147378274664144922";
@implementation DataFeed
BOOL connectable = NO;
///////////////////////////////
- (NSMutableData *) initContentBody
{
NSMutableData *body = [NSMutableData data];
[body appendData:[self addFormData:@"uid" withString:[[UIDevice currentDevice] uniqueIdentifier]]];
return body;
}
//////////////////////////
- (NSData *) addFormBoundary
{
return [[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding];
}
//////////////////////////////////////////
- (NSData *) addFormData:(NSString *)_name withInt:(int)_value
{
return [self addFormData:_name withString:[[NSNumber numberWithInt:_value] stringValue]];
}
- (NSData *) addFormData:(NSString *)_name withFloat:(float)_value
{
return [self addFormData:_name withString:[[NSNumber numberWithFloat:_value] stringValue]];
}
- (NSData *) addFormData:(NSString *)_name withString:(NSString *)_value
{
NSMutableData *body = [NSMutableData data];
[body appendData:[self addFormBoundary]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\n\r\n%@", _name, _value] dataUsingEncoding:NSUTF8StringEncoding]];
return body;
}
- (NSData *) addFormData:(NSString *)_name filename:(NSString *)_filename withData:(NSData *)_data
{
NSMutableData *body = [NSMutableData data];
[body appendData:[self addFormBoundary]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", _name, _filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/zip\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Transfer-Encoding: binary\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:_data];
return body;
}
2)On Android,
public void executeHttpPost() throws Exception {
String address = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
pairs.add(new BasicNameValuePair("key2", "value2"));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
}
The question, on body data of the android can it set to non json format, key-value pair? as you can see on iphone, body can be any parameters, doesn't have to be key value pair.can you give an example on android where the post data can be non-json format?
A: You're not constrained to UrlEncodedFormEntity, check out the "Known Indirect Subclasses" of the org.apache.http.HttpEntity interface (at the top of the page).
The most commonly used ones are probably:
*
*ByteArrayEntity: An entity whose content is retrieved from a byte array.
*FileEntity: An entity whose content is retrieved from a file.
*InputStreamEntity: A streamed entity obtaining content from an InputStream.
*SerializableEntity: Takes an Serializable object and outputs its serialized form
*StringEntity: An entity whose content is retrieved from a string.
*and finally UrlEncodedFormEntity: An entity composed of a list of url-encoded pairs.
(this list is not complete, check out the above link)
Here's some examples of how to use different types of entities:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
// a string entity containing JSON:
post.setEntity(new StringEntity("{ \"actually\" : [\"json\", \"this time\"]}");
// or uploading an image file:
post.setEntity(new FileEntity(new File("some/local/image.png"), "image/png");
// or some random bytes:
byte[] randomBytes = new byte[128];
new Random().nextBytes(randomBytes);
post.setEntity(new ByteArrayEntity(randomBytes);
HttpResponse response = client.execute(post);
...
Of course, don't do this all at once, one call to setEntity() only! If you need MIME multipart requests, check out this tutorial by Vikas Patel (you'll need an updated Apache HTTP Client JAR).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Button at Bottom Im not very good in creating android layouts so I am not able to align the button to the bottom in the MainView.
Picture:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<ListView android:id="@+id/lv_pizza" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"></ListView>
<Button android:layout_width="fill_parent" android:id="@+id/bt_add"
android:layout_height="wrap_content" android:text="hinzufügen"></Button>
<RelativeLayout android:layout_width="fill_parent" android:id="@+id/relativeLayout2" android:layout_height="fill_parent">
</RelativeLayout>
</LinearLayout>
Please help
A: This works for a linear layout, note the layout_weight 1 on the list -- that's what pushes the button to the bottom:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView android:id="@+id/lv_pizza"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button android:id="@+id/bt_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hinzufügen" />
</LinearLayout>
This then looks like this in the UI editor:
A: Hi you can set like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<ListView android:id="@+id/lv_pizza" android:layout_width="fill_parent"
android:layout_above="@+id/bt_add" android:layout_height="fill_parent" ></ListView>
<Button android:layout_width="fill_parent" android:id="@+id/bt_add"
android:layout_gravity="bottom" android:layout_height="wrap_content" android:text="hinzufügen"></Button>
</RelativeLayout>
A: Removing the RelativeLayout will push the button to bottom of the screen...
A: Use a layout_weight for the components inside the LinearLayout. If the ListView has a weight of 1.0, it should push the button to the bottom. I've done this with a ScrollLayout and it works well, allowing the component inside the scroll layout to actually scroll. You could put your ListView into a ScrollLayout to let it grow beyond the visible size.
Also, the second relativelayout also isn't necessary as it doesn't add anything.
A: You can set a marginTop in the Button until the bottom or change the layout to relative and set the position.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I use dirname with PHP on IIS? I have a php program that uses:
include (dirname(__FILE__) . "/../src/adLDAP.php");
but when I run it it comes out:
C:\inetpub\wwwroot\testphp/../src/adLDAP.php Fatal error:
Class 'adLDAP' not found in C:\inetpub\wwwroot\testphp\examples.php on line 12
How do I get the paths right on IIS with PHP? I did not see anything in php.ini to set this. I also tried to to use manually \ instead of / but it never sees the file.
This
include (dirname(__FILE__) . "\src\adLDAP.php");
gives this:
C:\inetpub\wwwroot\testphp\src\adLDAP.php
which is the right path but it never finds my class (I verified correct path with explorer copy and paste, it's there). I put in a echo "HELLO"; to test but never echos.
What am I doing wrong so I can include the file. Windows 7, IIS. Thank you.
It has include in front of it. Added.
did not help:
server path / vs \
A: adLDAP is namespaced. Instead of:
$adldap = new adLDAP();
try:
$adldap = new \adLDAP\adLDAP();
or:
$adldap = new adLDAP\adLDAP();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Formatting text within UILabel differently I'd like different words in a UILabel to be different colors. Does this mean each word will need to be a different UILabel? I'm guessing yes, though sure would be nice to just put color codes in the label somehow, you know? I guess I'm a bit spoiled by text markup in HTML.
A: There is no proper UIRichTextView in iOS. It's high on my wish-list for iOS 6 (and there's some reason to believe we may get it then due to the release of Pages).
Your options are to use multiple UILabel views, NSString UIKit Additions, Core Text, UIWebView, or one of a few third-party frameworks such as:
*
*NSAttributedString-Additions-for-HTML
*CoreTextWrapper
*OHAttributedLabel
*OmniUI
All of the current solutions have different problems. The most common problem is that it's hard to get select and copy functionality to work with rich text unless you use a web view. Web views are incredibly annoying because they're asynchronous and you have to do a lot of your interactions in JavaScript.
I wish there were a better answer.
(Obligatory shilling: This topic is covered in depth in Chapter 18 of iOS 5 Programming Pushing the Limits.)
A: UILabel doesn't support segmented formatting (the entire thing can only have one format).
Have a look at OHAttributedLabel, which does what you want.
A: As far as I'm aware you'd need to have separate labels for each different coloured word. Depending what you're trying to do you may be able to make use of myLabel.textColor to change the colour of the periodically or on events etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is there a pure CSS way to have a bar stay on the same place? Similar to some Facebook feature, like the Chat link, that stays constantly at the same place of the page, regardless if you scroll.
Is there a simple pure CSS way to achieve this?
Here is a very simplistic HTML:
<div id='constant-bar'> some background some text</div>
<p>content</p>
<p>content</p>
<p>content</p>
.... X 1000
<p>content</p>
I really care right now for IE>8 and FF > 5 and chrome, Safari latest versions. My code will be released only some time from today
A: look into the CSS attribute fixed:
position: fixed;
Example
A: Research position:fixed
It is not supported on many mobile browsers at the moment, and older Internet Explorer versions (IE<7) don't support it either. Additionally, IE 7 has a strange bug.
If you want it to stretch the full height of the page, you'll also have to look into that too. This tutorial might help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wait for random amount of time, then start updating elapsed time in a UILabel (iPhone) I'm trying to implement a button that starts a timer after a random period of time (between 0-10s). While the timer is running it should update a label every 0.005s to show how much time has elapsed. The problem i'm having is 2-fold:
*
*I'm not sure how to get the label to update with the elapsed time every 0.005s.
*I'm having trouble getting the app to wait the random amount of time before starting timer. At present I'm using sleep(x) however it seems to cause the app to ignore all the other code in the if statement and causes the button image to freeze up (i.e. it looks like its still clicked).
Here is the code I have so far...
- (IBAction)buttonPressed:(id)sender
{
if ([buttonLabel.text isEqualToString:@"START"])
{
buttonLabel.text = @" "; // Clear the label
int startTime = arc4random() % 10; // Find the random period of time to wait
sleep(startTime); // Wait that period of time
startTime = CACurrentMediaTime(); // Set the start time
buttonLabel.text = @"STOP"; // Update the label
}
else
{
buttonLabel.text = @" ";
double stopTime = CACurrentMediaTime(); // Get the stop time
double timeTaken = stopTime - startTime; // Work out the period of time elapsed
}
}
If anyone has any suggestions on..
A) How to get the label to update with the elapsed time.
or
B) How to fix the 'delay' period from freezing up the app
... it would be really helpful as I'm pretty much stumped at this point. Thanks in advance.
A: You should use an NSTimer to do this. Try the code:
- (void)text1; {
buttonLabel.text = @" ";
}
- (void)text2; {
buttonLabel.text = @"STOP";
}
- (IBAction)buttonPressed:(id)sender; {
if ([buttonLabel.text isEqualToString:@"START"]) {
int startTime = arc4random() % 10; // Find the random period of time to wait
[NSTimer scheduledTimerWithTimeInterval:(float)startTime target:self selector:@selector(text2:) userInfo:nil repeats:NO];
}
else{
// I put 1.0f by default, but you could use something more complicated if you want.
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(text1:) userInfo:nil repeats:NO];
}
}
I'm not exactly sure how you want to update label based on the time, but if you post more code, or give an example, I'll post the code on how to do that, but it would just be using an NSTimer as well. Hope that Helps!
A: The answer to A could be:
Once the random amount of time has passed, (@MSgambel has a good suggestion), then execute:
timer = [NSTimer scheduledTimerWithTimeInterval:kGranularity target:self selector:@selector(periodicallyUpdateLabel) userInfo:nil repeats:YES];
(The above line could go into @MSgambel's -text2 method.)
That will call the -periodicallyUpdateLabel method once every kGranularity seconds, repeatedly. In that method, you could do things like update your label, check for user actions, or end the game if the time is up or some other condition has been met.
And here is the -periodicallyUpdateLabel method:
- (void)periodicallyUpdateView {
counter++;
timeValueLabel.text = [NSString stringWithFormat:@"%02d", counter];
}
You'll have to format the text differently to get what you want. Also, translate from the counter value to time using kGranularity. However, and this is what I found, there is only so many cpu cycles in iOS devices. Trying to go down to microsecond level made the interface sluggish and the time displayed started to drift from the actual time. In other words, you may have to limit your updates of the label to once every one hundredth of a second or tenths. Experiment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NMEA sentences - PGLOR, GNGSA and QZGSA I'm writing an Android app that reads and parses NMEA sentences from GPS receiver and using a Nexus S phone for tests.
I'm getting GPGGA, GPGSV, GPGSA and GPRMC sentences that are pretty common and very well documented, but in addition, I'm getting next sentences and I'cant find any info about them:
PGLOR, GNGSA, QZGSA
Where I can find some docs about those sentences format?
A: I recently wrote an app that parsed the GPGGA NMEA strings, my advice is parse what you need, and leave the rest. Generally you don't need all formats, only specific ones.
A: The $GN-prefix is usually used when the sentence is formed using several satellite constellations (so far usually Glonass and GPS are the viable options). The $QZ-prefix is a little more unclear but I assume that it is for the Japanese QZSS-satellite constellation.
The rest of the sentence after the prefix is standard NMEA 0183 and contains what the normal GSA-sentence would contain.
The $PGLOR is probably used to produce information and / or configure the locationing chip. Or something similarly uninteresting.
What's really interesting is that Nexus S seems to have a Multi GNSS locationing chip.
Further information here
A: The first two characters typically define the type of device sending the message, with the last three being the type of message. $GNGSA and $QZGSA should be reporting the same or similar data as $GPGSA, which would be satellite data, including dilution of precision.
I don't know which device these come from, but GN is mentioned here: http://macrogroup.ru/content/data/store/images/f_1072_5353_1.pdf
Regarding $PGLOR... I'm not sure. Perhaps if you could post what chipset is used internally, its documentation could be consulted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Determining Pending Finalizer Sources I'm coming into a project that has a known issue. The application hangs on a call to GC.WaitForPendingFinalizers. The obvious solution workaround is to remove the WaitForPendingFinalizers call but unfortunately this is being done for us in a third-party assembly, so removal is not an option.
Instead, I want to find the root of the issue and figure out who's finalizer is blocking. The codebase, however, is large and since I'm just coming into it, it's also unfamiliar so I don't even have any gut feelings or intuitions of where it might be. This means I'm going to need to use intrumentation and tools to help find it.
So my questions are:
*
*Will the framework/ee thread that is iterating the Finalizer Queue show up in the Threads view in Studio? The stack trace for this would go a long way to finding where we are hanging.
*Is there a tool that will show me pending finalizers and their roots (this is a CF project, but I'm willing to take wide paths to try and find this)?
*Anyone have any thoughts or experiences they want to share that might aid in finding this?
A: This might be one of those cases where Windbg is your friend. Have a look at Tess's blog. Here's an article about debugging a finalizer issue with the !finalizequeue debugger command. http://blogs.msdn.com/b/tess/archive/2007/10/19/net-finalizer-memory-leak-debugging-with-sos-dll-in-visual-studio.aspx
(If you've never done anything with windbg and sos.dll before, do some more reading on Tess's blog. She has some articles that make it very approachable).
A: I took a quick look in VS (VS 11) and when I break I can see a Thread called "GC Finalizer Thread" and it's caught doing a Sleep() in my destructor.
But your mention of CF may make it an entirely different ballgame.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to make a URL in JavaSctipt I currently have this JavaScript:
new_string = "<p>Problem name: <a href=\"http://www.problemio.com/problems/problem.php?problem_id=\" + problem_id + ">" + title + "</a></p>";
Where the title and problem_id are variables with a string and an id respectively.
How should I approach quotes when I have such situations as I am facing now?
Thanks!
A: You've just made a few mistakes with your quotation marks and slashes. It's best to use both single and double quotes to keep track:
new_string = "<p>Problem name: <a href='http://www.problemio.com/problems/problem.php?problem_id=" + problem_id + "'>" + title + "</a></p>";
However, if you'd like to go the slash route:
new_string = "<p>Problem name: <a href=\"http://www.problemio.com/problems/problem.php?problem_id=" + problem_id + "\">" + title + "</a></p>";
A: Just end it with a quote:
var variable = 0;
var string = "\"quoted\"" + variable + "\"quotes everywhere\""; // "quoted"0"quotes everywhere"
A: ' for string, " for quotes inside string. I'm doing it like this, and I've seen most javascript projects do it that way too.
A: I believe you just have one quote out of place:
new_string = "<p>Problem name: <a href=\"http://www.problemio.com/problems/problem.php?problem_id=" + problem_id + "\">" + title + "</a></p>"
A: You can do this:
new_string = "<p>Problem name: <a href=\"http://www.problemio.com/problems/problem.php?problem_id=" + problem_id + "\">" + title + "</a></p>";
Or this:
new_string = '<p>Problem name: <a href="http://www.problemio.com/problems/problem.php?problem_id='+ problem_id +'">' + title + '</a></p>';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Memory & Handle Leaks in my ServiceHost I've got a ServiceHost in a service app that communicates with 1700 clients every 60 second. When I start the service, it climbs to about 1500 open handles almost immediately, then continues to add another 300 after about 5 minutes (and continues onward continuously after that.)
I've looked at ProcessExplorer and in Split view, it shows hundreds of handles of type File named "Device\Afd" - which is a representative of the TCP socket being used to communicate (I believe).
I'm only assuming that my handle leak is related to the ServiceHost because it represents the highest number of handles observed from Process Explorer. What I'm wondering is why doesn't the service close these? Do I need to set a timeout of some sort or do I need to actively close them myself somewhere?
Here's how my ServiceHost is created:
wcfObject = new WcfObject();
host = new ServiceHost(wcfObject, baseWcfAddress);
ServiceBehaviorAttribute attribute = (ServiceBehaviorAttribute)host.Description.Behaviors[typeof(ServiceBehaviorAttribute)];
attribute.ConcurrencyMode = ConcurrencyMode.Multiple;
attribute.InstanceContextMode = InstanceContextMode.Single;
And in my app.config:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="WcfObject" behaviorConfiguration="DefaultBehavior">
<host>
<baseAddresses >
<!-- Defined in code -->
</baseAddresses>
</host>
<endpoint name="NetTcpEndPoint" address="" binding="netTcpBinding" bindingConfiguration="netTcpBinding" contract="IWcfObject"/>
<endpoint name="NetTcpMetadataPoint" address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="netTcpBinding" maxReceivedMessageSize="9655360" maxBufferSize="9655360" maxBufferPoolSize="524288">
<readerQuotas maxArrayLength = "932000" maxStringContentLength="900000" maxDepth="32"/>
<security mode="None"></security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior" >
<serviceMetadata httpGetEnabled="False" httpGetUrl="" />
<serviceDebug includeExceptionDetailInFaults="True"/>
<serviceThrottling maxConcurrentCalls="50" maxConcurrentSessions="100" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
A: I think your specific problem is described here.
When the channel is created and the operation context exists, then
each new channel instance is appended in the list of WmiChannels (see
property InstanceContext.WmiChannels in code below). This list causes
the leak. However if the InstanceContext is recreated on each invoke
of operation (that is when InstanceContextMode is set on PerCall), the
list will be recreated and no leak will be caused.
For a workaround, see the same post. Please keep us informed of your findings.
A: As it turns out, I was running my service from a [STAThread] - anytime an app uses COM calls, you'll potentially leak memory unless you are running [MTAThread] mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: External (CDN hosted) image request URL rewritten in IE8 on canvas page over https, asks for proxy.php I have a canvas-based app on Facebook wit a lot of images to load, so I'm creating them in JavaScript.
var img = new Image();
img.src = document.location.protocol + '//example.cloudfront.net/example_path/example.png';
The images are hosted on Amazon's CDN, their base URL is similar to:
https://example.cloudfront.net/example_path/example.png
The URL of the app, hosted in a cloud (EC2, also Amazon) is similar to:
https://cloud.example.com/path_to_app/
It works on most browsers, but not in IE (8).
In IE, if I inspect the src property of a created image, it shows the correct URL, but the browser makes the following request:
GET /path_to_app/proxy.php?url=https://example.cloudfront.net/example_path/example.png HTTPS/1.1
There is no proxy.php on my server, nor is the word 'proxy' present anywhere in my code, neither client- nor server-side.
Is there something I don't know about externally hosted content in an iframe canvas page, served over https?
A: I found the problem.
I'm using flashcanvas in IE to emulate the <canvas> element. There are cross-domain asset access security issues with Flash, so the applet requests them via a proxy php script (actually included in the distribution, lol).
Trouble was, the flashcanvas source code is minimized/obfuscated, so the string 'proxy' is not visible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does a false assertion in async test in GHUnit crash the app instead of just failing the test? This question has very few views and no answers yet. If you have a suggestion what to change about this question to get more eyeballs, I'd be happy to hear them. Cheers!
I'm using GHAsyncTestCase to test a custom NSOperation of mine. I'm setting the test case as a delegate on the operation object and I'm calling didFinishAsyncOperation on the main thread when it's done.
When an assertion fails it throws an exception, which ought to be caught by the test case to render the test as "failed". But instead of this expected behavior, my app get's aborted by Xcode as soon as the assertion fails.
*** Terminating app due to uncaught exception 'GHTestFailureException', reason: ''NO' should be TRUE. This should trigger a failed test, but crashes my app instead.'
I'm obviously doing something wrong. Who can tell me?
@interface TestServiceAPI : GHAsyncTestCase
@end
@implementation TestServiceAPI
- (BOOL)shouldRunOnMainThread
{
return YES;
}
- (void)testAsyncOperation
{
[self prepare];
MyOperation *op = [[[MyOperation alloc] init] autorelease];
op.delegate = self; // delegate method is called on the main thread.
[self.operationQueue addOperation:op];
[self waitForStatus:kGHUnitWaitStatusSuccess timeout:1.0];
}
- (void)didFinishAsyncOperation
{
GHAssertTrue(NO, @"This should trigger a failed test, but crashes my app instead.");
[self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testAsyncOperation)];
}
@end
A: Look up your Xcode Breakpoints navigator,delete all exception breakpoints,That's all !!!
A: I've been digging for a week to find a solution to this when I finally caught a break. It's been a bit weird having next to no views on a bounty question and no one cared to attempt an answer. I was thinking the question might be stupid, but there were no downvotes and no one cared to correct it either. Has StackOverflow become that saturated?
A solution.
The trick is to not assert anything from the callback method, but put the assertions back in the original test. The wait method is actually blocking the thread, which I didn't think of before. If your async callback receives any values, just store them in an ivar or property and then make assertions based on them in your original test method.
This takes care of the assertions not causing any crashes.
- (void)testAsyncOperation
{
[self prepare];
MyOperation *op = [[[MyOperation alloc] init] autorelease];
op.delegate = self; // delegate method is called on the main thread.
[self.operationQueue addOperation:op];
// The `waitfForStatus:timeout` method will block this thread.
[self waitForStatus:kGHUnitWaitStatusSuccess timeout:1.0];
// And after the callback finishes, it continues here.
GHAssertTrue(NO, @"This triggers a failed test without anything crashing.");
}
- (void)didFinishAsyncOperation
{
[self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testAsyncOperation)];
}
A: Looking at the header files for GHUnit, it looks like that may be what is supposed to happen with your code. A subclass of GHUnit could override this method:
// Override any exceptions; By default exceptions are raised, causing a test failure
- (void)failWithException:(NSException *)exception { }
To not throw exceptions, but an easier solution is to use the GHAssertTrueNoThrow instead of GHAssertTrue macro.
A: I think this question should be rather, "how to test methods with blocks in GHUnit"?
And the answer can be found here: http://samwize.com/2012/11/25/create-async-test-with-ghunit/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Defining Custom iOS Keyboard Key Variant ~ f/w 4.x+ Some Keys on the iOS keyboard, when pressed and held for a second or so, revile Variants to the character being selected (see link) http://i.stack.imgur.com/4Hh4t.jpg
I'm curious to know if there is a certain way to add/remove to these variants - of course with Jailbreak. (It's impossible without J/B)
For Example, is there a way to add to the Key "l" when held to revile the string "lol"?
Thank you.
A: This can be done by simply editing a plist file in System-> Library-> Frameworks-> UIKit.framework and chose your keyboard plist file and add a string under 'Roman-Accent-I'
Do Not try this if you don't know what u r doing
A: I would try and figure out how these guys did it and go from there?
http://www.iphonehacks.com/2009/02/jailbreak-app-5row-qwerty-keyboard-adds-another-row-of-keys-to-iphones-virtual-keyboard.html
A: There's a package called Vmoji that adds extra key variants - it might be worth a look to help you figure out what's going on, or contacting the developer might be helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: module module class vs. module module::class in Ruby What is the difference between
module MyModule
module MySubModule
class MySubModuleClass
...
end
end
end
and
module MyModule
class MySubModule::MySubModuleClass
...
end
end
in Ruby?
A: On the second example you are defining a class, in the first is a module, and you can't use the syntax MySubModule::MySubModuleClass if MySubModule does not exist. So you have to have it defined before.
A: the second case will not work unless "MySubModule" is already defined elsewhere...
the second case is not a proper definition of "MySubModule" and will cause an error if you didn't define that MySubModule elsewhere
NameError: uninitialized constant MyModule::MySubModule
from (irb):2:in `<module:MyModule>'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drupal - Use existing cck fields in a CCK selectable list field This is for Drupal 6. Field display weights (per node) would solve this problem in Drupal 7, but no back port exists currently for 6.
I have a series of node reference fields for a variety of multi-media content on my site that I would like to be able to re-order on a per node basis.
I created node reference fields, each referring to one specific content type - field_ref_image (images), field_ref_documents (documents), field_ref_videos (videos), field_ref_youtube (youtube videos)
I then built views for each content type using the node relationships module to make a very visual presentation for selecting content.
But now I need to be able to re-order each of these on a per node basis.
So field_ref_image may need to be above field_ref_documents in one case but below it in another.
I built a view to display these fields and just need something to sort the results on.
I believe the solution lies in using a select list field in conjunction with the multi select module (allowing a sort order of field items), but I don't know how to set the allowed values to be my existing fields.
As a fallback I do have one node reference field created that references all my content types, then have a view built that groups based on node type, but the admin UI experience isn't very clear as to what content type is being referenced in any particular case.
Figuring out how to weight or order each field type using a select list or similar CCK field I believe is the answer.
Are there any PHP snippets that would allow me to use these pre-existing CCK fields as my allowed values list?
A: TBH, this seems like a pretty heavy solution for use case that is better handled natively by D7. In fact just offhand, I don't see how you would be able to do this in D6 using the method you described.
Not to be an upgrade evangelist here, but what are the reasons for trying to extend your site's functionality on an old version, instead of upgrading to the current version where your use case is much more easily implemented?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: registerDefaults to save a number i created a simple project, with a "+" and "-" buttons that increase or decrease a number inside a label.
I wanted to test the registerDefaults method, but if i click on the "home" button, and come back on the project from the simulator (with my app's icon), the number is still the same on screen.
How can i test the user settings with this example? or is it something with the simulator, or would it work if i use the device and wait for the memory warning method to automatically refresh the project, and then it would work?
here's a bit of my code :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
NSNumber *testValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"kRestore"];
if (testValue){
NSLog(@"already");
viewController.myNum = (int)testValue;
} else {
NSLog(@"empty");
viewController.myNum = 0;
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSNumber *num = [NSNumber numberWithInt:viewController.myNum];
NSDictionary *savedNumber = [NSDictionary dictionaryWithObject:num forKey:@"kRestore"];
[[NSUserDefaults standardUserDefaults] registerDefaults:savedNumber];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"ok resign active");
}
Thanks
A: Try setting the viewController.myNum = [testValue intValue]; instead of using (int):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
NSNumber *testValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"kRestore"];
if (testValue){
NSLog(@"already");
viewController.myNum = [testValue intValue];
} else {
NSLog(@"empty");
viewController.myNum = 0;
}
return YES;
}
Then just use setObject:forKey: like so:
- (void)applicationWillResignActive:(UIApplication *)application {
NSNumber *num = [NSNumber numberWithInt:viewController.myNum];
[[NSUserDefaults standardUserDefaults] setObject:num forKey:@"kRestore"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"ok resign active");
}
A: Try changing your applicationWilLResignActive: method to:
NSNumber *num = [NSNumber numberWithInt:viewController.myNum];
[[NSUserDefaults standardUserDefaults] setObject:num forKey:@"kRestore"];
[[NSUserDefaults standardUserDefaults] synchronize];
Also, you can't cast an NSNumber instance to an int. In your application:didFinishLaunchWithOptions: method, change (int)testValue to [testValue intValue].
A: Calling -registerDefaults in applicationWillResignActive makes little sense. See my answer here on how registerDefaults works: How to register user defaults using NSUserDefaults without overwriting existing values?
You use it to set the default values. To save a value that is not the default but the users preference, use the various -set.. methods provided.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Which is easier, write a Custom OData uri parser or a custom IQueryable provider? I'm wanting to create an OData service that returns data from multiple sources. For this reason I cannot use WCF Data Services with any of the out-of-box providers, plus we really want more control over the data model.
I see we have two options if we stick with the MS product stack;
*
*Use WCF with WebGet/WebInvoke to mimic an OData api, and perform the query string parsing and translation internally. e.g. For cases where our data is in a Sql database we must translate the $filter clause into a SQL where clause in order to build our query. Note here that we cannot use any kind of ORM here, since our Data model is dynamic and we don't have any CLR entity classes that could be populated with an ORM.
*We use WCF Data Services with a Custom provider, this requires us to pass an IQueryable for the resource set, which leaves us with either doing a Select * FROM Table and using Linq to objects, or implementing our own IQueryable provider that supports the expressions required by OData. Will WCF Data Services even accept an IQuerable?
Which would be the easiest to implement? We mostly only want to support the $filter features of the OData spec, $expand and $select can come later.
It seems a shame to abandon WCF Data Services, it would be preferable if it could supply the parsed OData query that you could then translate to a Linq query yourself, rather than expecting your data source to have an IQueryable provider.
A: You can write your own data context class. The more functionality you need the greater the effort. The WCF Data Services Toolkit may be of some help and I found this OData Roadmap: Exposing Any Data Source as an OData service presentation from MIX to be helpful.
So I say writing a custom IQueryable provider would be both easier and cleaner.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Iterating through Struct members Lets say we have a struct
Struct myStruct
{
int var1;
int var2;
string var3;
.
.
}
Is it possible to to iterate through the structure's members by maybe using foreach? I have read some things on reflection, but I am not sure how to apply that here.
There are about 20 variables in the struct. I am trying to read values
off a file and trying to assign them to the variables but don't want
to call file.ReadLine() 20 times. I am trying to access the member
variables through a loop
A: You apply reflection in pretty much the same way as normal, using Type.GetFields:
MyStruct structValue = new MyStruct(...);
foreach (var field in typeof(MyStruct).GetFields(BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public))
{
Console.WriteLine("{0} = {1}", field.Name, field.GetValue(structValue));
}
Note that if the struct exposes properties (as it almost certainly should) you could use Type.GetProperties to get at those.
(As noted in comments, this may well not be a good thing to do in the first place, and in general I'm suspicious of user-defined structs, but I thought I'd include the actual answer anyway...)
EDIT: Now it seems you're interested in setting the fields, that's slightly more complicated due to the way value types work (and yes, this really shouldn't be a struct.) You'll want to box once, set values on the single boxed instance, and then unbox at the end:
object boxed = new MyStruct();
// Call FieldInfo.SetValue(boxed, newValue) etc
MyStruct unboxed = (MyStruct) boxed;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: PostgreSQL: top n entries per item in same table | uId | title | amount | makers | widgets |
1 richard 998 xcorp sprocket
2 swiss 995 ycorp framitz
3 ricky 90 zcorp flobber
4 ricky2 798 xcorp framitz
1 lilrick 390 xcorp sprocket
1 brie 200 mcorp gullywok
1 richard 190 rcorp flumitz
1 brie 490 bcorp sprocket
etc...
I am trying to retrieve only 3 records per makers, the top 3 amounts and the widgets they produced
Here's is what I have:
SELECT amount, makers FROM (SELECT amount, makers, (SELECT count(*) FROM entry as t2
WHERE t2.amount = t1.amount and t2.makers >= t1.makers) AS RowNum
FROM entry as t1
) t3
WHERE t3.RowNum<4 order by amount;
Is this returning what I actually need? Is there a better way to go about this? Most of the ways I have seen to do this kind of thing are doing joins etc on disparate tables, all the info I need is on one table.
Expected Output:
| uId | title | amounts | makers | widgets |
1 richard 998 xcorp sprocket
41 swiss 995 xcorp widget
989 richard 989 xcorp sprocket
22 swiss 995 ycorp framitz
92 swiss 990 ycorp widget
456 swiss 895 ycorp flobber
344 ricky 490 zcorp flobber
32 tricky 480 zcorp flobber
13 ricky 470 zcorp flobber
etc...
The order of the makers doesn't matter so much as getting the top 3 amounts for each makers, and the widgets they provided. The number of makers is set, there will always be x makers
A: SELECT *
FROM (
SELECT uid,
title,
amount,
maker,
widgets,
rank() over (partition by maker order by amount desc) as rank
FROM entry
) t
WHERE rank <= 3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to calculate the area of a layer in centimeters using photoshop I want to calculate the size of a layer area in centimeters using photoshop. Is there any tool to do so rather than the ruler? The layer I need to calculate the size of its area doesn't have a proper shape.
Thanks in advance
A: Make a selection and there is a INFO tab where you can see the size. You have to set the unit to centimeters in Preferences -> Units (pixels is the default setting).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MongoDB sort by subdocument count I have a document which looks something like:
{
"_id" : ObjectId("4e84f78b26d2046d5d00b5b2"),
"parent_id" : 0,
"ratings" : [
"20716",
"78167"
],
"text" : "test"
}
Is it possible to sort by the count of "ratings"? Doing something like:
db.comments.find().sort({rating.count(): -1})
throws an error:
SyntaxError: missing : after property id (shell):0
A: That's not directly possible with mongodb [1]
One solution, if you frequently use this query, is to increment and decrement a field 'count' each time you modify the ratings array and sort on that field.
You document will look like :
{
"_id" : ObjectId("4e84f78b26d2046d5d00b5b2"),
"parent_id" : 0,
"ratings" : [
"20716",
"78167"
],
count : 2
"text" : "test"
}
and you query with
db.comments.find().sort({count: -1})
A: There is a marked answer already, but I thought I'd add that this can be done using the aggregation framework:
db.comments.aggregate( [
{ $unwind: "$ratings" },
{ $group : { _id : { parent_id: "$parent_id", text: "$text" },
ratingsCount : { $sum : 1 } } },
{ $sort : { ratingsCount : -1 } }
] )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: What is this technique to resize the images proportionally used by google chrome new tab? I saw this code in Google Chrome Beta version's new tab where it show the icon if installed tabs.
They are using any technique to resize the images.
this is html of a icon
<div class="app-img-container launch-click-target" title="Box Office" style="height: 97.56981132075472px; width: 97.56981132075472px; ">
<img class="" src="chrome://extension-icon/dhbbohlkjglcppclgngklojecglglinl/128/0">
</div>
and it's css of related classes
.app-img-container {
margin-left: auto;
margin-right: auto;
-webkit-mask-size: 100% 100%;
}
.app-img-container > * {
height: 100%;
width: 100%;
}
Can anyone tell me which method they are using? Is it based on Javascript?
To check this you can install Google Chrome Beta and install some apps from chrome store then open a new tab in chrome. you will se the icons.
Note: it's only works in Beta version
This is the whole source of Tab page which I took from view source
http://jsbin.com/ikituc/edit#html
And this is rendred source which i copied from Chrome Developer tools HTML tab
http://jsbin.com/ekiqaf/edit#html
I want to know the method which is being used to re-size the icons.
A: What do you mean by resizable? There is no resizable icon here in Canary. If you mean resizing from small icons to big icons I should say there is two different icons for every app. For example for Angry Birds:
chrome://extension-icon/aknpkdffaafgjchaibgeefbgmgeghloj/16/1
chrome://extension-icon/aknpkdffaafgjchaibgeefbgmgeghloj/128/0
Any other "resize" is because of CSS3 transitions
A: The method is surely based on javascrip.
If you take a look at the calculateLayout_ method you will understand why :)
A: Its a JS + CSS powered solution.
<div class="app-img-container launch-click-target" title="Chrome Web Store"
style="height: 67.98490566037735px; width: 67.98490566037735px; ">
<img class="" src="chrome://theme/IDR_WEBSTORE_ICON">
<img class="apps-promo-logo">
</div>
chrome://newtab/ source:
.app-img-container > * {
height: 100%;
width: 100%;
}
They set the width of .app-img-container programatically, image gets this width with CSS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: jQuery closest behaviour in IE very slow I have a table with 5000 rows. In each row I have an html element. myElementList is the list of those elements. Now I need to select all the tr's of these elements. I am using the following code.
myElementList.closest('tr');
This work great in FF. But when I run the same in IE 8. The browser hangs out and a popup messgae appears that propmt for to stop the script.
Any suggestion why I am seeing this behaviour or thier is any alternative.
Edit:
The behaviour remains same when I use parents()
myElementList.parents('tr');
A: To get what you wish fairly snappy (the closest parent tr to every checked checkbox) you'd could do something like this:
$.fn.extend({
closestByTagName: function(tagname) {
var tag = tagname.toUpperCase(), i = this.length, node, found=[], trParents;
while(i--) {
node = this[i];
while((node=node.parentNode) && node.nodeName != tag);
if(node) {
found[found.length] = node;
}
}
return $(found);
}
});
var result = $('input:checked').closestByTagName('tr');
It isn't pretty, but i can't think of a faster way. (it should beat jQuery by a wide margin)
A: Try using parent(), child(), next(), prev() selectors. I'm not 100% on how exactly jQuery traverses the table to find the tr but 5,000 rows is a lot of traversing. Being more specific would make the js engine do less work.
http://api.jquery.com/category/traversing/
$('input:checked').parent('tr').each(function(i){....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Callback function for JSONP with jQuery AJAX I didn't quite understand how to work with the callback for the ajax function of jQuery.
I have the following code in the JavaScript:
try {
$.ajax({
url: 'http://url.of.my.server/submit?callback=?',
cache: false,
type: 'POST',
data: $("#survey").serialize(),
dataType: "jsonp",
timeout: 200,
crossDomain: true,
jsonp: 'jsonp_callback',
success: function (data, status) {
mySurvey.closePopup();
},
error: function (xOptions, textStatus) {
mySurvey.closePopup();
}
});
} catch (err) {
mySurvey.closePopup();
}
And on the server side (AppEngine / Python) I get the value of the callback parameter and respond with
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
self.response.out.write(callback + '({"msg": "ok"});')
But then I get an "Error: jQuery152042227689944248825_1317400799214 is not a function" in the browser console.
What is the proper way to handle this? Right now I get the results that I need, but the fact that I know it's not right is bothering me.
A: This is what I do on mine
$(document).ready(function() {
if ($('#userForm').valid()) {
var formData = $("#userForm").serializeArray();
$.ajax({
url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
type: "GET",
data: formData,
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
});
function localJsonpCallback(json) {
if (!json.Error) {
$('#resultForm').submit();
} else {
$('#loading').hide();
$('#userForm').show();
alert(json.Message);
}
}
A: delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=? and then telling jQuery that you want to use jsonp_callback instead.
A: $.ajax({
url: 'http://url.of.my.server/submit',
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'jsonp_callback'
});
jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:
url: 'http://url.of.my.server/submit?callback=?'
the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.
$.ajax({
url: 'http://url.of.my.server/submit?callback=?',
success: function (data, status) {
mySurvey.closePopup();
},
error: function (xOptions, textStatus) {
mySurvey.closePopup();
}
});
The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:
$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: Get variables show up in sub-sub directory rewrites, .htaccess, mod_rewrite Here is my .htaccess:
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ([^/]+/.*) index.php?dir=%{REQUEST_URI}
The htaccess lives in test.com/main/.htaccess
I can access test.com/main/ and test.com/index.php fine
test.com/main/directory gets rewritten to test.com/main/index.php?dir=/main/directory/ BUT test.com/main/directory stays in the url bar. This is good.
The problem is when I try to access sub-sub directories. When I access test.com/main/foler1/folder2 it gets rewritten to index.php?dir=/main/folder1/folder2/. This is also good, however test.com/main/folder1/folder2/?dir=/main/folder1/folder2/ shows up in the address bar instead of keeping test.com/main/folder1/folder2 in the url bar. This is the problem.
I want all sub directories, not just the direct children of main to keep the directory in the url bar while rewriting. The direct children do this fine, but any directories under that rewrite in a way where my get variables show up.
The purpose of this rewrite is so I don't have to copy in an index.php file into every newly created folder so copying the .htaccess into each folder defeats the purpose.
A: You probably want RewriteRule ([^/]+/.*) index.php?dir=%{REQUEST_URI} [QSA,L] (The L prevents mod rewrite from processing any further rules if the rule is successful) QSA appends any query string which may have been passed in.
Update:
The issue is that the server is rewriting the URL without the slash (visibly) as the URL with the slash, and including your rewrite rule as part of that. The way around that would be to only process the rule when the URL ends with a slash eg:
RewriteRule ([^/]+/.*/$) index.php?dir=%{REQUEST_URI} [QSA,L]
This way it will do the rewrite in two separate steps:
*
*Add the slash visibly.
*Rewrite using your rule to index.php
Instead of:
*
*Add the slash and rewrite to index.php visibly.
A: I'll add the solution I found while testing mootinator's solution.
Instead of linking to
test.com/main/foler1/folder2
link to
test.com/main/foler1/folder2/ (Include the slash!)
Redirection will successfully redirect to
index.php?dir=/main/folder1/folder2/
while
test.com/main/foler1/folder2/
stays in the url bar.
It's a somewhat hackish solution but it should work just fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pop up when back arrow hit on IE, using javascript I created a button using javascript, which upon hitting would use the history.go(-1) JavaScript function and also pop up a window. hitting the back button on IE already has the built in feature of going back one step into the history, but I also need the pop up to show when a user hits the back button.
Can someone help me with this?
Thanks
A: This is a touchy subject on SO (as it should be). Typically, when a programmer wants to see if the user is clicking the back button or leaving the page, it's for a malicious purpose. Because I think much better of you, user583227, I'll get you started in the right direction: How to detect if the user clicked the "back" button
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Traffic Performance Testing Webpages Under Specified Conditions As the title implies, I would like to be able to simulate traffic to a collection of webpages that I have created for loadbalancing and bottleneck issues. I would like to mimic typical HTTP requests relative to the upload/download speed of the user. Furthermore, I would like to be able to perform extreme tests assuming a certain amount of storage and bandwidth on a server(s).
How I should go about doing this?
A: Look at Apache Flood: hhttp://httpd.apache.org/test/flood/
Good description: http://www.clove.org/flood-presentation/flood.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using PHP $_COOKIE to manage session vars Due to server settings I am having to use $_COOKIE instead of $_SESSION to manage session vars for a project.
On my search form I set an initial cookie but am unclear whether this is helpful or needed?
setcookie('NOSG', 'oHai', time()+7200, '/', 'some.org');
Each time the search results page loads I iterate over the cookies and back date the ones I need to clear and then set the new values like so:
if ($board) {
foreach ($_COOKIE as $k => $v) {
if (preg_match('/boa_/', $k)) {
setcookie($k, '', time()-3600, '/', 'some.org');
}
}
foreach ($people as $p) {
setcookie('boa_'.$p->ID, $p->whatever, time()+7200, '/', 'some.org');
}
}
Mostly this is used for making sticky selections in multi-line <SELECT> inputs.
Is this approach sound? I have rarely used $_COOKIE for anything.
// EDIT 1:12 PM GMT-06:00
All of the comments and answers are focused on fixing sessions. I assume this is because there is some reason the method suggested is NOT sound? The question asked is about using $_COOKIE to remember form settings. Would anyone care to respond as to why the method I am using is or is not appropriate to the problem?
A: The error
Permission denied. session.save_path is set to /var/lib/php/session PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0
Is due to an error on the part of your host/system administrator. They should set the permissions on /var/lib/php/session to 777 so it is writable by all users. If they are using something that executes your PHP script as your user, the data is still safe because your user will own the session data file so no one else can view or modify it.
Alternatively, you can change the session save path on the fly to a directory under your control.
If you were to have a common file that initiated your session, add this before session_start():
session_save_path('/home/yoursite/sessions');
// or
session_save_path($_SERVER['DOCUMENT_ROOT'] . '../sessions');
// or, an alternate method
ini_set('session.save_path', '/home/yoursite/sessions');
session_start();
Then just created that folder and set the permissions appropriately so it is readable/writable by your user only.
A: Technically all a session is, is a text file (OK, you can hold the data in a database as well) containing variables that's identified by a value held in a cookie (or the address bar).
It wouldn't be impossible to recreate the functionality within PHP using things like setcookie(), serialize() and file_put_contents() writing to a folder outside the web tree ... though you might also need a Cron job to schedule garbage collection (to be fair, PHPs native session GC doesn't seem to be spectacular).
You'd just need to create a custom session handling object and set the "session" id for it in a cookie exactly the same as if you were using normal session handling - except instead of using $_SESSION you'd use you Session::get() and Session::set() methods.
If you keep the API clean then, at a future date if you manage to get session handling enabled on the server, you'd only need to tweak your session handling object and it wouldn't affect the rest of your program code - it's probably a good idea to abstract away then session handling anyway.
A: None of the respondents addressed my question: Is using $_COOKIE to store session data a sound method?
Experience has taught me what they would not. Not all browsers handle cookies in the same way. For instance Internet Explorer has limits per domain on the number of cookies: http://support.microsoft.com/kb/941495
So the answer is- $_SESSION is superior to cookies as it is handled by PHP in the same manner for all browsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I use TADOQuery.Parameters with integer parameter types that have to be put in two or more places in a query? I have a complex query that contains more than one place where the same primary key value must be substituted. It looks like this:
select Foo.Id,
Foo.BearBaitId,
Foo.LinkType,
Foo.BugId,
Foo.GooNum,
Foo.WorkOrderId,
(case when Goo.ZenID is null or Goo.ZenID=0 then
IsNull(dbo.EmptyToNull(Bar.FanName),dbo.EmptyToNull(Bar.BazName))+' '+Bar.Strength else
'@'+BarZen.Description end) as Description,
Foo.Init,
Foo.DateCreated,
Foo.DateChanged,
Bug.LastName,
Bug.FirstName,
Goo.BarID,
(case when Goo.ZenID is null or Goo.ZenID=0 then
IsNull(dbo.EmptyToNull(Bar.BazName),dbo.EmptyToNull(Bar.FanName))+' '+Bar.Strength else
'@'+BarZen.Description end) as BazName,
GooTracking.Status as GooTrackingStatus
from
Foo
inner join Bug on (Foo.BugId=Bug.Id)
inner join Goo on (Foo.GooNum=Goo.GooNum)
left join Bar on (Bar.Id=Goo.BarID)
left join BarZen on (Goo.ZenID=BarZen.ID)
inner join GooTracking on(Goo.GooNum=GooTracking.GooNum )
where (BearBaitId = :aBaitid)
UNION
select Foo.Id,
Foo.BearBaitId,
Foo.LinkType,
Foo.BugId,
Foo.GooNum,
Foo.WorkOrderId,
Foo.Description,
Foo.Init,
Foo.DateCreated,
Foo.DateChanged,
Bug.LastName,
Bug.FirstName,
0,
NULL,
0
from Foo
inner join Bug on (Foo.BugId=Bug.Id)
where (LinkType=0) and (BearBaitId= :aBaitid )
order by BearBaitId,LinkType desc, GooNum
When I try to use an integer parameter on this non-trivial query, it seems impossible to me. I get this error:
Error
Incorrect syntax near ':'.
The query works fine if I take out the :aBaitid and substitute a literal 1.
Is there something else I can do to this query above? When I test with simple tests like this:
select * from foo where id = :anid
These simple cases work fine. The component is TADOQuery, and it works fine until you add any :parameters to the SQL string.
Update: when I use the following code at runtime, the parameter substitutions are actually done (some glitch in the ADO components is worked around) and a different error surfaces:
adoFooContentQuery.Parameters.FindParam('aBaitId').Value := 1;
adoFooContentQuery.Active := true;
Now the error changes to:
Incorrect syntax near the keyword 'inner''.
Note again, that this error goes away if I simply stop using the parameter substitution feature.
Update2: The accepted answer suggests I have to find two different copies of the parameter with the same name, which bothered me so I reworked the query like this:
DECLARE @aVar int;
SET @aVar = :aBaitid;
SELECT ....(long query here)
Then I used @aVar throughout the script where needed, to avoid the repeated use of :aBaitId. (If the number of times the parameter value is used changes, I don't want to have to find all parameters matching a name, and replace them).
I suppose a helper-function like this would be fine too: SetAllParamsNamed(aQuery:TAdoQuery; aName:String;aValue:Variant)
A: FindParam only finds one parameter, while you have two with the same name. Delphi dataset adds each parameter as a separate one to its collection of parameters.
It should work if you loop through all parameters, check if the name matches, and set the value of each one that matches, although I normally choose to give each same parameter a follow-up number to distingish between them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: link color is stuck on active (blue) Hihi,
I have a problem with three links in the same div... the ugly default blue link color is blocking the assigned font-color to take over
URL: http://nicejob.is/clients/pizzahollin/www/menu.htm
Any help would be nice - typical it´s just a typo but I´ve tried everything
A: At least from what I can see, you don't have any defaults set for a, which would be why the browser is handling it.
And if you're expecting this to, then yes, you have a typo in main.css
.font-filer a { color:#997f62; }
needs to be
.font-filter a { color:#997f62; }
A: You set the font-color on the surrounding p but not on the a itself. Try explicitly setting a color for the link.
<!-- In the stylesheet, you set explicit color for p -->
<p class="font-filter">
<!-- and not for a, so it's using default -->
<a title="most-popular" href="#most-popular">
<cufon class="cufon cufon-canvas" alt="Vinsælustu" style="width: 145px; height: 34px;">
<canvas width="158" height="36" style="width: 158px; height: 36px; top: -2px; left: -1px;"></canvas>
<cufontext>Vinsælustu</cufontext>
</cufon>
</a>
</p>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to edit the implode so it will join values with two strings? In the function below a possible output maybe
1 day and 2 hours and 34 minutes
My question is how do I edit the implode so it will output
1 day, 2 houts and 34 minutes
This is my function
function time_difference($endtime){
$hours = (int)date("G",$endtime);
$mins = (int)date("i",$endtime);
// join the values
$diff = implode(' and ', $diff);
if (($hours == 0 ) && ($mins == 0)) {
$diff = "few seconds ago";
}
return $diff;
}
A: Something like this?
function implodeEx($glue, $pieces, $glueEx = null)
{
if ($glueEx === null)
return implode($glue, $pieces);
$c = count($pieces);
if ($c <= 2)
return implode($glueEx, $pieces);
$lastPiece = array_pop($pieces);
return implode($glue, array_splice($pieces, 0, $c - 1)) . $glueEx . $lastPiece;
}
$a = array('a', 'b', 'c', 'd', 'e');
echo implodeEx(',', $a, ' and ');
A: There are a lot of places for x-time-ago functions. here are two in PHP. Here's one in Javascript.
A: I would do something like:
if ($days) {
$diff .= "$days day";
$diff .= $days > 1 ? "s" : "";
}
if ($hours) {
$diff .= $diff ? ", " : "";
$diff .= "$hours hour";
$diff .= $hours > 1 ? "s" : "";
}
if ($mins) {
$diff .= $diff ? " and " : "";
$diff .= "$mins minute";
$diff .= $mins > 1 ? "s" : "";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: running Mathematica remotely on macs Here is what I want to do:
I want to run Mathematica on another Mac from my Mac (both Snow Leopards). I want to do this because the remote Mac has multiple cores/processors while my local Mac is rather shabby. I would like to have the front end still locally (i.e. the graphical interface).
What I've learned:
I used to do this type of thing from multiple Linux machines and was expecting to have similar success for Mac-to-Mac operation. However no such luck.
The problem seems to be a display issue (front end).
Mac front end runs in Aqua while X11 is what is really needed (this is why there is no problem on Unix). While Macs have X11, for some reason Mathematica can't use it.
So how do I get around this issue?
Possible solutions that I have had to rule out are: 1. screen sharing. Not practical since someone else will be using the remote Mac on another account. Screen sharing only uses the active screen. 2. Installing Unix on the remote computer. Not possible in my situation.
Thanks.
A: You should be able to set up a remote kernel on the other Mac. This is done through the Evaluation > Kernel Configurations menu item. The you can set the remote kernel for a given notebook using Evaluation > Notebook's Kernel or globally via Evaluation > Default Kernel.
I haven't done this in a while, and it's sometimes useful to test things from a terminal with something like
ssh <user>@<remote.machine.com> </path/to/remote/Mathematica.app/Contents/MacOS/MathKernel>
A: Why not use the command line kernel? I have a script math which does:
#!/bin/bash
rlwrap /Applications/Mathematica.app/Contents/MacOS/MathKernel
I built rlwrap from source, but basically that tool gives you readline behaviors. You can just do
ssh remote-machine /Applications/Mathematica.app/Contents/MacOS/MathKernel
A: The only solution, I believe, is for you to upgrade to OS X Lion. It allows simultaneous screen sharing sessions where each user can control the screen for their own account:
http://www.apple.com/macosx/whats-new/features.html#screensharing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to check if a user installed the app? I have an app on facebook, which is kind of a competition between users. Each user gains points and the one with most points wins.
I keep the IDs of the users in a table in my database. When a user enters the app, there's a script that checks if he is already in the table, and if not, it adds the user id to the table.
Then, I have a page that shows all of the users and how many points they have. I get through the graph api the user's name by his ID, and then shows it on a nice table.
The only problem is: when a user that used the application once deletes it from his installed application on facebook, I can't get his name anymore, and I get an uncaught OAuth exception.
How can I check if the user has installed the app, so I can display his name only if the app is currently installed on his facebook?
A: Basically, here is what you would need to do.
<?php
include_once("facebook.php");
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
));
$user = $facebook->getUser();
try {
$user_profile = $facebook->api('/me');
} catch(FacebookApiException $e) {
$user = null;
}
if($user) {
// authenticated user
$name = $user_profile['name'];
}
This makes an API request for the current logged in user and, provided it fails, catches the exception and sets the $user variable to null. Then you can do a simple check to see if $user exists.
Hopefully this will point you in the right direction.
A: I would like to suggest to check this client side.
Then when a user returns you can execute this to see if the permissions are still available, and if not request them again:
FB.getLoginStatus(function(response){
if(response.status == 'connected'){
appisinstalled-actonthis();
}else{
// request permissions
FB.login(function(response){
if(response.status == 'connected'){
appisinstalled-actonthis();
}else{
handlethecancelpermissions();
}
});
}
});
Within your appisinstalled-actonthis function you can then add there name and/or profile pic
Just my two cents!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Data Mining situation Suppose I have the data as mentioned below.
11AM user1 Brush
11:05AM user1 Prep Brakfast
11:10AM user1 eat Breakfast
11:15AM user1 Take bath
11:30AM user1 Leave for office
12PM user2 Brush
12:05PM user2 Prep Brakfast
12:10PM user2 eat Breakfast
12:15PM user2 Take bath
12:30PM user2 Leave for office
11AM user3 Take bath
11:05AM user3 Prep Brakfast
11:10AM user3 Brush
11:15AM user3 eat Breakfast
11:30AM user3 Leave for office
12PM user4 Take bath
12:05PM user4 Prep Brakfast
12:10PM user4 Brush
12:15PM user4 eat Breakfast
12:30PM user4 Leave for office
This data tell me about the daily routine of different people. From this data it seems user1 and user2 behave similarly (though there is a difference in time they perform the activity but they are following the same sequence). With the same reason, User3 and User4 behave similarly.
Now I have to group such users into different groups. In this example, group1- user1 and USer2 ... followed by group2 including user3 and user4
How should I approach this kind of situation. I am trying to learn data mining and this is an example I thought of as a data mining problem. I am trying to find an approach for the solution, but I can not think of one. I believe this data has the pattern in it. but I am not able to think of the approach which can reveal it.
Also, I have to map this approach on the dataset I have, which is pretty huge but similar to this :) The data is about logs stating occurrence of events at a time. And I want to find the groups representing similar sequence of events.
Any pointers would be appreciated.
A: It looks like clustering on top of associating mining, more precisely Apriori algorithm. Something like this:
*
*Mine all possible associations between actions, i.e. sequences Bush -> Prep Breakfast, Prep Breakfast -> Eat Breakfast, ..., Bush -> Prep Breakfast -> Eat Breakfast, etc. Every pair, triplet, quadruple, etc. you can find in your data.
*Make separate attribute from each such sequence. For better performance add boost of 2 for pair attributes, 3 for triplets and so on.
*At this moment you must have an attribute vector with corresponding boost vector. You can calculate feature vector for each user: set 1 * boost at each position in the vector if this sequence exists in user actions and 0 otherwise). You will get vector representation of each user.
*On this vectors use clustering algorithm that fits your needs better. Each found class is the group you use.
Example:
Let's mark all actions as letters:
a - Brush
b - Prep Breakfast
c - East Breakfast
d - Take Bath
...
Your attributes will look like
a1: a->b
a2: a->c
a3: a->d
...
a10: b->a
a11: b->c
a12: b->d
...
a30: a->b->c->d
a31: a->b->d->c
...
User feature vectors in this case will be:
attributes = a1, a2, a3, a4, ..., a10, a11, a12, ..., a30, a31, ...
user1 = 1, 0, 0, 0, ..., 0, 1, 0, ..., 4, 0, ...
user2 = 1, 0, 0, 0, ..., 0, 1, 0, ..., 4, 0, ...
user3 = 0, 0, 0, 0, ..., 0, 0, 0, ..., 0, 0, ...
To compare 2 users some distance measure is needed. The simplest one is cosine distance, that is just value of cosine between 2 feature vectors. If 2 users have exactly the same sequence of actions, their similarity will equal 1. If they have nothing common - their similarity will be 0.
With distance measure use clustering algorithm (say, k-means) to make groups of users.
A: Using an itemset mining algorithm like Apriori as proposed in the other answer is not the best solution because Apriori does not consider time or the sequential ordering. Thus, it requires to do an additional pre-processing step to consider ordering.
A better solution is to use a sequential pattern mining algorithm like PrefixSpan, SPADE, or CM-SPADE directly. A sequential pattern mining algorithm will directly find subsequences that appears often in a set of sequences.
Then you can still apply clustering on the sequential patterns found!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Creating an Html.ActionLink to a dynamic content page I have functionality on my site to create/edit/delete pages for the front end. Here's my controller:
namespace MySite.Controllers
{
public class ContentPagesController : Controller
{
readonly IContentPagesRepository _contentPagesRepository;
public ContentPagesController()
{
MyDBEntities entities = new MyDBEntities();
_contentPagesRepository = new SqlContentPagesRepository(entities);
}
public ActionResult Index(string name)
{
var contentPage = _contentPagesRepository.GetContentPage(name);
if (contentPage != null)
{
return View(new ContentPageViewModel
{
ContentPageId = contentPage.ContentPageID,
Name = contentPage.Name,
Title = contentPage.Title,
Content = contentPage.Content
});
}
throw new HttpException(404, "");
}
}
}
And in my global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Page", // Route name
"Page/{name}", // URL with parameters
new { controller = "ContentPages", action = "Index" }, // Parameter defaults
new[] { "MySite.Controllers" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new[] { "MySite.Controllers" }
);
}
So I have a dynamic page in my database, named About. If I go to mysite.com/Page/About, I can view the dynamic content.
I want to create an ActionLink to this page. I've tried it like this:
@Html.ActionLink("About Us", "Index", "ContentPages", new { name = "About" })
But when I look at the link on the page, the url just goes to the current page with Length=12 in the query string. For instance, if I'm on the homepage, the link goes to mysite.com/Home?Length=12
What am I doing wrong here?
A: You are not using the correct ActionLink overload. Try like this:
@Html.ActionLink(
"About Us", // linkText
"Index", // action
"ContentPages", // controller
new { name = "About" }, // routeValues
null // htmlAttributes
)
whereas in your example:
@Html.ActionLink(
"About Us", // linkText
"Index", // action
"ContentPages", // routeValues
new { name = "About" } // htmlAttributes
)
which pretty obviously explains why your doesn't generate the expected link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to submit file, loop only over form elements having name in jqgrid How to implement file upload in jqGrid using dataProxy from http://jqgrid-php.net below?
Running code below causes exception
Unable to get value of the property 'removeAttr': object is null or undefined
at line
$(this).data('name', $(this).attr('name')).removeAttr('name');
as show in comment in code.
It looks like ele (form) contains elements without name which causes this exception.
How to fix this code ?
How to change this code so that it loops (saves/restores name) only over elements which have name.
var dataProxyAjax = function (opts, act) { // from http://jqgrid-php.net
opts.url = $(this).getGridParam('url');
//use normal ajax-call for del
if (act.substring(0, 4) == 'del_') {
$.ajax(opts);
}
opts.iframe = true;
var $form = $('#FrmGrid_' + $(this).getGridParam('id'));
var ele = $form.find('INPUT,TEXTAREA').not(':file');
//Prevent non-file inputs double serialization
ele.each(function () {
// todo: how to fix the error: Unable to get value of the property 'removeAttr': object is null or undefined
$(this).data('name', $(this).attr('name')).removeAttr('name');
});
//Send only previously generated data + files
$form.ajaxSubmit(opts);
//Set names back after form being submitted
setTimeout(function () {
ele.each(function () {
$(this).attr('name', $(this).data('name'));
});
}, 200);
};
A: you are trying to set the value of something that isnt a value. removeAttr just removes the attr...it seems like you are trying to set the data of 'name' for (this) element to be equal to (this) but with the attr 'name' removed. I'm not sure that makes a lot of sense.
try:
ele.each(function () {
// todo: how to fix the error: Unable to get value of the property 'removeAttr': object is null or undefined
var theName = $(this).attr('name');
$(this).removeAttr('name');
$(this).data('name', theName);
});
A: Not exactly sure what you're trying to do but hopefully this helps explain your problem.
How to change this code so that it loops (saves/restores name) only over elements which have name.
ele.each(function () {
// "only over elements which have name"
if ($(this).hasAttr('name')) {
// if it has a name do something with it
}
});
However, if an HTML object doesn't have a name it won't throw an exception, it will just appear as undefined. Shown here: http://jsfiddle.net/ZF3uC/1/
$(this).data('name', $(this).attr('name')).removeAttr('name');
This is throwing the exception because what you're doing here is saying, give me the name property of the name attribute of the HTML element stored in $(this) then remove that attribute.
The problem is the name attribute doesn't exist so $(this).data('name', $(this).attr('name')) is returning an undefined object which has no method called removeAttr
You can see how this is happening here http://jsfiddle.net/ZF3uC/5/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Binding to Class Item This seems like it should be really basic but I can't seemto get it working.
I have a class file called XMLSource as follows:
Public Class XMLSource
Public Shared BrandItems As New MediaItems
Public Class MediaItems
Inherits ObservableCollection(Of MediaObject)
Implements INotifyPropertyChanged
End Class
End Class
Public Class MediaObject
Public Property Name As String
Public Property Title As String
End Class
The application reads an XML file and stores some items into XMLSource.BrandItems (happens on start-up).
I want to bind a Label control's Content property to XMLSource.BrandItems(0).Name
I tried:
<Label Content="{Binding Source={XMLSource},Path=.BrandItems[0].Src}" FontSize="20"></Label>
But it's not working.
Is it possible to bind directly like this?
A: You cannot contruct bindings like this, if you write {} that indicates a markup extension, further you cannot have static/shared members in a binding path. I think the correct binding would be:
{Binding [0].Src, Source={x:Static ns:XMLSource.BrandItems}}
x:Static is a markup extension which allows access of static members. (Note that this also allows access of fields unlike the Path which only allows public properties)
Where ns is declared in an xmlns attribute and points to the namespace of your XMLSource class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PKCS#11 TLS Authentication I am new to PKCS#11 and Common Access Cards but as I understand it, on the card you have the certificates(s) that can be extracted and the private key(s) that can't. I am trying to write an app that communicates with a web server that requires certificates for authentication. The PKCS library provided from the hardware vendor is pretty thin. I can essentially access the certificate object or sign data using the on-card private key.
What I am unsure of how I handle the handshake and such when connecting to the webserver. Am I supposed to provide the certificate along with something else signed by the private key? If so, what is it that I sign with the private key? I have Googled this but have been unable find some kind of explanation for this process.
A: If you are using an RSA key on the common access card for authentication, you'll need to send a CertificateVerify message in the handshake, which contains digital signatures over the handshake records to that point. You'll also need to send the client certificate, of course. See §7.4.8 of the TLS specification for details.
Hopefully, your TLS library supports the use of a PKCS #11 cryptographic module. If not, you might have to switch. Implementing TLS yourself when you aren't familiar with the specification is unreasonable.
A: I think you just need to retrieve your client certificate from your PKCS#11 device and then use it along the request you are making to web server. You don't need to implement SSL if you use existing libraries. They should contain all you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tetrahedralization visualization Octave Hi does anyone know how to visualize the tetrahedrons in the output of the delaunay3() function in Octave?
http://www.obihiro.ac.jp/~suzukim/masuda/octave/html3/octave_151.html
In MATLAB this visualization is done with the tetramesh() function but Octave does not have this function built in!
The link does mention the triplot and trimesh functions but they only create triangles, not tetrahedra.
A: Unfortunately, I don't know enough about this to give any thoughts on it. But, I would like to mention the following, in case you hadn't seen it before. There have been discussions on tetramesh before. A quick solution was written up by martin_helm:
function tetramesh( T, X, C)
if nargin < 3
C = mod((1:size(T, 1))'-1, size(colormap(), 1) + 1);
endif
triang = [T(:, 1) T(:, 2) T(:, 3); ...
T(:, 2) T(:, 3) T(:, 4); ...
T(:, 3) T(:, 4) T(:, 1); ...
T(:, 4) T(:, 1) T(:, 2)];
patch("Faces", triang, "Vertices", X, "FaceVertexCData", [C; C; C; C])
endfunction
Along with some example usage:
backend("fltk") % backend("gnuplot") could also be used
d = [-1 1];
[x,y,z] = meshgrid(d,d,d);
x = [x(:);0];
y = [y(:);0];
z = [z(:);0];
tetra = delaunay3(x,y,z);
X = [x(:) y(:) z(:)];
tetramesh(tetra, X)
view(30,30)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to delete CallLogs from blackberry Device Programatically I use 'CallLogs.deleteCall(position,FolderType);'
But it can't delete the record.
Please help me to solve this problem.
PhoneLogs _logs = PhoneLogs.getInstance();
int len = _logs.numberOfCalls(_logs.FOLDER_NORMAL_CALLS);
for (int i = 0; i < len; i++) {
_logs.deleteCall(i, _logs.FOLDER_NORMAL_CALLS);
}
A: This question has been answered in the Blackberry Support forms and you can get a solution there. It is a thread issue and problem in the RIM API. Please follow this thread it is suggested by RIM adviser
Deleting call logs, Waiting is the solution
and
Delete of phonelog
If you have more doubts in blackberry come here i will explain click here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between console and winforms applications when running from cmd I have a winforms application that sometimes used from the command line.
Here is the code (simplified of course):
[STAThread]
static void Main()
{
AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("Hello");
/*Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());*/
}
If that was a console application the output could be:
C:\ConsoleApplication\ConsoleApplication.exe
Hello
C:\ConsoleApplication\_
In case of windows application its actually:
C:\WindowsApplication\WindowsApplication.exe
C:\WindowsApplication\Hello
_
Can anyone tell me why do we have such difference and is it possible to make my windows application to behave like console when running from cmd?
edit:
I want my windows application to behave like console when running from cmd:
C:\WindowsApplication\WindowsApplication.exe
Hello
C:\WindowsApplication\_
solution:
As a result I'm running my application as
C:\WindowsApplication\start /wait WindowsApplication.exe
A: There is a flag in the exe, telling if this is a console app or gui (winform in your case) app. When you start an app, Windows will detach the console from the program if it is a console app. You can use the following approach to achieve what you want:
*
*Compile you application as gui, name it mytool.exe
*Create a doskey alias mytool=start /wait c:\path\mytool.exe $*
In this way, when you start mytool.exe in explorer or shortcut, you start a normal windows application; when you type in mytool in console, you actually start it by "start /wait", which will not detach the console regard less of the flag. (However, you do need to attach to parent console in your app if you want to output/input something from the console.
A: Yes. The difference is that cmd.exe is aware of the kind of executable. It knows to wait for the process to terminate when it is a console mode app. It does not wait when it is a regular Windows gui app. Trusting that it will create its own window. So it displays the command prompt again, your output gets appended to that. You'll also have trouble using Console.ReadLine() btw.
You'd have to start your program with start /wait yourapp.exe to force cmd.exe to wait. Calling AllocConsole() instead is the only universal fix. Also takes care of creating the console when your app gets started from a shortcut.
AllocConsole() is fairly disorienting. Consider writing a tiny console mode app that does nothing but Process.Start + WaitForExit to start your main program. Perhaps also munging the command line arguments. Now you get the blocking behavior back. If you rename the executable to mainapp.com (to start mainapp.exe) then the difference is hidden quite well, a trick that VS uses as well (devenv.exe vs devenv.com).
A: You want the Windows App to block the Console thread as long as it's running, if I understand you correctly. I have no idea why you would do that, but I can give a shot at how it might work:
Change the WinForms application to a console application, that opens a form. This way it would block the console thread while displaying a window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: merge changes in a single file from multiple branches I have a git repo with two divergent branches, production and v2. I'm working on a third branch with a collaborator that we're merging into called prod-merge. The idea is that v2 has a ton of feature updates and production was a series of bug fixes/patches.
So now v2 should more or less be canonical but I need to merge in the changes from my production branch.
My collaborator and I have split up the workflow such that I'm in charge of merging the 'foo' namespace and he's in charge of merging in the 'bar' namespace. Said another way, I'm responsible for merging in the production branch, foo.rb file. There are several files for each of us.
I've been playing with diff,merge,patch and am without finding a workflow that feels really solid. I'd like a three way merge to make sure I don't miss anything and then commit that merge. What's the simplest solution that could work?
thanks,
Bryce
A: there must be a better way, but I found this to do just the trick:
git format-patch --stdout feature..master -- app/controllers/feeds_controller.rb > ~/Desktop/feeds.patch
git am -3 -i --ignore-date ~/Desktop/feeds.patch
A: We have lots of very complex branches, branch ownership scenarios, etc. I've documented the approach here. Hope this gives you some good ideas.
https://plus.google.com/109096274754593704906/posts/R4qkeyRadLR
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Windows Installer from .Net 2.0 Custom Action to .Net 4.0 Custom Action - BadImageFormatException I'm having a problem with an application that I recently upgraded from .Net 2.0 to .Net 4.0. During installation, the custom action starts to execute and throws an error.
=== Logging started: 9/30/2011 2:34:09 ===
Error 1001. Error 1001. Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\Program Files\MyPath\MyCustomAction.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded..
=== Logging stopped: 9/30/2011 2:34:30 ===
Note that should I uninstall the old version of the application first, then install the new version of the application, the installation succeeds without error.
The only thing I can guess is that the .Net 2.0 custom action is failing to be loaded by Windows Installer as it's not the same .Net 4.0 framework as used by the latest version of my application. Has anyone run into this?
A: You've got to set the condition for the runtime in the vdproj (it doesn't update with your custom action project):
http://msdn.microsoft.com/en-us/library/kz0ke5xt.aspx
In Solution Explorer, click the Setup project.
On the View menu, point to Editor, and then click Launch Conditions.
Click .NET Framework.
In the Properties window, change the Version property to the version of the .NET Framework that you want the Setup project to check for and install.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: "bundle install" fails when setting :git path in Gemfile I want to update one of my gems from the master source branch instead of from a gem repo. So I put this in my Gemfile:
gem "prawn", :git => "https://github.com/sandal/prawn.git"
However, now when I run:
bundle install
or:
bundle update
I get:
Updating https://github.com/sandal/prawn.git
syntax error on line 42, col 0: `end'
/Users/me/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/1.8/yaml.rb:137:in `load': undefined method `path' for #<String:0x101aa83c0> (NoMethodError)
from /Users/me/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/specification.rb:480:in `from_yaml'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler.rb:238:in `load_gemspec'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler.rb:235:in `chdir'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler.rb:235:in `load_gemspec'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/source.rb:353:in `load_spec_files'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/source.rb:352:in `each'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/source.rb:352:in `load_spec_files'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/source.rb:570:in `load_spec_files'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/source.rb:385:in `local_specs'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/source.rb:555:in `specs'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/definition.rb:356:in `converge_locked_specs'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/definition.rb:345:in `each'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/definition.rb:345:in `converge_locked_specs'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/definition.rb:143:in `resolve'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/definition.rb:90:in `specs'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/definition.rb:85:in `resolve_remotely!'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/installer.rb:43:in `run'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/installer.rb:8:in `install'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/cli.rb:219:in `install'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/vendor/thor/task.rb:22:in `send'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/vendor/thor/task.rb:22:in `run'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/vendor/thor.rb:263:in `dispatch'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/lib/bundler/vendor/thor/base.rb:386:in `start'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/gems/bundler-1.0.20/bin/bundle:13
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/bin/bundle:19:in `load'
from /Users/me/.rvm/gems/ree-1.8.7-2011.03@myapp/bin/bundle:19
Any ideas on how I can fix this?
A: try pulling it in manually using git git://github.com/sandal/prawn.git then include it in your bundler then bundle install alrytz
A: The problem was with the version of rubygems I was using. Once I upgraded to version 1.8.15, this worked appropriately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: awkward DLL exports section I have a section of C++ code in MSVC2010 that creates a DLL wrapper. The section of code looks something like this...
extern "C" __declspec(dllexport) DWORD myDllExportFunction()
{
return (DWORD)SomeFunction(SomeParameter);
}
or...
_declspec(dllexport) int64 _stdcall myDllExportFunction2(<someType> someParameter){
{
return new (DWORD)SomeExternalFunction(SomeParameter);
}
I would expect my exports section from doing a dumpbin on this dll to contain just the fully qualified function name however it looks more like this.
_myDllExportFunction@12 = _myDllExportFunction@12
I have no idea why this equal sign is there or what it means. I have a strong feeling that the function is not accessible by programs which import the dll as it is not doing what it is supposed to.
for sake of providing enough information I have included some of my compiler and linker switches
Compiler Options:
/Zi /nologo /Wall /WX- /O2 /Ob2 /Oi /Oy- /D "_WINDLL" /D "_MBCS" /D "_AFXDLL" /Gm- /EHsc /GS /fp:precise /Zc:wchar_t /Zc
Linker Options:
/MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:"C:\....\MyProj.pdb" /SUBSYSTEM:CONSOLE /OPT:REF /OPT:ICF /PGD:"C:\....\MyProj.pgd" /TLBID:1 /DYNAMICBASE:NO /NXCOMPAT:NO /IMPLIB:"MyProj.lib" /MACHINE:X86 /ERRORREPORT:QUEUE
Note: /IMPLIB:"MyProj.lib" -> This import library has all of the exports that I want to have in my DLL in the format that I want them to be in the dll.
Is there any setting in my projects options that would cause this? Was there any changes to dllexport in the past years that I might have missed? Is there any information that I could provide you that would help you understand my problem?
A: Try turning off debug information generation.
A: You have mangled the name by declaring it __stdcall, presumably in a separate declaration. You must give it the __cdecl calling convention to avoid name mangling.
A: If you want to control the names of exported functions (for example, to remove mangling), you'll need to use a linker module definition (.def) file.
A: There are a few different options to prevent name mangling.
*
*Change the declaration specifier for the exported function from
__stdcall to __cdecl. So the function signature should look like
this
extern "C" DWORD __declspec(dllexport) __cdecl myDllExportFunction()
If you must use the __stdcall calling convention use one of the following two methods to get around name mangling. In both cases you do not need to add __declspec(dllexport) to the function definition (but it's OK if you do).
*
*Add a .def file to the project containing the lines
LIBRARY YourLibraryName
EXPORTS
myDllExportFunction
*
*In the project properties, go to Linker -> Command Line and in the edit box for Additional Options add /export:myDllExportFunction
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Bizarre XML access behavior in .NET WebBrowser between Action Script 2 and Action Script 3 I'd started a discussion about a problem with a SWF file not loading an XML data file when rendered in a .NET WebBrowser control (see here)
Further investigation has revealed that if the XML data file is loaded using Action Script 2 (via XML.load()), it works. But if the SWF file in question uses Action Script 3 (via URLLoader.load(), I think), the data file is NOT loaded, UNLESS the XML file is in the same folder as the HTML file.
If either SWF file is loaded using Internet Explorer 9, then everything works OK.
Are there any know issues (which would be apparently well-hidden from Internet search engines, because we've been beating on those) regarding the performance of SWF + Action Script 3 + .NET WebBrowser?
It's just so weird that there are ways to coerce the AS3 solution to work by moving files (not really an option for what we want to do), and that Internet Explorer 9 has no trouble, but the WebBrowser control (which everyone SAYS "is just a wrapper for IE") does NOT work the same way.
Any help appreciated.
A: Actually, it isn't a cross browser problem - SWFObject is not a magic bullet in that regard. We experienced the problem initially while using SWFObject and removed it from the equation to verify that it was specific to the C# WebBrowser control (and not any actual specific browser).
The issue has to do with the passing of BASE parametre information to the C# control. It appears to be successfully passed when run in IE, Firefox and others. It's only in the context of the C# WebBrowser control that this data seems to get lost. And, specifically, only in the case of an AS3 swf as opposed to an AS2 swf. Using the standard load operations for each case, simply reading a file, where the base path is specified in a host HTML page, using the most basic embed method (no special frameworks or APIs), that information (the BASE parameter data) is apparently not received by the Flash in the case of AS3 files. It seems to be consistantly received and processed by the AS2 files and the file is able to be located.
It's quite vexing and it's a little surprising that we haven't been able to find more posts of folks having the problem. In any case, it doesn't seem to be a cross-browser issue, per se. The browsers proper all work as expected vis a vis the BASE parametre. The problem only manifests in this case of using the C# WebBrowser control. It's as if it isn't supporting the newer AS3 engine or something like that.
Anyway, i hope that clears up the issue somewhat...
A: I'll add a wrap-up to the sordid saga...
Through discussions with Microsoft and Adobe, we determined that this was indeed an issue with the Flash ActiveX control being used in a WebBrowser control. Adobe describes this as an "unsupported use case" and that's the end of the story. There's not going to be a "fix". I was able to replicate the issue with the ActiveX WebBrowser control as well, so it's not a .NET thing exclusively. And, as mentioned, the version of ActionScript in use also contributes to success or failure.
What did get done in the long run was to dynamically adjust a <base> tag in the overall HTML document during the loading, and pointing the reference to the folder that held the SWF and XML files. Seems kludgy, but it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to compare two NSSets based on attributes of objects? I have two nssets.
nsset1: person.id = 1, person.id = 2, person.id = 3
nsset2: person.id = 1, person.id = 2
Results should be:
nsset1 - nsset2: person (with id 3)
nsset2 - nsset1: null
These objects with the same id in those two sets are different objects, so I couldn't simply do minusSet.
I want to do something like:
nsset1: person.id = 1, person.id = 2, person.id = 3
nsset2: person.id = 4, person.id = 5
Results should be like this:
nsset1 - nsset2: person (id 1), person (id 2), person (id 3)
nsset2 - nsset1: person (id 4), person (id 5)
What is the best way to do this?
A: @AliSoftware's answer is an interesting approach. NSPredicate is pretty slow outside of Core Data, but that often is fine. If the performance is a problem, you can implement the same algorithm with a loop, which is a few more lines of code, but generally faster.
Another approach is to ask whether two persons with the same ID should always be considered equivalent. If that's true, then you can override isEqual: and hash for your person class like this (assuming identifier is an NSUInteger):
- (BOOL)isEqual:(id)other {
if ([other isMemberOfClass:[self class]) {
return ([other identifier] == [self identifier]);
}
return NO;
}
- (NSUInteger)hash {
return [self identifier];
}
Doing this, all NSSet operations will treat objects with the same identifier as equal, so you can use minusSet. Also NSMutableSet addObject: will automatically unique for you on identifier.
Implementing isEqual: and hash has broad-reaching impacts, so you need to make sure that everyplace you encounter two person objects with the same identifier, they should be treated as equal. But if that's you case, this does greatly simplify and speed up your code.
A: You should try something like this
NSSet* nsset1 = [NSSet setWithObjects:person_with_id_1, person_with_id_2, person_with_id_3, nil];
NSSet* nsset2 = [NSSet setWithObjects:person_with_id_2, person_with_id_4, nil];
// retrieve the IDs of the objects in nsset2
NSSet* nsset2_ids = [nsset2 valueForKey:@"objectID"];
// only keep the objects of nsset1 whose 'id' are not in nsset2_ids
NSSet* nsset1_minus_nsset2 = [nsset1 filteredSetUsingPredicate:
[NSPredicate predicateWithFormat:@"NOT objectID IN %@",nsset2_ids]];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: one-to-many relationship with table having composite key This is the full code for mapping of the tables I am doing. But dont know why I am getting
java heap space error. I am using Jboss server and the exact error message is java.lang.OutOfMemoryError: Java heap space.
package com.mercer.chat.app.dataobject;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MHRContChatSessionDO {
private Long id;
private String chatBucketHeadline;
private String preChatLongHeadline;
private String postChatLongHeadline;
private String preChatSummary;
private String postChatSummary;
private String chatBucketImage;
private String chatLogPath;
private Integer roomId;
private List<MHRContChatAlertsDO> chatAlerts;
public MHRContChatSessionDO() {
super();
}
public MHRContChatSessionDO(Long id, String chatBucketHeadline, String preChatLongHeadline,
String postChatLongHeadline, String preChatSummary, String postChatSummary, String chatBucketImage,
String chatLogPath,Integer roomId, List<MHRContChatAlertsDO> chatAlerts) {
super();
this.id = id;
this.chatBucketHeadline = chatBucketHeadline;
this.preChatLongHeadline = preChatLongHeadline;
this.postChatLongHeadline = postChatLongHeadline;
this.preChatSummary = preChatSummary;
this.postChatSummary = postChatSummary;
this.chatBucketImage = chatBucketImage;
this.chatLogPath = chatLogPath;
this.roomId = roomId;
this.chatAlerts = chatAlerts;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChatBucketHeadline() {
return chatBucketHeadline;
}
public void setChatBucketHeadline(String chatBucketHeadline) {
this.chatBucketHeadline = chatBucketHeadline;
}
public String getPreChatLongHeadline() {
return preChatLongHeadline;
}
public void setPreChatLongHeadline(String preChatLongHeadline) {
this.preChatLongHeadline = preChatLongHeadline;
}
public String getPostChatLongHeadline() {
return postChatLongHeadline;
}
public void setPostChatLongHeadline(String postChatLongHeadline) {
this.postChatLongHeadline = postChatLongHeadline;
}
public String getPreChatSummary() {
return preChatSummary;
}
public void setPreChatSummary(String preChatSummary) {
this.preChatSummary = preChatSummary;
}
public String getPostChatSummary() {
return postChatSummary;
}
public void setPostChatSummary(String postChatSummary) {
this.postChatSummary = postChatSummary;
}
public String getChatBucketImage() {
return chatBucketImage;
}
public void setChatBucketImage(String chatBucketImage) {
this.chatBucketImage = chatBucketImage;
}
public String getChatLogPath() {
return chatLogPath;
}
public void setChatLogPath(String chatLogPath) {
this.chatLogPath = chatLogPath;
}
public Integer getRoomId() {
return roomId;
}
public void setRoomId(Integer roomId) {
this.roomId = roomId;
}
public List<MHRContChatAlertsDO> getChatAlerts() {
return chatAlerts;
}
public void setChatAlerts(List<MHRContChatAlertsDO> chatAlerts) {
this.chatAlerts = chatAlerts;
}
}
public class MHRContChatAlertsDO implements Serializable {
private Long id;
private String userId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public MHRContChatAlertsDO() {
}
public MHRContChatAlertsDO(Long id,String userId) {
this.id=id;
this.userId=userId;
}
@Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof MHRContChatAlertsDO)) return false;
MHRContChatAlertsDO arg1 = (MHRContChatAlertsDO) arg0;
return (this.id.longValue() == arg1.getId().longValue()) && (this.userId.equals(arg1.getUserId()) );
}
@Override
public int hashCode() {
int hsCode;
hsCode = id.hashCode();
hsCode = 19 * hsCode+ userId.hashCode();
return hsCode;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="true">
<class name="com.mercer.chat.app.dataobject.MHRContChatSessionDO"
table="QA_TEST2">
<cache usage="read-only" include="all"/>
<id name="id" type="java.lang.Long">
<column name="ID_CHAT_SESSION" precision="22" scale="0" />
<generator class="assigned" />
</id>
<property name="chatBucketHeadline" type="string">
<column name="CHAT_BUCKET_HEADLINE" />
</property>
<property name="preChatLongHeadline" type="string">
<column name="PRE_CHAT_LONGHEADLINE" scale="0" />
</property>
<property name="postChatLongHeadline" type="string">
<column name="POST_CHAT_LONGHEADLINE" />
</property>
<property name="preChatSummary" type="string">
<column name="PRE_CHAT_SUMMARY" />
</property>
<property name="postChatSummary" type="string">
<column name="POST_CHAT_SUMMARY" not-null="true" />
</property>
<property name="chatBucketImage" type="string">
<column name="CHAT_BUCKET_IMAGE_PATH" />
</property>
<property name="chatLogPath" type="string">
<column name="CHAT_LOG_PATH" />
</property>
<property name="roomId" type="java.lang.Integer">
<column name="ROOM_ID" scale="0" />
</property>
<list name="chatAlerts" batch-size="5" cascade="all" lazy="false">
<cache usage="read-only" include="all" />
<key column="ID_CHAT_SESSION" />
<list-index column="ID_USER" />
<one-to-many
class="com.mercer.chat.app.dataobject.MHRContChatAlertsDO" />
</list>
</class>
</hibernate-mapping>
<hibernate-mapping default-lazy="true">
<class name="com.mercer.chat.app.dataobject.MHRContChatAlertsDO" table="QA_TEST3">
<cache usage="read-only" include="all" />
<composite-id >
<key-property name="id" type="java.lang.Long">
<column name="ID_CHAT_SESSION" precision="22" scale="0" />
</key-property>
<key-property name="userId" type="string">
<column name="ID_USER" />
</key-property>
</composite-id>
</class>
</hibernate-mapping>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to read an Excel spreadsheet in c# quickly I am using Microsoft.Office.Interop.Excel to read a spreadsheet that is open in memory.
gXlWs = (Microsoft.Office.Interop.Excel.Worksheet)gXlApp.ActiveWorkbook.ActiveSheet;
int NumCols = 7;
string[] Fields = new string[NumCols];
string input = null;
int NumRow = 2;
while (Convert.ToString(((Microsoft.Office.Interop.Excel.Range)gXlWs.Cells[NumRow, 1]).Value2) != null)
{
for (int c = 1; c <= NumCols; c++)
{
Fields[c-1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)gXlWs.Cells[NumRow, c]).Value2);
}
NumRow++;
//Do my other processing
}
I have 180,000 rows and this turns out be very slow. I am not sure the "Convert" is efficient. Is there anyway I could do this faster?
Moon
A: There are several options - all involve some additional library:
*
*OpenXML 2.0 (free library from MS) can be used to read/modify the content of an .xlsx so you can do with it what you want
*some (commercial) 3rd-party libraries come with grid controls allowing you to do much more with excel files in your application (be it Winforms/WPF/ASP.NET...) like SpreadsheetGear, Aspose.Cells etc.
A: Hi I found a very much faster way.
It is better to read the entire data in one go using "get_range". This loads the data into memory and I can loop through that like a normal array.
Microsoft.Office.Interop.Excel.Range range = gXlWs.get_Range("A1", "F188000");
object[,] values = (object[,])range.Value2;
int NumRow=1;
while (NumRow < values.GetLength(0))
{
for (int c = 1; c <= NumCols; c++)
{
Fields[c - 1] = Convert.ToString(values[NumRow, c]);
}
NumRow++;
}
A:
I am not sure the "Convert" is efficient. Is there anyway I could do
this faster?
What makes you believe this? I promise you that Convert.ToString() is the most effective method in the code you posted. Your problem is that your looping through 180,000 records in an excel document...
You could split the work up since you know the number of row this is trival to do.
Why are you coverting Value2 to a string exactly?
A: I found really fast way to read excel in my specific way. I need to get it as a two dimensional array of string. With really big excel, it took about one hour in old way. In this way, I get my values in 20sec.
I am using this nugget: https://reposhub.com/dotnet/office/ExcelDataReader-ExcelDataReader.html
And here is my code:
DataSet result = null;
//https://reposhub.com/dotnet/office/ExcelDataReader-ExcelDataReader.html
using (var stream = File.Open(path, FileMode.Open, FileAccess.Read))
{
// Auto-detect format, supports:
// - Binary Excel files (2.0-2003 format; *.xls)
// - OpenXml Excel files (2007 format; *.xlsx)
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
result = reader.AsDataSet();
}
}
foreach (DataTable table in result.Tables)
{
if (//my conditions)
{
continue;
}
var rows = table.AsEnumerable().ToArray();
var dataTable = new string[table.Rows.Count][];//[table.Rows[0].ItemArray.Length];
Parallel.For(0, rows.Length, new ParallelOptions { MaxDegreeOfParallelism = 8 },
i =>
{
var row = rows[i];
dataTable[i] = row.ItemArray.Select(x => x.ToString()).ToArray();
});
importedList.Add(dataTable);
}
A: I guess it's not the Convert the source of "slowing"...
Actually, retrieving cell values is very slow.
I think this conversion is not necessary:
(Microsoft.Office.Interop.Excel.Range)gXlWs
It should work without that.
And you can ask directly:
gXlWs.Cells[NumRow, 1].Value != null
Try to move the entire range or, at least, the entire row to an object Matrix and work with it instead of the range itself.
A: Use the OleDB Method. That is the fastest as follows;
string con =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +
@"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Facebook Credits on an external website I tryed the sample code found here:
https://developers.facebook.com/docs/creditsapi/
Even if i added my company address & payment, i still get this error:
API Error Code: 1151 API Error Description: Sorry, but this app may
not be eligible to accept Facebook Credits. If this app has accepted
credits before, please try again. Error Message: Invalid Application
I think the credits api best work on iframe apps. Is possible to integrate credits in my website?
Best
Matteo
A: credits only work in facebook canvas apps:
The Facebook Credits API enables a user to use credits as a method for
purchasing digital and virtual goods within a Facebook canvas
application. Please note: the credits api is not yet available for use
by external websites but only on canvas iframe applications.
A: The error is because you do not have a valid application id. You are going to have to create an application for your website. This can be done by going to https://developers.facebook.com/apps . If you have an application made for your website still go to the website and grab the App ID/API Key and put after
FB.init({appId:
A: What I do is redirect the user into the iFrame canvas for payment and then back out to my web site when done.
Not sure this breaks any Facebook agreement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS Animate Dashed Rectangle Border I have a UIImageView displaying an image. I want to "highlight" a portion of the image by drawing a rounded rectangle outline. I would like to have the outline drawn with a thick, dashed line that "animates" by continually varying where the "beginning" of the line starts.
I thought about drawing a circle that had the look I want and then simply animating it, but I really need a rectangular solution, so that's out.
Background:
I'm drawing the rounded rectangle border by calculating 8 points and drawing 4 straight lines and 4 curves. (Maybe this can be easier, but it's not the broken part!)
My thinking is that I'll use an "offset" variable that starts at the top-left of the rounded rectangle, where the top-left curve meets the top straight piece. Then, I will increment this "offset" across the top of the rounded rectangle until it reaches the top-right curve, whereupon I will "reset" the "offset" variable to its original value.
This is working pretty much as I'd like, until the "reset" occurs. At this point, the animation is jerky (kind of expected), but it also appears to travel in reverse for a small portion of the time, before resuming "forward" motion. Finally, at the beginning/end of my dashed line, I get an extra long segment on the dashed line. I know they can't all be equal-length (can they? how to calculate?), but how can I make 2 shorter segments rather than 1 longer segment?
Anybody have an idea of what I can do to get a smooth "marching ants" kind of look? Any other ideas on a good way to (using animation) call the user's eye to a particular area of the screen? (It needs to surround a particular area without obscuring it.)
Current code:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
// Rounded corner will be 10% of average side length (i.e., (w + h) / 2)
float averageSide = ([self HighlightRect].size.width + [self HighlightRect].size.height) / 2.0;
float roundSize = averageSide * 0.10;
// offset is a static, class variable
offset += roundSize / 4.0;
if ([WhereIAmView offset] < roundSize) {
offset = roundSize;
}
if ([WhereIAmView offset] > ([self HighlightRect].size.width - roundSize)) {
offset = roundSize;
}
// Set the "main" color of the rounded rectangle
UIColor *lineColor = [UIColor colorWithRed:027.0/255.0 green:050.0/255.0 blue:224.0/255.0 alpha:1.0];
CGContextSetStrokeColorWithColor(context, [lineColor CGColor]);
CGContextSetLineWidth(context, 16.0);
CGFloat pattern[] = {25.0, 5.0};
CGContextSetLineDash(context, offset, pattern, 2);
CGRect rRect = [self HighlightRect];
// The top left corner
CGPoint topLeft = CGPointMake(rRect.origin.x, rRect.origin.y);
// The top right corner
CGPoint topRight = CGPointMake(rRect.origin.x + rRect.size.width, rRect.origin.y);
// The bottom right corner
CGPoint bottomRight = CGPointMake(rRect.origin.x + rRect.size.width, rRect.origin.y + rRect.size.height);
// The bottom left corner
CGPoint bottomLeft = CGPointMake(rRect.origin.x, rRect.origin.y + rRect.size.height);
// The two points across the top of the rounded rectangle (left to right)
CGPoint point1 = CGPointMake(rRect.origin.x + roundSize, rRect.origin.y);
CGPoint point2 = CGPointMake(rRect.origin.x + rRect.size.width - roundSize, rRect.origin.y);
// The two points along the right of the rounded rectangle (top to bottom)
CGPoint point3 = CGPointMake(rRect.origin.x + rRect.size.width, rRect.origin.y + roundSize);
CGPoint point4 = CGPointMake(rRect.origin.x + rRect.size.width, rRect.origin.y + rRect.size.height - roundSize);
// The two points along the bottom of the rounded rectangle (right to left)
CGPoint point5 = CGPointMake(rRect.origin.x + rRect.size.width - roundSize, rRect.origin.y + rRect.size.height);
CGPoint point6 = CGPointMake(rRect.origin.x + roundSize, rRect.origin.y + rRect.size.height);
// The two points along the left of the rounded rectangle (bottom to top)
CGPoint point7 = CGPointMake(rRect.origin.x, rRect.origin.y + rRect.size.height - roundSize);
CGPoint point8 = CGPointMake(rRect.origin.x, rRect.origin.y + roundSize);
// Move to point 1
CGContextMoveToPoint(context, point1.x, point1.y);
// Add line to point 2 (this is the straight portion across the top)
CGContextAddLineToPoint(context, point2.x, point2.y);
// Add curve to point 3 (this is the rounded portion in top right)
CGContextAddArcToPoint(context, topRight.x, topRight.y, point3.x, point3.y, roundSize);
// Add line to point 4 (this is the straight portion across the right)
CGContextAddLineToPoint(context, point4.x, point4.y);
// Add curve to point 5 (this is the rounded portion in bottom right)
CGContextAddArcToPoint(context, bottomRight.x, bottomRight.y, point5.x, point5.y, roundSize);
// Add line to point 6 (this is the straight portion across the bottom)
CGContextAddLineToPoint(context, point6.x, point6.y);
// Add curve to point 7 (this is the rounded portion in bottom left)
CGContextAddArcToPoint(context, bottomLeft.x, bottomLeft.y, point7.x, point7.y, roundSize);
// Add line to point 8 (this is the straight portion across the left)
CGContextAddLineToPoint(context, point8.x, point8.y);
// Add curve to point 1 (this is the rounded portion in top left)
CGContextAddArcToPoint(context, topLeft.x, topLeft.y, point1.x, point1.y, roundSize);
// Stroke the path
CGContextStrokePath(context);
}
bump
bump bump
A: Try Using CAShapeLayer with CGPath of your shape.
Rounded rectangle path can be constructed using Uibezierpath convenience method.
You can set a line pattern for the shape layer. Animating the line property of the shape layer would give the "marching ants like effect".
shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(160.0f, 140.0f)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
[shapeLayer setLineWidth:1.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:10],
[NSNumber numberWithInt:5],
nil]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0];
[shapeLayer setPath:path.CGPath];
[[imageview layer] addSublayer:shapeLayer];
The animation function can be,
- (void)toggleMarching
{
if ([shapeLayer animationForKey:@"linePhase"])
[shapeLayer removeAnimationForKey:@"linePhase"];
else {
CABasicAnimation *dashAnimation;
dashAnimation = [CABasicAnimation
animationWithKeyPath:@"lineDashPhase"];
[dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
[dashAnimation setToValue:[NSNumber numberWithFloat:15.0f]];
[dashAnimation setDuration:0.75f];
[dashAnimation setRepeatCount:10000];
[shapeLayer addAnimation:dashAnimation forKey:@"linePhase"];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: android memory usage and heap usage when I look at my application in a memory utility (like Memory Usage app), it shows my application using 33MB of memory.
If while debugging my app, I go into DDMS and look at the heap, it's taking 4MB.
So at this point, I'm wondering where the other 29MB is being chewed up by. Secondly, my concern is that I could wind up spending a huge amount of time trying to trim that 4MB to something much smaller like say 2-3MB, but that hardly seems like I'm putting a dent in the memory usage. So how do i get that memory usage down much more significantly?
A: check and discoer it properly..........
http://elinux.org/Android_Memory_Usage
How do I discover memory usage of my application in Android?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Stored Procedure - Search an array of strings in a field and display the count of occurrences In our case, we're restricted to SQL Server 2000.
Say we have a table "Articles" with a field "ArticleText". How do we search a string consisted of many words, and return the number of found occurrences.
An example of a search string: John is a nice boy (so it contains 5 words)
ID ArticleText Result
1 John is going to learn 2
2 John is doing his homework nice-ly 3
3 John is a nice boy 5
Up to now I've found a split function
for sql server 2000 to delimit the search string. Now I'm trying to iterate through the records and display the count of found words in one field, but I got stuck. Any help?
A: SQL Server 2008 solution
You use cross apply, which passes each value from a table into the function and joins the result.
SELECT a.ID, a.ArticleText, COUNT(*) as [Result]
FROM Articles as a
CROSS APPLY dbo.Split(a.ArticleText,' ') as S
WHERE S.Data IN ('John','is','a','nice','boy')
GROUP BY a.ID, a.ArticleText
Interestingly, if you are just passing in the text as a single string, which is more likely when you replace the example text. You can use the Split function for that as well e.g. 'John is a nice boy' from a procedure parameter or local variable.
SELECT a.ID, a.ArticleText, COUNT(*) as [Result]
FROM Articles as a
CROSS APPLY dbo.Split(a.ArticleText,' ') as S
WHERE S.Data IN (SELECT Data FROM dbo.Split(@Search,' '))
GROUP BY a.ID, a.ArticleText
A: SQL Server 2000 solution
New idea. Try splitting the search string first into 1 temp table. Then joining back to the articles using wild cards.
DECLARE @Search nvarchar(200);
SET @Search = 'John is a nice boy';
IF NOT OBJECT_ID('tempdb..#S') IS NULL
DROP TABLE #S;
SELECT *
INTO #S
FROM dbo.Split(@Search, ' ');
SELECT a.ID, a.ArticleText, COUNT(*) as [Result]
FROM #S as s
JOIN Articles as a on a.ArticleText like s.Data + ' %'
OR a.ArticleText like '% ' + s.Data + '%'
GROUP BY a.ID, a.ArticleText
I tested this on SQL Server 2008 R2 with 2000 compatibility mode.
The 2 join conditions ensure that it matches the first word or any beginning of words (to get 'nice-' ).
You should tweak this to your requirements and consider replace functions for the hyphen and other punctuation.
A: Rusell, Thanks a lot man.
Now, I had a problem with the #S
"There is already an object named '#S' in the database."
and also with the:
SELECT * INTO @tblWords FROM dbo.Split(@Search, ' ');
But nevermind, i fixed it, so I'm sending the code that works in SQL 2000.
declare @Search varchar(100)
set @Search = 'John is a nice boy'
DECLARE @tblWords TABLE(IDArray int, ArrayValue VARCHAR(500))
INSERT INTO @tblWords (IDArray, ArrayValue) SELECT * FROM [dbo].[Split] (@Search, ' ')
SELECT IDArticle, ArticleText, COUNT(*) as [Result] FROM @tblWords
JOIN Articles on ArticleText like ArrayValue + ' %'
OR ArticleText like '% ' + ArrayValue + '%'
GROUP BY IDArticle, ArticleText
Order by Result desc
For those who want to try this, here's the table code:
CREATE TABLE [Articles] (
[IDArticle] [int] IDENTITY (1, 1) NOT NULL ,
[ArticleText] [varchar] (500)
Thanks again Rusell, I owe you a coffee.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XSLT Add target="_blank" to a URL I've created an XSLT file that runs through a SharePoint list to generate a table of resources. One part of it creates a link that goes off site. I'm wanting to have it open in a new window using target="_blank", but I'm unsure of how to do this in the XSLT.
Here's the portion that creates the link:
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="Website"/>
</xsl:attribute>
<xsl:text>Visit Website</xsl:text>
</xsl:element>
Can anyone shed some light on this for me? I'm fairly new to working with XSLTs.
A: Will it work ?
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="Website"/>
</xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<xsl:text>Visit Website</xsl:text>
</xsl:element>
A: It's actually much easier than this: you don't need these xsl:element and xsl:attribute instructions at all. Just do
<a href="{Website}" target="_blank">Visit Website</a>
XSLT can be verbose, but it doesn't have to be!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Youtube dimensions wordpress Is it possible to change the default embed dimensions of an youtube (or another video) in Wordpress for your current theme? I've searched for a plugin and some code, but I can't seem to find any.
What I mean is the default embed size used when you just paste an youtube url in an post or page.
A: The currently accepted answer has an example that uses the following shortcode:
[youtube=http://www.youtube.com/watch?v=0Bmhjf0rKe8&w=640&h=385]
The shortcode [youtube] only works if you have the Jetpack plugin installed.
To make it work with WordPress with no Jetpack you can use the built-in [embed] shortcode like this:
[embed width=640 height=385]http://www.youtube.com/watch?v=0Bmhjf0rKe8[/embed]
A: To change the default embed size go to Settings > Media and just set a fixed width/height.
You also have the shortcode
[youtube=http://www.youtube.com/watch?v=0Bmhjf0rKe8&w=640&h=385]
where you can manually insert width and height as params. This shortcode will overwrite the default WP settings.
A: Open your theme’s functions.php file, and add the following code:
if ( ! isset( $content_width ) ) $content_width = 600;
Remember to change the number 600 appropriately for your theme. It is the maximum width in pixels for your content area.
Once you do this, WordPress will automatically use that for the maximum width of your oEmbed elements (youtube videos, slideshare, etc).
via wpbeginner.com
A: The media settings have been removed. You can do it with a filter however.
function mycustom_embed_defaults($embed_size){
$embed_size['width'] = 600; // Adjust values to your needs
$embed_size['height'] = 500;
return $embed_size; // Return new size
}
add_filter('embed_defaults', 'mycustom_embed_defaults');
Taken from here http://shailan.com/2154/change-wordpress-default-embed-size-using-filters/
A: They've got rid of the fixed width/height option in the media settings of the new version of Wordpress. Not sure why. It was useful!! Shortcodes don't seem to work either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Does cascade="all-delete-orphan" have any meaning in a Hibernate unidirectional many-to-many association with a join table? I have two objects which form a parent-child relationship which have a many-to-many relationship. Following the recommendations in the Hibernate reference manual, I have mapped this using a join table:
<class name="Conference" table="conferences">
...
<set name="speakers" table="conference_speakers" cascade="all">
<key column="conference_id"/>
<many-to-many class="Speaker" column="speaker_id"/>
</set>
</class>
<class name="Speaker" table="speakers">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="firstName"/>
<property name="lastName"/>
</class>
My wish is that a single Speaker can be associated with many different Conferences, but also that any Speaker which is no longer referenced by any Conference is removed from the speakers table (as a Speaker with no associated conferences doesn't have much meaning in my project).
However, I've found that if I use cascade="all-delete-orphan", then if a Speaker which is associated with multiple Conferences is removed from just one of them, Hibernate attempts to delete the Speaker instance itself.
Below is a unit test which shows this behavior:
@Test
public void testRemoveSharedSpeaker() {
int initialCount = countRowsInTable("speakers");
Conference c1 = new Conference("c1");
Conference c2 = new Conference("c2");
Speaker s = new Speaker("John", "Doe");
c1.getSpeakers().add(s);
c2.getSpeakers().add(s);
conferenceDao.saveOrUpdate(c1);
conferenceDao.saveOrUpdate(c2);
flushHibernate();
assertEquals(initialCount + 1, countRowsInTable("speakers"));
assertEquals(2, countRowsInTable("conference_speakers"));
// the remove:
c1 = conferenceDao.get(c1.getId());
c1.getSpeakers().remove(s);
flushHibernate();
assertEquals("count should stay the same", initialCount + 1, countRowsInTable("speakers"));
assertEquals(1, countRowsInTable("conference_speakers"));
c1 = conferenceDao.get(c1.getId());
c2 = conferenceDao.get(c2.getId());
assertEquals(0, c1.getSpeakers().size());
assertEquals(1, c2.getSpeakers().size());
}
An error is thrown when s's removal from c1.speakers is processed, because Hibernate is deleting both the row in the join table and the speakers table row as well:
DEBUG org.hibernate.SQL - delete from conference_speakers where conference_id=? and speaker_id=?
DEBUG org.hibernate.SQL - delete from speakers where id=?
If I change cascade="all-delete-orphan" to just cascade="all", then this test works as expected, although it leads to the undesired behavior where I will end up with orphaned rows in my speakers table.
This leads me to wonder - is it even possible for Hibernate to know when to delete orphaned objects from the child-side of the relationship, but only when the child is not referenced by any other parents (whether or not those parents are in the current Session)? Perhaps I am misusing cascade="all-delete-orphan"?
I get the same exact behavior if I use JPA annotations instead of XML mapping such as:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "conference_speakers",
joinColumns = @JoinColumn(name = "conference_id"),
inverseJoinColumns = @JoinColumn(name = "speaker_id"))
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Set<Speaker> speakers = new HashSet<Speaker>();
This is with Hibernate 3.6.7.Final, by the way.
A: DELETE_ORPHAN cascade mode is not defined for many-to-many relationship - only for one-to-many (the latter sports a "orphanRemoval=true|false" attribute within JPA standard @OneToMany annotation, so you don't have to resort to proprietary Hibernate annotation).
The reason for this is exactly as you've described - there's no way for Hibernate to figure out whether "orphaned" end of the many-to-many relationship is truly orphaned without running a query against the database which is both counter-intuitive and can (potentially) have serious performance implications.
Hibernate behavior you've described is therefore correct (well, "as documented"); though in a perfect world it would have alerted you to the fact that DELETE_ORPHAN is illegal on many-to-many during 2nd pass mappings compilation.
I can't think of a good way of achieving what you want to do, to be honest. The easiest (but database-specific) way would likely be to define a trigger on deletion from conference_speakers that would check whether this speaker is "truly" orphaned and delete it from speakers if so. The database-independent option is to do the same thing manually in DAO or listener.
Update: Here's an excerpt from Hibernate docs (Chapter 11.11, right after gray Note on CascadeType.ALL), highlights are mine:
A special cascade style, delete-orphan, applies only to one-to-many
associations, and indicates that the delete() operation should be
applied to any child object that is removed from the association.
Further down:
It does not usually make sense to enable cascade on a many-to-one or
many-to-many association. In fact the @ManyToOne and @ManyToMany don't
even offer a orphanRemoval attribute. Cascading is often useful for
one-to-one and one-to-many associations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Existing Linux Module Symbol I am porting a Linux module (PageMgrMod) to a more recent kernel, but now the functions are not visible to other modules. For example, loading a module that uses PageMgrMod gives the error
no symbol version for init_pgmgr
Unknown symbol init_pgmgr
But reading /proc/kallsyms shows the symbol exists
ffffffff81883c0d T x86_init_pgd_noop
ffffffffa012a5c0 r __ksymtab_init_pgmgr [PageMgrMod]
ffffffffa012a669 r __kstrtab_init_pgmgr [PageMgrMod]
ffffffffa012a600 r __kcrctab_init_pgmgr [PageMgrMod]
ffffffffa012a380 T init_pgmgr [PageMgrMod]
This functionality worked on a 2.6.18 kernel but fails on a 2.6.32-24 kernel.
I have seen similar questions, but those solutions do not help due to the fact I cannot modify the other modules.
If it makes a difference, the module sources are in different folders.
A: To make init_pgmgr visible to other modules, add
EXPORT_SYMBOL(init_pgmgr);
to the PageMgrMod module. Without the above declaration, the symbol is available to any code built into the kernel (referred to some places as an external symbol), but not to other loadable modules.
This is similar to question #413955 How to write Linux driver module call/use another driver module?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Display last modified time of JavaScript file I am developing a webapp and the browser doesn't consistently empty the cache each time I refresh, so sometimes I'm not getting the latest version of my JavaScript file loaded.
I would like to have a console message indicating if I'm using the latest version of the JavaScript file each time I refresh. I'm thinking that displaying the "last modified" time of the JavaScript file will do the job!
Any thoughts? Is there a standard solution to my problem that I've missed?
A: For production environments, whenever you modify your script file, you can alter your script tags to include a version querystring, so that the browser sees there is a new version and gets a fresh copy from the server:
<script type="text/javascript" src="/scripts/myscript.js?v1"></script>
This is just a simple trick that gives the browser a url it hasn't seen before, forcing it to request the new file. The server ignores the querystring and just returns the script file.
For development environments, press ctrl+f5 to force the browser to fetch a fresh copy from the server.
A: My standard solution for this kind of a problem (if I do understand your concern correctly), is to check the Net tab on the firebug. Go to the Js sub-tab, and then you will see the list of js files being requested from the server/cached. just check the response header.
look at the other answer here. Always use ctrl + f5 to refresh your browser (if you want fresh copy from the serer).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call any url from aspx page? I have one .aspx page and inside that page I want to call third party url and I should include the content from that url.
I can achive this by using iframe but i am restricted to not to use iframe.
Ex:
<body>
my content ......
..................
<Video><url="www.yamaha.com\learnPiano"> Thirdparty video get played here </url> </Video>
.................
..................... my content ....
</body>
A: Look into WebRequest and WebResponse.
A: You can do this on the server side. Add an ASP:Literal control to your page and name it "OtherContent" for example.
var webRequest = WebRequest.Create("http://www.google.com");
var webResponse = webRequest.GetResponse();
if (webResponse != null)
{
var responseStream = webResponse.GetResponseStream();
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream);
var pageSource = streamReader.ReadToEnd();
OtherContent.Text = pageSource;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Builtin DropActivityHere Designer? I've noticed the System.Activities.Core.Presentation assembly contains several designers, and I've found them to be quite useful for re-usability.
I've now found myself creating activities that need to say "Drop activity here" (they accept a child activity). This is seen all over the place with the built-in WF activities, so I assume there must be some designer, e.g., DropHereDesigner, somewhere. I can reproduce it with XAML, but I don't want to unless I must.
Anyone know if this designer can be found anywhere in the WF built-in libraries?
A: The WorkflowItemPresenter is used for this functionality.
<WorkflowItemPresenter
xmlns="clrnamespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
HintText="Drop activity here"
Item="{Binding Path=ModelItem.Child.Handler}" />
However, if you are asking "Can I get away with not touching XAML in order to create a designer" the answer is amost assuredly no.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: common variable for log4j.xml configuration I have log4j.xml configuration like this:
<appender name="MyAppender"class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/logs/custom/my.log"/>
...
</appender>
However the root directory of my file are the same for a lot of appender. Is there a way to defined "/logs/custom/" as a variable and reused it in all of my appender.
Thanks,
Sean
A: I don't believe this is possible using XML configuration, but it is in a .properties file configuration:
mysubdir = /logs/custom
...
log4j.appender.MyAppender.File = ${mysubdir}/my.log
A: UPDATE: The original answer applies to Log4j 1.x
Log4j 2.x has much richer support for properties in configuration file, see the Log4j manual about Configuration with properties.
Log4j 1.x (the original answer):
The only way to achieve something similar when you are using log4j.xml is to set a system property at startup and then reference that from your log4j.xml.
At startup, you set your system property:
java -Dlog_dir=/var/logs/custom com.yourorg.yourapp.Main
Or set it programmatically at runtime (before initializing Log4j):
System.setProperty("log_dir", "/var/logs/custom")
Then you can reference it like this:
<appender name="MyAppender"class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="${log_dir}/my.log"/>
...
</appender>
Or in properties file, like this:
log4j.appender.MyAppender.File = ${log_dir}/my.log
Source: I got inspiration for this answer from Using system environment variables in log4j xml configuration.
Also, if you are running under Tomcat, you can use ${catalina.home} variable, like this:
<appender name="MyAppender"class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="${catalina.home}/logs/my.log"/>
...
</appender>
A: It is possible in XML as well to define a variable and reuse it in the rest of the doc:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" [
<!ENTITY logHome "/logs/folder1/folder2">
]
>
Then, refer to this variable just defined, as &logHome;
<param name="File" value="&logHome;/folder3/my.log"/>
How about that?
(I believe I learnt about XML entity references some time ago at this link: http://www.ibm.com/developerworks/xml/library/x-tipentref/index.html)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Allow plus sign in URL with MVC 3 I need to be able to allow the "+" sign for certain actions in a controller. I am building a tag filtering engine that allows something like this (ie. stackoverflow) : /Stuff/Tagged/tag-name-1+tag-name-2+other-tag
I know I can set allowDoubleEscaping="true" in the web.config, but it is not best practices for security reasons.
I am guessing there is a way using maybe a custom filer or some other registry in the global.asax?
A: StackOverflow is probably treating the + as a whitespace. Most likely they map the route /Stuff/Tagged/{*tags} and call string.split() on the tags. This actually works out great if you don't allow whitespace in your tags.
A: + means whitespace in an url. You should URL encode them:
/Stuff/Tagged/tag-name-1%2Btag-name-2%2Bother-tag
A: You can use simple replace:
string url = Url.Action("Index", "YourController");
url = url.Replace("%2b", "+");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can't DSolve two-body problem using Mathematica? EDIT:
@auxsvr is correct that I had the force equations wrong, and about the
-3/2 exponent.
Another way to see this it to simply to 2 dimensions and consider a
force acting from the origin, proportional to 1/r^2 just like gravity,
where r is the distance from the origin.
At (x,y), the force acts in the direction (-x,-y). However, that's
just the direction, not the magnitude. If we use k as the constant of
proportionality, the force is (-kx, -ky).
The magnitude of the force is thus Sqrt[(-kx)^2+(-ky)^2], or
k*Sqrt[x^2+y^2], or k*Sqrt[r^2] or k*r
Since the force magnitude is also 1/r^2, this gives us k= 1/r^3.
The force is thus (-x/r^3, -y/r^3).
Since I was initially using r^2 as my primary quantity, that's (r^2)^(-3/2), which is where the 3/2 comes from.
This effectively invalidates my question, although it still makes an
interesting theoretical discussion.
I retried this Mathematica with the correct equations, but still got
no answer. As other points out, the result is only an ellipse under
certain conditions (could be a parabola or hyperbola in other cases).
Additionally, although the eventual orbit is a conic section, the
initial orbit may spiral in or out until the final conic section orbit
is achieved.
EDIT ENDS HERE
I'm using Mathematica to solve the two-body problem:
DSolve[{
d2[t] == (x1[t]-x0[t])^2 + (y1[t]-y0[t])^2 + (z1[t]-z0[t])^2,
D[x0[t], t,t] == (x1[t]-x0[t])/d2[t],
D[y0[t], t,t] == (y1[t]-y0[t])/d2[t],
D[z0[t], t,t] == (z1[t]-z0[t])/d2[t],
D[x1[t], t,t] == -(x1[t]-x0[t])/d2[t],
D[y1[t], t,t] == -(y1[t]-y0[t])/d2[t],
D[z1[t], t,t] == -(z1[t]-z0[t])/d2[t]
},
{x0,y0,z0,x1,y1,x1,d2},
t
]
But I get back:
There are fewer dependent variables than equations, so the system is overdetermined.
I count 7 equations and 7 dependent variables?
In fact, the system is semi-undetermined, since I don't provide positions and velocities at time 0.
I realize my equations themselves might be wrong for the two-body problem, but I'd still like to know why Mathematica complains about this.
A: I'm suprised no one else noticed that everyone wrote the equations of motion incorrectly, which is apparent from the plot, because bounded orbits in the gravitational potential of two bodies are always closed (Bertrand's theorem). The correct equations of motion are
{x0''[t] == (-x0[t] + x1[t])/d2[t]^(3/2),
y0''[t] == (-y0[t] + y1[t])/d2[t]^(3/2),
x1''[t] == -x0''[t],
y1''[t] == -y0''[t]}
with
d2[t_]:= (x1[t]-x0[t])^2 + (y1[t]-y0[t])^2
since the motion is planar for central force fields. Also, one must set the initial conditions appropriately, otherwise the centre of mass moves and the orbits are no longer conical sections.
A: How about NDSolve?
d2[t_] = (-x0[t] + x1[t])^2 + (-y0[t] + y1[t])^2 + (-z0[t] +
z1[t])^2; sol = {x0, y0, z0, x1, y1, z1} /.
NDSolve[{x0''[t] == (-x0[t] + x1[t])/d2[t],
y0''[t] == (-y0[t] + y1[t])/d2[t],
z0''[t] == (-z0[t] + z1[t])/d2[t], x1''[t] == -x0''[t],
y1''[t] == -y0''[t], z1''[t] == -z0''[t], x0[0] == 0, y0[0] == 0,
z0[0] == 0, x1[0] == 1, y1[0] == 0, z1[0] == 0, x0'[0] == -0.5,
y0'[0] == 1, z0'[0] == 0.5, x1'[0] == 0.5, y1'[0] == -1,
z1'[0] == -0.5}, {x0, y0, z0, x1, y1, z1}, {t, 0, 120}][[1]]
r = 3;
Animate[
Graphics3D[
{
PointSize -> 0.05,
Point[{sol[[1]][t], sol[[2]][t], sol[[3]][t]}],
Point[{sol[[4]][t], sol[[5]][t], sol[[6]][t]}],
Red,
Line[Table[{sol[[1]][t1], sol[[2]][t1], sol[[3]][t1]}, {t1, 0, t, 0.1}]],
Green,
Line[Table[{sol[[4]][t1], sol[[5]][t1], sol[[6]][t1]}, {t1, 0, t, 0.1}]]
},
PlotRange -> {{-r, r}, {-r, r}, {-r, r}}
], {t, 0, 120}, AnimationRate -> 4
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: fatal error LNK1104: cannot open file 'd3dc9.lib' I'm currently going though a game programming book and am trying to compile some directx9 code
I have the latests DirectX11 SDK and the code has these lines of code
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
But I get
LINK : fatal error LNK1104: cannot open file 'd3dc9.lib'
I don't know how to set it up to find this file although in fact I don't get why it asks for it since it isn't inside the Lib file for the DirectX 11 SDK and isn't what i've asked for.
A: The linker only knows the name of the .lib file, it doesn't know what directory it is stored in. Project + Properties, Linker, General, Additional Library Directories setting.
The version 11 SDK is quite new. You may need an older version of the SDK if these .libs are no longer distributed. I know the June 2010 edition has them. Download is here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Leiningen 1.3 Upgrade Plugin Classpath I have a plugin that used to use command-line from contrib with the following in ns,
(:use [leiningen.compile :only [eval-in-project]]
[clojure.contrib command-line logging])
that used to work, I am guessing since leiningen also uses clojure and contrib it is automatically on its classpath with the new contrib structure above becomes,
(:use [leiningen.compile :only [eval-in-project]]
[clojure.tools cli logging])
it seems leiningen does not include jars from the lib/ on its class path and this fails, is there a workaround this?
A: Right. Unless you use eval-in-project, your code runs in Leiningen's classpath. Any code on lein's classpath is thus available to your project. These, however, are not.
Is the code that uses cli and logging inside of the eval-in-project call? If so, those jars need to be dependencies on the projects that you call the plugin in, and the use call must be passed to eval-in-project (see the documentation of eval-in-project for more info).
If the code that uses cli and logging is not inside of an eval-in-project call, then you can add those dependencies to your plugin project and it should just work. If you try to test the plugin inside of the plugin project itself, you'll need to add :eval-in-leiningen true to your project.clj.
If this doesn't help, please expand your question with more details/code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript popup over all applications I have an ASP.NET page, running in IE, that monitors several server jobs running at night. When an error occurs on a job, I have a popup window that opens with javascript, window.open(). The problem is, employees tend to have other applications, such as Netflix, running full screen and do not see the popup window notifying them of the error. I have javascript code on the popup page to continually set focus to itself, so it will blink in the taskbar, but Netflix covers the taskbar, so not helpful.
Currently using:
setInterval('window.focus()',500);
Is there a way to make a popup window in IE that will open over every other application?
A: No, you only have control over the browser and that is even limited, not the entire Desktop/Laptop.
A: The only way to overcome to other windows is using fullscreen=yes to make your window full screen. It's supported in IE only (MSDN docs) and Mozilla people hate it!
Otherwise you don't have access to OS level from the browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I capture button events when phone display is turned off When using Slacker Radio on my android phone I am able to skip to the next song when the display is off by long pressing the volume button.
What part of the API should I be looking at to implement such a feature for my app?
A: I think you might find what your looking for from this post. You just need to listen for that specific key event. You might want to look into a WakeLock to keep your program active when the display is turned off.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hough Transform Equation I was wondering why the Hough Transform uses rho=xcos(theta) + ysin(theta) for representation of a straight line (y=mx+b). I tried to work through this (and went to the wikipedia article about this), but can not find a way to derive one from the other.
Does anyone know how to derive one from the other?
Thank you in advance.
A: That's just a transform from a linear coordinate system to a rotational one. The reason for this is outlined in the Wikipedia article:
In the Hough transform, a main idea is to consider the characteristics of the straight line not as image points (x1, y1), (x2, y2), etc., but instead, in terms of its parameters, i.e., the slope parameter m and the intercept parameter b. Based on that fact, the straight line y = mx + b can be represented as a point (b, m) in the parameter space. However, one faces the problem that vertical lines give rise to unbounded values of the parameters m and b. For computational reasons, it is therefore better to use a different pair of parameters, denoted r and θ (theta), for the lines in the Hough transform.
And to transform between the two, use the equation y = -(cos(theta)/sin(theta))x + r/sin(theta). Thus m = -(cos(theta)/sin(theta)) and b = r/sin(theta). These obviously break down when sin(theta)=0 or theta=0, which is why the rotational coordinate system is preferred (there aren't any problems with lines with infinite slopes).
A: Polar coordinate system is 2-D coordinate system that has a reference point (like origin) called pole and a line from the pole called the polar axis. Each point in the Polar coordinate system is represented as (rho, theta) where 'rho' is the distance between the pole (origin) and the point and 'theta' is the angle between the polar axis and the line joining the pole and the point. See here.
The Polar coordinate (rho, theta) can be converted to Cartesian coordinate (x,y) using the following trigonometric equations.
x = rho cos theta ----(1)
y = rho sin theta ----(2)
Refer here for more info.
How do we get the above equations?
The equations use concepts of a right angle (trignonometry)
See the picture here.
cos theta = adjacent-side/hypotenuse = x/rho, thus we get (1)
sin theta = opposite-side/hypotenuse = y/rho, thus we get (2)
and Pythagorean theorem says,
hypotenuse^2 = adjacent side ^2 + opposite side^2, so
rho^2 = x^2 + y^2 ----(3)
Now let's derive the relationship between Cartesian coordinate (x,y) and Polar coordinate (rho,theta)
rho^2 = x^2 + y^2 ---- from (3)
rho^2 = x*x + y*y
rho^2 = x(rho cos theta) + y (rho sin theta) ---- from (1) and (2)
rho^2 = rho(x cos theta + y sin theta)
rho = x cos theta + y sin theta
A: Derivation:
The equation x/a + y/b = 1:
*
*defines a line
*has x-intercept = a
*has y-intercept = b
From trigonometry, recall how a ray rotated by angle t will project onto the x- and y- axes according to (angle=t, radius=1) -> (x=cos(t), y=sin(t))*
Draw the tangent line at the labelled point. Trigonometry (or even geometry with similar triangles) tells us that the tangent line intersects at x=1/cos(t), y=1/sin(t). Thus the line a distance 1 away will have a=1/cos(t) and b=1/sin(t), and thus described by x/(1/cos(t)) + y/(1/sin(t)) = 1...
... which is just cos(t) x + sin(t) y = rho where rho=1
You can see that rho corresponds to how far the line is from the origin (either by playing around with the equation, or by noting that multiplication here just scales all values by the same amount, effectively rescaling the grid).
*see http://en.wikipedia.org/wiki/File:Unit_circle.svg for credit
A: Each pair of rho, theta relates to an x,y pair for a given line in that the distance rho from the origin at angle theta places you at an x,y coordinate on the line.
The rho, theta equation is used instead of y=mx+b so that a sequence of rho, theta values can be put into the equation without computational problems that arise with the y=mx+b method where the slope is undefined (that is, the line is vertical).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Does git have an "I am an idiot" switch to prevent push -f without a branch? I just did a
git push -f
without including the branch I intended to push and git just blasted in everything to my repo. Fortunately we could piece together the old repo without to much trouble but it would be nice if I could change a setting in git to prevent -f all or make it so I have to do it explicitly.
Anyone aware of a setting I can change for this?
A: You can setup a pre-receive hook on the remote repo, that can prevent force push. You can also ensure that force push can only be done if explicitly specifying a particular branch.
You can also setup your local repository to change the default behaviour of the git push so that it will push only the current branch:
For example, to default to pushing only the current branch to origin
use git config remote.origin.push HEAD. Any valid (like the
ones in the examples below) can be configured as the default for git
push origin.
A: The git push.default option is exactly what you are looking for.
From git documentation at http://git-scm.com/docs/git-config:
push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:
*
*nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
*current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.
*upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).
*simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.
When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.
This mode will become the default in Git 2.0.
*matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).
To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.
This is currently the default, but Git 2.0 will change the default to simple.
In your situation, you might want to use git config --global push.default nothing to make sure you never push anything without specifying a refspec explicitely.
A: I don't think there is a setting for this. But I do agree that the mistake could be NOT including the branch name and force all to overwrite. If Git had a the ability, disable -f if no branch is specified. Maybe I'll submit a patch..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Click event outside MovieClip in AS3 Is there any way to detect if the user click outside a MovieClip?
For instance, I need to detect it to close a previously opened menu (like Menu bar style: File, Edition, Tools, Help, etc).
How can I detect this kind of event? Thanks!
A: Add a listener to stage and check if stage is the target of the event.
Example of code here:
http://wonderfl.net/c/eFao
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class FlashTest extends Sprite
{
private var _menu : Sprite;
public function FlashTest()
{
_menu = new Sprite();
_menu.x = 100;
_menu.y = 100;
_menu.alpha = 0.5;
with(_menu.graphics)
{
beginFill(0xFF0000, 1);
drawRect(0, 0, 300, 300);
endFill();
}
addChild(_menu);
_menu.addEventListener(MouseEvent.CLICK, onClickHandler);
stage.addEventListener(MouseEvent.CLICK, onClickHandler);
}
private function onClickHandler(event : MouseEvent) : void
{
switch(event.target)
{
case _menu:
_menu.alpha = 0.5;
break;
case stage:
_menu.alpha = 1;
break;
}
}
}
}
A: You can add a listener to the click event of the root element:
MovieClip(root).addEventListener(MouseEvent.CLICK, clickObject);
then in the function clickObject, you can check to see what you are clicking.
function clickObject(e:Event):void
{
var hoverArray:Array = MovieClip(root).getObjectsUnderPoint(new Point(stage.mouseX, stage.mouseY));
var hoverOverObject:* = hoverArray[hoverArray.length - 1];
}
hoverOverObject references the element that you are clicking on. Often this will be the shape within the movie clip, so you'll need to look at it's parent then compare it to your movie clip. If the click wasn't on the drop down movie clip, trigger the close.
A: var container:MovieClip = new MovieClip();
var mc:MovieClip = new MovieClip();
with(mc.graphics){
beginFill(0xff0000,1);
drawCircle(0,0,30);
endFill();
}
mc.name = "my_mc";
container.addChild(mc);
addChild(container);
stage.addEventListener(MouseEvent.CLICK, action);
function action (e:MouseEvent):void
{
if(e.target.name != "my_mc"){
if(container.numChildren != 0)
{
container.removeChild(container.getChildByName("my_mc"));
}
}
}
A: Use capture phase:
button.addEventListener(MouseEvent.CLICK, button_mouseClickHandler);
button.stage.addEventListener(MouseEvent.CLICK, stage_mouseClickHandler, true);
//...
private function button_mouseClickHandler(event:MouseEvent):void
{
trace("Button CLICK");
}
private function stage_mouseClickHandler(event:MouseEvent):void
{
if (event.target == button)
return;
trace("Button CLICK_OUTSIDE");
}
Note that using stopPropagation() is good for one object, but failed for several. This approach works good for me.
A: Use a stage and a sprite (menu) click listener with the sprite listener executing first and apply the stopPropagation() method to the click handler of the sprite. Like this:
menu.addEventListener(MouseEvent.CLICK, handleMenuClick);
stage.addEventListener(MouseEvent.CLICK, handleStageClick);
private function handleMenuClick(e:MouseEvent):void{
// stop the event from propagating up to the stage
// so handleStageClick is never executed.
e.stopPropagation();
// note that stopPropagation() still allows the event
// to propagate to all children so if there are children
// within the menu overlay that need to respond to click
// events that still works.
}
private function handleStageClick(e:MouseEvent):void{
// put hide or destroy code here
}
The idea is that a mouse click anywhere creates a single MouseEvent.CLICK event that bubbles from the stage, down through all children to the target, then back up through the parents of the target to the stage. Here we interrupt this cycle when the target is the menu overlay by not allowing the event to propagate back up to the parent stage, ensuring that the handleStageClick() method is never invoked. The nice thing about this approach is that it is completely general. The stage can have many children underneath the overlay and the overlay can have its own children that can respond to clicks and it all works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I ensure that the browser does not cache a page I need to make sure that the page is reloaded when going back to a page, without showing any messages to the user.
This must behave the same across all browsers.
A: The only way I have been able to achieve this reliably, especially with AJAX, is to append a query-string token on the page Url, such as DateTime.Now.Ticks.
You cannot count on <META> tags.
http://bla.com/bla.aspx?token=348343889
A: Try this:
EDIT - Added SetNoStore()
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
I think you can do it this way too:
<meta http-equiv="Expires" CONTENT="0">
<meta http-equiv="Cache-Control" CONTENT="no-cache">
<meta http-equiv="Pragma" CONTENT="no-cache">
Here's a solution that's specific for Safari:
<body onunload="" ...>
Here's another solution, but it's a bit of a hack:
<script type="text/javascript">
function noBack(){window.history.forward();}
noBack();
window.onload=noBack;
window.onpageshow=function(evt){if(evt.persisted)noBack();}
window.onunload=function(){void(0);}
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why can't I bind a value to this parameter when using PDO?
Possible Duplicate:
In PHP with PDO, how to check the final SQL parametrized query?
I am creating an in-memory SQLite database and attempting to run a query on it. I am preparing a SELECT statement and trying to bind a value - but it isn't working:
<?php
$db = new PDO('sqlite::memory:');
$statement = $db->query('CREATE TABLE test ( id INT )');
$statement->execute();
$statement = $db->prepare('SELECT id FROM test WHERE id = ?');
$statement->execute(array('12'));
echo $statement->queryString;
?>
I expect the script to output 'SELECT id FROM test WHERE id = "12"' but instead the script ignores the value I bound and outputs: 'SELECT id FROM test WHERE id = ?'.
What am I doing wrong, and how can I bind a value?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JasperReport - JavaBean Data Sources from official documentation JavaBean from official documentation:
http://jasperforge.org/uploads/publish/jasperreportswebsite/trunk/sample.reference/datasource/index.html#javabeandatasources
"For instance, to retrieve the value of a report field named address, the program will try to call through reflection a method called getAddress() on the current JavaBean object. "
From my experience, I'm almost certain that it is not on the current object, but on all JavaBean objects (of a given type) that are passed as a collection or a list.
When I try to print an atribute of a specific instance of a bean, it prints all the values of all instances of that bean. Anyone knows how to pass this?
A: How are you printing your attribute? If it is by putting a textField into a detail band, then that behaviour is correct. This is because the detail band is repeated once for every record in the dataset. If you are using a bean datasource this means that accessing the field address from the detail band will call getAddress() for every bean in the collection.
If you don't want an element to be repeated, move it to a different band. Or if you want to print the value only for a specific bean, add a printWhenExpression to your element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7613987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.