text stringlengths 8 267k | meta dict |
|---|---|
Q: Auto commit transactions if not explicitly committed or rolledback we use Weblogic server and always set autoCommit to 'false' when getting Connection to Oracle 10g.
I want to know if there is a setting in Weblogic wherein it will automatically Commit transactions if a Commit or Rollback is not explicitly called from within application code. I heard similar setting exists in Websphere.
A: It looks like you are not using either Container-managed or Bean-managed transactions. Or, for that matter, you are merely retrieving a connection from a DataSource and then disabling autocommit, without the initial establishment a transaction context; this implies that you are using JDBC transactions (that rely on the transaction manager of the underlying database).
When you use Container or Bean managed transactions, you will no longer have to worry about the autocommit property of a Connection used in a transaction, as the container will ensure that the autocommit property is set to false, before returning the Connection to the application.
If you need to use Container-managed transactions, you'll need to use EJBs. Any transaction associated with an EJB will commit automatically, unless a RuntimeException or an ApplicationException is thrown.
If you need to use Bean-managed or programmatic transactions, you will have to use the UserTransaction API.
If you are using an ORM framework like Hibernate that is responsible for establishing connections, then you ought to remember that it is Hibernate that is responsible for switching off the autocommit property of the Connection. and in most cases, it would switch off the property.
If you intend to use JDBC transactions, despite the better alternative of JTA transactions, then you could attempt to set the defaultAutoCommit property for the driver, from either Admin Console, or in the JDBC configuration file of the Datasource. The snippet of the JDBC configuration file is shown below:
<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://xmlns.oracle.com/weblogic/jdbc-data-source" xmlns:sec="http://xmlns.oracle.com/weblogic/security" xmlns:wls="http://xmlns.oracle.com/weblogic/security/wls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/jdbc-data-source http://xmlns.oracle.com/weblogic/jdbc-data-source/1.0/jdbc-data-source.xsd">
<name>JDBC Data Source-Oracle</name>
<jdbc-driver-params>
<url>jdbc:oracle:thin:@localhost:1521:oracle</url>
<driver-name>oracle.jdbc.OracleDriver</driver-name>
<properties>
<property>
<name>user</name>
<value>app</value>
</property>
<!-- Disable autocommit for connections-->
<property>
<name>defaultAutoCommit</name>
<value>false</value>
</property>
</properties>
...
In the Administration Console, you may add the defaultAutoCommit=false property in the Properties textarea of the DataSource configuration:
A: The connections configured inside of a connection pool on the App Server are not really closed when you call the connection.close() method, they are actually returned back to the connection pool, and can be used by the next requesting object. Not sure if the DataSource connection pools will track if there are uncommitted changes on a connection being returned to the pool and perform an auto commit or rollback on it?
A: Setting autoCommit to false is the right thing to do.
All RDBMS that I know of commit the transaction at the end unless explicitly rolled back. Do you see a different behavior? If you suspect something is wrong, one option is to turn on logging in the database server, where you would be able to see the commit request. I am afraid I don't know how to do it in Oracle.
Logging in app server may not be useful because it too may not be issuing explicit commit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I repeat a portion of a background image Is it possible to repeat-x and repeat-y just a specific portion of an image sprite? I can obviously separate the image into different files, but I was hoping there's a more efficient way of doing it.
A: Not for background - CSS3 provdes this for borders. You can combine a tiled background with a sliced border to achieve the desired effect.
(Browser support is not complete, though)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How i handle the game continue and external events in android(Andengine) I am developing the game using andengine.
How i handle the game continue options after redirect to home screen(press home key ) but the timer in running in background.
How to handle the external events (Incoming calls, sms). In j2me i used hideNotify and show Notify . How i make in andengine
A: You must make all of actions that will save the state of your app in onPause() method of the Activity. This method calls when the new activity put in the head of activity stack.
A: I think you should read this article containing the fundamentals about the activity lifecycle which pretty much covers all you need to know about how to handle an application going into background, exiting, coming back to front: http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with TAdvMemo component (about wordwrap) I am using TAdvMemo. My problem is with the WordWrap property. It works very well when I type text in the text area, but when I add a string to it in code, it has no effect.
I have set WordWrap property to: wwRightMargin and RightMargin property to 80, but not see other property that can help me, so i ask some idea as solve it?
i mean for example:
AdvMemo.Lines.Add(MyString);
where MyString is a string as: 'hello word'. When it is longer than 80 chars, and wrap is enabled, it should wrap to a new line, but instead it's all on the same line.
A: Try using AdvMemo.InsertText instead. Lines.Add doesn't care about wrapping, it just handles some special chars in the string.
A: After you added text to adv memo you must update wrap by calling UpdateWrap() function. Here is an example for you:
AdvMemo.Lines.Add(MyString);
AdvMemo.UpdateWrap();
or
AdvMemo.Lines.Text(MyString);
AdvMemo.UpdateWrap();
Be sure that WordWrap property of Adv Memo is different than wwNone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tool for debugging Borland & Visual Studio applications sometimes I have to debug an application that was written with Borland C++ Builder. This application loads dlls compiled with Visual C++. Is there a debugger that can debug both parts of the application? Currently I have to decide - either I can easily set break points and see the source in Visual Studio or I have to start Borland C++, but I can't work with the source from the Visual-Studio compiled dll.
thank you for your help,
Tobias
A: You could try OllyDbg - version 1.x does not seem to support the latest Win version but there is also the 2.0 although it's still in alpha state(haven't tried myself that one yet).
EDIT - clarification:
Source debugging OllyDbg reads debugging information in Borland and
Microsoft formats. This information includes source code and names of
functions, labels, global and static variables. Support for dynamical
(stack) variables and structures is very limited.
The above is take from here.
UPDATE:
I'm not familiar with the Borland C++ Builder but at this link you can find some articles explaining how to deal with some interoperability issues between Borland and MS that might be of help.
A: if both parts built using ulink linker and have debug info you could try cdb32 debugger (from the ulink linker author)
cdb32 is still in its alpha stage though and I personally never tried such "mixed" debugging
A: Have you tried loading the DLL code in VS, loading the app code in BCB, and having both debuggers attached to the same running process at the same time? Not sure if Windows will allow that, but it might be worth a try.
A: I suspect there is no perfect answer to your question, you are going to have to compromise in some way, as I'm sure you are already doing.
I have a similar problem to yours at work. The applications that I work on are written in Python instead of Borland C++, but like your situation, these apps rely on a rather large Visual Studio compiled DLL for some functions.
My method of debugging these applications involves a combination of two debugging strategies: the use of an interactive debugger and the so called "printf" debugging technique.
What I basically do is pick one of the two areas as my main debug focus, and that determines my debugging approach:
*
*If for a given situation I decide that I need to debug the DLL with greater detail, then I work with the VS debugger. I set the executable to run in the DLL project as my python script and that enables full debugging of the DLL code. If I need debugging support from the Python side, then I add print statements. If I need a breakpoint on the Python side to inspect some values, I just print all those values and immediately after call a C++ function that does nothing, but that has a breakpoint set in VS.
*When I need to concentrate more on the Python side more I use a Python interactive debugger, but I have VS with the DLL project loaded on the side so that I can quickly add any necessary printfs on the DLL and recompile, so essentially the reverse of the above.
I know it's not the answer you expect, but it is a decent solution in my opinion.
A: It looks that it is possible to convert the debugging information generated by C++ Builder to a format understood by WinDbg (link to discussion). If so you could use it to debug both parts of your application (I haven't tried this though).
A: you can convert the .map files to Microsoft's debug file format
http://code.google.com/p/map2dbg/
now you can use Windebug; there is also a tool mentioned to convert to pdb format, so you could try the vc++ debugger
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x80131522 I am getting the error
Msg 6512, Level 16, State 27, Line 6
Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x80131522. You need to restart SQL Server to use CLR integration features.
i am using SQL Server 2008 R2 Edition with windows 7. This error occur while creating the stored procedure. inside this stored procedure i am inserting some temp data in a variable table which has only a single column with HIERARCHYID as a the datatype
after some google i come to know that this is something related to CLR so i have enabled the clr in sql server
after that if i check "select * from dm_clr_properties" this says state as "CLR initialization permanently failed"
can anyone please help
A: SQLCLR initialization failed due to which you are not able to perform the insert. HierarchyID data type uses CLR objects. Have you tried repairing the .NET framework on the machine>
A: You should try running the following in the database that is giving you this problem:
select * from sys.assemblies --This is important to check.
select * from sys.dm_clr_properties --This is important to check.
If nothing is returned by sys.assemblies, then you have a problem.
If "state", from sys.drm_clr_properties, says something other than "CLR is initialized", then you have a problem.
You will need to reinstall the .net framework or try repairing it using this tool:
http://www.microsoft.com/en-us/download/details.aspx?id=30135
Note: Our DBA wasn't able to complete the repair because it required restarting the server which is a big deal for our production envrionment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can i define a mysql connection in Zend's application.ini file? I am new to Zend Framework. I want to initialize connection configration of zend and phpmyadmin.
Whats the code for that?
A: This connection is not between Zend and phpmyadmin. It is Zend-MySQL connection.
Please read following article. It includes basic information that how to connect to MySQL with Zend:
*
*Create a Model and Database Table
Here is a sample of application.ini database configuration:
[production]
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "mysqlhost"
resources.db.params.username = "mysqlusername"
resources.db.params.password = "mysqlpassword"
resources.db.params.dbname = "databasename"
resources.db.isDefaultTableAdapter = true
A: resources.db.params.charset = "utf8"
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "mysite"
resources.db.isDefaultTableAdapter = true
;resources.db.params.profiler = true ;if you use profiler
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can SerialPort.set_ReadTimeout throw IOException { NativeErrorCode = ERROR_OPERATION_ABORTED }? After sending a message out a SerialPort to a device, in preparation to read back its response, I tried setting the ReadTimeout and got back a rather oddball error:
System.IO.IOException was unhandled
Message="The I/O operation has been aborted because of either a thread exit or an application request.\r\n"
Source="System"
StackTrace:
at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
at System.IO.Ports.InternalResources.WinIOError()
at System.IO.Ports.SerialStream.set_ReadTimeout(Int32 value)
at System.IO.Ports.SerialPort.set_ReadTimeout(Int32 value)
There are no other threads accessing the SerialPort, and no event handlers registered with it (which I hope would rule out interference from the implicit thread behind the port).
In any case, though, it just seems weird to me: how can SetCommTimeouts fail with ERROR_OPERATION_ABORTED?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to catch whole screen re-paint event? (windows, c#) Is there any way to catch whole screen re-paint event? (windows, c#)
I want to do CopyFromScreen only after screen was updated, not by timer.
A: There is no such thing as a whole screen paint. The system optimises and only updates invalid regions. I don't know what you are trying to achieve (you didn't say) but it sounds like a remote desktop type application. They typically use mirror drivers.
A:
There is no such thing as a whole screen paint
*
*that is true, but the screen can't update faster than its refresh rate (60-80 fraps per second). You need to set a timer with that interval and to make screenshots in its Tick event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Data constraints in US state/county/city/zip database? I have a database of US zip codes and their corresponding states, cities and counties. It was supplied as a flat file and I'm trying to normalize the data and figure out exactly which entities depend on which others.
One problem I've come across is that some cities seem to exist in more than one county. I was under the impression that in the US, there is a hierarchy of State -> County -> City -> Zip.
However, this data seems to show otherwise for some cities:
Is my data set incorrect or is this actually a feature of US geography?
A: I am working with this same topic. I have learned that Virgina has cities that are not within a county. The city functions as both a city and county but in not within any county boundary. Also Alaska has no counties. Their equivilant is Boroughs, but the whole state is not divided into boroughs. Any area not within a borough is referred to as the "unorganized borough".
A: No, there isn't a clean hierarchy like that.
You're also liable to find cities that straddle state borders (cities in two states), and ZIP codes that take in more than one city. Not long ago, there were ZIP codes that straddled state borders, too. (ZIP codes are more about the route followed to deliver mail than about geography.) There might still be some.
As far as I know, no county is split between two states. But if there happened to be one, it wouldn't surprise me.
Depending on your application, you might discover even weirder things. I used to have to deal with addresses in the mountains that were "in" one county geographically, but were "in" a second county for emergency services (fire, police), and "in" yet a third county for non-emergency services (water, sewer, garbage collection). It depended on where the address was in relation to mountain ridges and roads.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XPath Query in JMeter I'm currently working with JMeter in order to stress test one of our systems before release. Through this, I need to simulate users clicking links on the webpage presented to them. I've decided to extract theese links with an XPath Post-Processor.
Here's my problem:
I have an a XPath expression that looks something like this:
//div[@data-attrib="foo"]//a//@href
However I need to extract a specific child for each thread (user). I want to do something like this:
//div[@data-attrib="foo"]//a[position()=n]//@href
(n being the current index)
My question:
Is there a way to make this query work, so that I'm able to extract a new index of the expression for each thread?
Also, as I mentioned, I'm using JMeter. JMeter creates a variable for each of the resulting nodes, of an XPath query. However it names them as "VarName_n", and doesn't store them as a traditional array. Does anyone know how I can dynamicaly pick one of theese variables, if possible? This would also solve my problem.
Thanks in advance :)
EDIT:
Nested variables are apparently not supported, so in order to dynamically refer to variables that are named "VarName_1", VarName_2" and so forth, this can be used:
${__BeanShell(vars.get("VarName_${n}"))}
Where "n" is an integer. So if n == 1, this will get the value of the variable named "VarName_1".
If the "n" integer changes during a single thread, the ForEach controller is designed specifically for this purpose.
A: For the first question -- use:
(//div[@data-attrib="foo"]//a)[position()=$n]/@href
where $n must be substituted with a specific integer.
Here we also assume that //div[@data-attrib="foo"] selects a single div element.
Do note that the XPath pseudo-operator // typically result in very slow evaluation (a complete sub-tree is searched) and also in other confusing problems ( this is why the brackets are needed in the above expression).
It is recommended to avoid using // whenever the structure of the document is known and a complete, concrete path can be specified.
As for the second question, it is not clear. Please, provide an example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Convert SQL Datareader to Dataset in C# I am exporting large set of records from database to Dataset which may be a cause for System.OutofMemory exception. To prevent this, as first step I have decided to use SQL Datareader. My concern is presentation should not be changed and there should be minimal code change in BL, I should write a method in DL which should retrieve data using SQL reader and fill the dataset and return to BL.
A: You can use DataTable.Load() method.
A: Whether you or the Framework fills the DataSet you'll have the OutOfMemoryException.
You have to return an IEnumerable and change the BL code to handle it.
Alternatively, you could try to set the DataTable.MinimumCapacity to avoid memory fragmentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I need to redirect the user to this one page in case of ANY kind of error I added this in my webconfig file but its not redirecting. It shows the aspx error as it is with the Stack Trace and all:-
<customErrors mode="RemoteOnly" defaultRedirect="myhomepage.aspx"/>
What could be wrong? Please help me out.
A: I think you need the values as mode="On" so that it shows up the custom errors. This will allow custom errors for remote clients as well as localhost (while you debug) and it is not the case for RemoteOnly which ignores the localhost.
More details refer here
A: The way you've got it set up at the moment is that it will show that page for any users that are not on the same computer that IIS is running on. If you're testing it from localhost then it won't work (unless as V4Vendetta suggested you set the Mode to On).
A: RemoteOnly means.. Remote Only. In other words, you see the YSOD (Yellow Screen Of Death) when you view the page with the error if you are browsing from the same computer as the program is executing on.
If you view it from a different computer, then you will see your custom error page.
If you want to see the custom error even when browsing locally, then use mode="On".
If you are still not seeing the custom error message, even if browsing remotely, it probably means you did not add it to the correct section of the web.config. It should be in
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="myhomepage.aspx"/>
</system.web>
</configuration>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing a .NET Datatable to MATLAB I'm building an interface layer for a Matlab component which is used to analyse data maintained by a separate .NET application which I am also building. I'm trying to serialise a .NET datatable as a numeric array to be passed to the MATLAB component (as part of a more generalised serialisation routine).
So far, I've been reasonably successful with passing tables of numeric data but I've hit a snag when trying to add a column of datatype DateTime. What I've been doing up to now is stuffing the values from the DataTable into a double array, because MATLAB only really cares about doubles, and then doing a straight cast to a MWNumericArray, which is essentially a matrix.
Here's the current code;
else if (sourceType == typeof(DataTable))
{
DataTable dtSource = source as DataTable;
var rowIdentifiers = new string[dtSource.Rows.Count];
// I know this looks silly but we need the index of each item
// in the string array as the actual value in the array as well
for (int i = 0; i < dtSource.Rows.Count; i++)
{
rowIdentifiers[i] = i.ToString();
}
// convenience vars
int rowCount = dtSource.Rows.Count;
int colCount = dtSource.Columns.Count;
double[,] values = new double[rowCount, colCount];
// For each row
for (int rownum = 0; rownum < rowCount; rownum++)
{
// for each column
for (int colnum = 0; colnum < colCount; colnum++)
{
// ASSUMPTION. value is a double
values[rownum, colnum] = Conversion.ConvertToDouble(dtSource.Rows[rownum][colnum]);
}
}
return (MWNumericArray)values;
}
Conversion.ConvertToDouble is my own routine which caters for NULLS, DBNull and returns double.NaN, again because Matlab treats all NULLS as NaNs.
So here's the thing; Does anyone know of a MATLAB datatype that would allow me to pass in a contiguous array with multiple datatypes? The only workaround I can conceive of involves using a MWStructArray of MWStructArrays, but that seems hacky and I'm not sure how well it would work in the MATLAB code, so I'd like to try to find a more elegant solution if I can. I've had a look at using an MWCellArray, but it gives me a compile error when I try to instantiate it.
I'd like to be able to do something like;
object[,] values = new object[rowCount, colCount];
// fill loosely-typed object array
return (MWCellArray)values;
But as I said, I get a compile error with this, also with passing an object array to the constructor.
Apologies if I have missed anything silly. I've done some Googling, but information on Matlab to .NET interfaces seems a little light, so that is why I posted it here.
Thanks in advance.
[EDIT]
Thanks to everyone for the suggestions.
Turns out that the quickest and most efficient way for our specific implementation was to convert the Datetime to an int in the SQL code.
However, of the other approaches, I would recommend using the MWCharArray approach. It uses the least fuss, and it turns out I was just doing it wrong - you can't treat it like another MWArray type, as it is of course designed to deal with multiple datatypes you need to iterate over it, sticking in MWNumerics or whatever takes your fancy as you go. One thing to be aware of is that MWArrays are 1-based, not 0-based. That one keeps catching me out.
I'll go into a more detailed discussion later today when I have the time, but right now I don't. Thanks everyone once more for your help.
A: As @Matt suggested in the comments, if you want to store different datatypes (numeric, strings, structs, etc...), you should use the equivalent of cell-arrays exposed by this managed API, namely the MWCellArray class.
To illustrate, I implemented a simple .NET assembly. It exposes a MATLAB function that receives a cell-array (records from a database table), and simply prints them. This function would be called from our C# application, which generates a sample DataTable, and convert it into a MWCellArray (fill table entries cell-by-cell).
The trick is to map the objects contained in the DataTable to the supported types by the MWArray-derived classes. Here are the ones I used (check the documentation for a complete list):
.NET native type MWArray classes
------------------------------------------
double,float,int,.. MWNumericArray
string MWCharArray
DateTime MWNumericArray (using Ticks property)
A note about the date/time data: in .NET, the System.DateTime expresses date and time as:
the number of 100-nanosecond intervals that have elapsed since January
1, 0001 at 00:00:00.000
while in MATLAB, this is what the DATENUM function has to say:
A serial date number represents the whole and fractional number of
days from a specific date and time, where datenum('Jan-1-0000
00:00:00') returns the number 1
For this reason, I wrote two helper functions in the C# application to convert the DateTime "ticks" to match the MATLAB definition of serial date numbers.
First, consider this simple MATLAB function. It expects to receive a numRos-by-numCols cellarray containing the table data. In my example, the columns are: Name (string), Price (double), Date (DateTime)
function [] = my_cell_function(C)
names = C(:,1);
price = cell2mat(C(:,2));
dt = datevec( cell2mat(C(:,3)) );
disp(names)
disp(price)
disp(dt)
end
Using deploytool from MATLAB Builder NE, we build the above as a .NET assembly. Next, we create a C# console application, then add a reference to the MWArray.dll assembly, in addition to the above generated one. This is the program I am using:
using System;
using System.Data;
using MathWorks.MATLAB.NET.Utility; // MWArray.dll
using MathWorks.MATLAB.NET.Arrays; // MWArray.dll
using CellExample; // CellExample.dll assembly created
namespace CellExampleTest
{
class Program
{
static void Main(string[] args)
{
// get data table
DataTable table = getData();
// create the MWCellArray
int numRows = table.Rows.Count;
int numCols = table.Columns.Count;
MWCellArray cell = new MWCellArray(numRows, numCols); // one-based indices
// fill it cell-by-cell
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
{
// fill based on type
Type t = table.Columns[c].DataType;
if (t == typeof(DateTime))
{
//cell[r+1,c+1] = new MWNumericArray( convertToMATLABDateNum((DateTime)table.Rows[r][c]) );
cell[r + 1, c + 1] = convertToMATLABDateNum((DateTime)table.Rows[r][c]);
}
else if (t == typeof(string))
{
//cell[r+1,c+1] = new MWCharArray( (string)table.Rows[r][c] );
cell[r + 1, c + 1] = (string)table.Rows[r][c];
}
else
{
//cell[r+1,c+1] = new MWNumericArray( (double)table.Rows[r][c] );
cell[r + 1, c + 1] = (double)table.Rows[r][c];
}
}
}
// call MATLAB function
CellClass obj = new CellClass();
obj.my_cell_function(cell);
// Wait for user to exit application
Console.ReadKey();
}
// DateTime <-> datenum helper functions
static double convertToMATLABDateNum(DateTime dt)
{
return (double)dt.AddYears(1).AddDays(1).Ticks / (10000000L * 3600L * 24L);
}
static DateTime convertFromMATLABDateNum(double datenum)
{
DateTime dt = new DateTime((long)(datenum * (10000000L * 3600L * 24L)));
return dt.AddYears(-1).AddDays(-1);
}
// return DataTable data
static DataTable getData()
{
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Price", typeof(double));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add("Amro", 25, DateTime.Now);
table.Rows.Add("Bob", 10, DateTime.Now.AddDays(1));
table.Rows.Add("Alice", 50, DateTime.Now.AddDays(2));
return table;
}
}
}
The output of this C# program as returned by the compiled MATLAB function:
'Amro'
'Bob'
'Alice'
25
10
50
2011 9 26 20 13 8.3906
2011 9 27 20 13 8.3906
2011 9 28 20 13 8.3906
A: One option, is to just open up .NET code directly from matlab, and have matlab query the database directly, using your .net interface instead of trying to go through this serialization process you describe. I have done this repeatedly in our environment with great success. In such an an endeavor
Net.addAssembly is your biggest friend.
Details are here.
http://www.mathworks.com/help/matlab/ref/net.addassembly.html
A second option would be to go with Matlab Cell Array's. You can set it up, so the columns are different data types, each column forming a cell. That is a trick matlab itself uses in the textscan function. I'd recommend reading the documentation for that function here:
http://www.mathworks.com/help/techdoc/ref/textscan.html
A third option, is to use textscan completely. Write a text file out from your .net code, and let textscan handle the parsing of it. Textscan is very powerful mechanism for getting this kind of data into matlab. You can point textscan to a file, or to a bunch of strings.
A: I have tried the functions written by @Amro but the result for certain dates are not correct.
What I tried was:
*
*Create a date in C#
*Use function to convert to Matlab date num as supplied by @Amro
*Use that number in Matlab to check its correctness
It seems to have problems with date with 1 Jan 00:00:00 for some years e.g. 2014, 2015. For example,
DateTime dt = new DateTime(2014, 1, 1, 0, 0, 0);
double dtmat = convertToMATLABDateNum(dt);
I got dtmat = 735599.0 from this.
I used in Matlab as follow:
datestr(datenum(735599.0))
I got this in return:
ans = 31-Dec-2013
When I tried 1 Jan 2012 it was OK. Any suggestion or why this happens?
A: I had the same issue as @Johan.
The problem is in Leap years that not calculate correctly the date
To fix it I change the code that converts the DateTime to the following:
private static long MatlabDateConversionFactor = (10000000L * 3600L * 24L);
private static long tickDiference = 367;
public static double convertToMATLABDateNum(DateTime dt) {
var converted = ((double)dt.Ticks / (double)MatlabDateConversionFactor);
return converted + tickDiference;
}
public static DateTime convertFromMATLABDateNum(double datenum) {
var ticks = (long)((datenum - 367) * MatlabDateConversionFactor);
return new DateTime(ticks, DateTimeKind.Utc);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery - disable selects which follow after I'm trying to create a number of dropdown menus which values depend on the previous selection.
What I'm trying to achieve is to get all following selects become disabled if the preceding one hasn't got the value selected.
Say someone has picked an option from the first one, second one and third one - then have selected a blank value from the first one - I would like all following ones - regardless of how many there are - become disabled again.
I've collected all selects in the form:
var sels = obj.closest('form').find('input[type="select"]');
I think that perhaps I should get the index of the selected one and then disable all other indexes, but don't quite know how to do it.
Here's the structure of the form:
<form action="" method="post">
<select name="option-1" id="option-1">
<option value="">Select one</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select name="option-2" id="option-2">
<option value="">----</option>
</select>
<select name="option-3" id="option-3" disabled="disabled">
<option value="">----</option>
</select>
</form>
Now - I know how to enable them - I just need to find out how to disable all relevant ones when the user changes one of the menu values to blank.
A: Given the following HTML:
<select>
<option value="0">-Choose-</option>
<option value="1">Valid option</option>
</select>
<select>
<option value="0">-Choose-</option>
<option value="1">Valid option</option>
</select>
<!-- As many selects as you like -->
The following jQuery should work:
var sels = $("select");
sels.not(":first").prop("disabled", true);
sels.change(function() {
if($(this).val() !== "0") {
$(this).next().prop("disabled", false);
}
else {
$(this).nextAll("select").val("0").prop("disabled", true);
}
});
You can see it in action here. It simply disables all but the first select, binds a change event to all of them, and in the event handler it checks to see if a valid value has been selected. If so, it enables the next select. If not, it disables it. Note that .prop requires jQuery version at least 1.6. If you have to use an older version, you can safely use .attr instead.
A: There is a great function in jQuery called: nextAll();
When you write event handler to select fields like below you can jump to all next selects with this function and disable them.
$("select").change(function(){
$("select").removeAttr("disabled");
if($(this).val()==0){
$(this).nextAll().attr("disabled","disabled");
}
});
You just need to specify properly which selects you want to affect.
A: There are a few elements of this, first off, you can find out what the index of the currently changed select is by using the .indexdocs method.
$('select').change(function(){
var $this = $(this);
// find the index of the changed selects within all selects
var index = $('select').index($this);
})
Secondly, you can disable all following selects using the gt()docs selector.
$('select').change(function(){
var $this = $(this);
var index = $('select').index($this);
$('select:gt(' + index + ')').attr('disabled',$this.val() == '');
});
Live example: http://jsfiddle.net/mQmfb/
A: You could have a look at the jquery plugins that would already deal with your issue. See this jquery plugin page for some examples.
Yet, if you want to enable selects when the previous one is selected, you'd probably better:
*
*disable all your selects at first.
*enable the first one when the page loads (or within your code, depending on how your HTML is created)
*enable the following select with a .change() event and the right selector (depending on your HTML code (hence you haven't posted it, we cannot help you more)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Crystal Reports - Data repeating if chart is included We are using Crystal Reports XI R3 for our reporting purposes. We have created typed dataset which act as the datasource for the reports.
I am facing an issue including a bar chart along with the grid on one of the reports. The chart gets embedded into the header section by default and the grid is generated out of the details section.
If I design the report without the chart, it all works fine. If I supply 8 rows of data, it publishes 8 rows in the report too. But if I include a chart on the same report, the data in the details section gets multiplied, and I get 64 rows or something with the same datasource.
This should be a pretty straight forward functionality, but it doesn't seem to be working for me. I tried include a sub-report and have the details section in the sub-report and it works fine. But, I can't go with this approach either as this report in itself would be included to another as a sub-report and we cant have nested sub-reports in Crystal.
Please help me with some pointers on what could be going wrong ?
Edit: On further investigation, it looks like a problem with having two different tables to populate the chart and the grid. If I use a single table for both, it works fine.
Attaching screenshot on @Kalyan's request:
A: The issue indeed was with using multiple unrelated tables for a single report. Crystal Reports by default doesn't allow using multiple tables, unless they are linked in someway. If you dont specify a link, it tries to apply a link on its own and runs a join while publishing the report.
Due to this join, the data was getting repeated for me.
To resolve the issue, I created a group on the primary key of the table corresponding to the grid, and used the group to generate the grid and suppressed the details section. Problem resolved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Ruby, delete null values of a string Example:
String test="hi\000\000\000"
Problem:
Some methods require a string to be without nulls, how can I delete all null values of a string?
.split("\000",1) gives me an error: 'force_encoding' method doesn't exist
.gsub('\000','') does nothing
A: Try using double quotes, so test.gsub("\000", '').
A: Right now I tried this in JRuby and it worked:
test.gsub(/\000/, '')
Note that I am using a regex in the gsub and not a string.
A: Even more simple:
test.delete("\000")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SQL 2008 - pipe delimited string split How can a split pipe delimited string value in SQL into separate columns eg.
2008|1245|0|1004|1224|0|
into
FirstValue SecondValue ThirdValue ForthValue FifthValue SixthValue
2008 1245 0 1004 1224 0
Using a simple select script.
Thank you
A: Try out
CREATE FUNCTION dbo.fnSplit(
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = '|' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO
--Test
select * from fnSplit('2008|1245|0|1004|1224|0|','|')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .htaccess loop redirect error I have a .htaccess that's supposed to force connection using SSL. It works well on localhost, when I take it online I have all manner of errors.
Here is my code.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z]*)/?$ goto.php?page=$1
ErrorDocument 404 PageNotFound
IndexIgnore *
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
Where am I missing it please, thank you.
A: The problem is here:
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
The ^(.*)$ matches everything so will keep matching even after it has redirected the user to https, thus the infinite loop.
So you need to make this rule only match when it is required, the folloing RewriteCond should cause the rule to only match whilst https is off, which should stop the infinite loop:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extracting ClusterName RegularExpressions I have a regular expression which will give the computername, cluster name & OSinfo
Get-QADComputer | ? {$.osname -match "2008" -and $.computername -match "hv"} |
Select @{Name="ComputerName";Expression={$_.computername.replace("$","")}}
,@{Name="ClusterName";Expression={$.computername.replace("$","");$.computername.replace("n[0-9][0-9]","")}},@{Name="OperatingSystem";Expression={$_.osname}}
Now the problem im facing is in extracting the clustername,
for example if output of computer name is ADFCGS1N01$, i wanted the cluster name to look like ADFCGSN1, i wanted to remove all the characters after N to get cluster name,
Can some one please help me with the same
A: Does this gives you the correct value?
Get-QADComputer -OSName *2008* -Name *hv* | Select -ExpandProperty Name
Per your comment, remove the N+2 digits from the end of name, including the dollar (if exists):
Get-QADComputer -OSName *2008* -Name *hv* | Foreach-Object {$_.Name -replace 'N\d{2}\$?$'}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change the color of image android I want to change the color of image that exist in imageview. i got the image from imageview in Bitmap object and applied colormatrix on it.
The problem is that , once i change the color of image, it doesn't change bt override the previous color,
I want that , when i change the color, the previous color of image should be removed and any specific color that i choose is applied.
i am using the following code to do that...
void setImageColor(RGBColor rgbcolor,ImageView view)//,Bitmap sourceBitmap)
{
view.setDrawingCacheEnabled(true);
Bitmap sourceBitmap = view.getDrawingCache();
if(sourceBitmap!=null)
{
float R = (float)rgbcolor.getR();
float G = (float)rgbcolor.getG();
float B = (float)rgbcolor.getB();
Log.v("R:G:B",R+":"+G+":"+B);
float[] colorTransform =
{ R/255f, 0, 0, 0, 0, // R color
0, G/255f, 0, 0, 0, // G color
0, 0, B/255f, 0, 0, // B color
0, 0, 0, 1f, 0f
};
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0f); //Remove Colour
colorMatrix.set(colorTransform);
ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
Paint paint = new Paint();
paint.setColorFilter(colorFilter);
Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true);
view.setImageBitmap(mutableBitmap);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawBitmap(mutableBitmap, 0, 0, paint);
}
else
return;
}
A: Declare a static sourceBitmap and do this only once: Bitmap sourceBitmap = view.getDrawingCache(); let's say in onResume() of your activity (or when you change the image from ImageView).
And your function should be:
void setImageColor(RGBColor rgbcolor, ImageView view, Bitmap sourceBitmap) {
if (sourceBitmap == null) return;
float r = (float) rgbcolor.getR(),
g = (float) rgbcolor.getG(),
b = (float) rgbcolor.getB();
Log.v("R:G:B", r + ":" + g + ":" + b);
float[] colorTransform =
{
r/255, 0 , 0 , 0, 0, // R color
0 , g/255, 0 , 0, 0, // G color
0 , 0 , b/255, 0, 0, // B color
0 , 0 , 0 , 1, 0
};
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0f); // Remove colour
colorMatrix.set(colorTransform);
ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
Paint paint = new Paint();
paint.setColorFilter(colorFilter);
Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true);
view.setImageBitmap(mutableBitmap);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawBitmap(mutableBitmap, 0, 0, paint);
}
This way you will hold the unaltered image and apply the filters on the original.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to clip text in android canvas? I'm creating kids learning application in android.
I created Imageview on which text is displayed and i applied canvas for Imageview so i can able to
paint on whole canvas. Upto this working fine.
Now my problem is i have to clip the text present in canvas imageview.
I know to clip the region with shapes like Rect , Circle but dont know how to clip the text in android canvas... Also the clipped region must allows me to paint only the clipped region ( not the region other than text view in Imageview .)
Help with some sample code is appreciated.
A: Finally i found the solution for my question...
If you want to clip the textview in android you have an method called getTextPath()
that will give you the outline of the text which holds the glyph for the text and apply
canvas .clipPath(path);
Now i can able to clip the text view in android canvas....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to retrieve records for last few hours in SQL Server theyI had a asp.net (vb) web application to store work overtime (OT) records.
In SQL server, the OT table likes this, e.g.:
ot_key | From Time | To Time | total_min
12 | 2011-09-22 10:00 | 2011-09-22 13:00 | 180
13 | 2011-09-24 14:00 | 2011-09-24 15:00 | 60
14 | 2011-09-23 12:00 | 2011-09-23 14:30 | 150
15 | 2011-09-24 18:00 | 2011-09-24 19:30 | 90
As user will input previous date OT records, so the records in db will not be in sequence. the date of records#14 is before records#13.
if user want to know which OT records cover the last 2 hours, the system should retrieve record #15 (90mins) & #13 (30mins) because they covers the final 2 hours.
How to write the SQL statement to retrieve the records ? Thanks
Joe
A: if I understand correctly, all you need to do is this (but its weird the way you phrased your question, so I'm not sure this what you are looking for.
select * from OT where total_min <=
[number of hours expressed in minutes]
A: CREATE TABLE OT (
[ot_key] INT,
[From Time] DATETIME,
[To Time] DATETIME,
[total_min] INT
)
INSERT OT
VALUES (12,'2011-09-22 10:00', '2011-09-22 13:00', 180),
(13, '2011-09-24 14:00', '2011-09-24 15:00', 60),
(14, '2011-09-23 12:00', '2011-09-23 14:30', 150),
(15, '2011-09-24 18:00', '2011-09-24 19:30', 90)
Query:
DECLARE @CoverTime INT = 120
;WITH cteOTRN AS (
SELECT ROW_NUMBER() OVER (ORDER BY [To Time] DESC) AS [ROW_NUMBER], *
FROM OT
)
, cteOTRT AS (
SELECT *
FROM cteOTRN ot
CROSS APPLY (
SELECT SUM([total_min]) AS [RunningTotal]
FROM cteOTRN
WHERE [ROW_NUMBER] <= ot.[ROW_NUMBER]
) rt
)
SELECT *, [total_min] AS [CoverTime]
FROM cteOTRT ot
WHERE [RunningTotal] <= @CoverTime
UNION
SELECT TOP 1 *, [RunningTotal] - @CoverTime
FROM cteOTRT ot
WHERE NOT ([RunningTotal] <= @CoverTime)
AND NOT EXISTS (
SELECT *
FROM cteOTRT ot
WHERE [RunningTotal] = @CoverTime
)
ORDER BY [To Time] DESC
See also Calculate a Running Total in SQL Server
A: Do a
select * from OT where datediff(hour,ToTime,getdate()) < 2
which will give you the posts where the difference between currenttime and totime is less than 2 hours.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Text input with 100% width inside a td expands/continues outside the td Here is the live demo
I'm trying to put a padded text input inside a td, and I want it to occupy 100% of the width, but it goes outside of the td.
I don't understand why that happens, anybody knows?
CSS
table{
border: solid 1px gray;
width: 90%;
}
input{ width: 100%; padding:10px; }
HTML
<table>
<tr>
<td style="width:150px;">Hello</td>
<td><input type='text' value='hihihih'/></td>
</tr>
</table>
A: Explanation
Here's a link to the W3C Box model which explain in detail what happens to your element.
- - - - -
All input elements have borders by default and may also have padding and margins, but most importantly, it follows the W3C box model specifications using the content-box.
This means that if you set the width to 100%, the actual size of the element will be greater than 100% when you include padding/borders, as shown in the images above.
Solution
Add padding to the td to manually adjust the width of the input until it's where you want it to be. Remember that adding padding to the input means you have to add the same amount to the td to counteract the expansion.
Here's a live example
input {
width: 100%;
padding: 10px;
margin: 0px;
}
table .last, td:last-child {
padding: 2px 24px 2px 0px;
}
Alternative solution
You can also do the CSS3 version using box sizing (browser compatability).
This property can be used to switch between the two box models and will make it behave like you'd expect it to.
Here's a live example
input {
width: 100%;
padding: 10px;
margin: 0px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
Here are some possible duplicates of the same question
*
*can i stop 100% width text boxes from extending beyond their containers
*Problem with input type='text' and textarea width
*100% Width div's and form elements + padding?
A: Simple. 100% width + padding, thats why. You should set padding for wrapper, not input
A: you can use box-sizing property for this because padding add width in your input field .
CSS:
input {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
}
but it's not working IE7
A: Easiest way is to set the padding as a percent of width, subtracted from 100%.
So:
input {
width:96%;
padding:0 2%;
}
A: I have found
<td><input type='text' value='hihihih'/>
works funny, try
<td> <input type='text' value='hihihih'/>
it seems to work wonders
Though to be truthful was using size= a number as opposed to width=100%
for some unknown reason the text was outside the table!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: creating local database for reminder in Mango There ia reminder application and there is a need to create a localDatabase table for reminder keep the enteries into its table.
how do i create a local database for Reminder Enteries in Windows phone mango?
A: You can use LinQ to Sql to create your database in designer and save it in isolated storage.
MSDN local database Sample
There is an easier way to do it :
Corrado's Blog
I used this example for my application, and it works like a charm, i copied the whole Linq to Sql dbml into my Wp7 project and it works. Just don't forget to delete or comment out the two unsupported constructors.
A: http://sterling.codeplex.com/
You can use serling as well to store your Reminder entries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the java.security.PrivateKey object from RSA Privatekey.pem file? I have a RSA private key file (OCkey.pem). Using java i have to get the private key from this file. this key is generated using the below openssl command.
Note : I can't change anything on this openssl command below.
openssl> req -newkey rsa:1024 -sha1 -keyout OCkey.pem -out OCreq.pem -subj "/C=country/L=city/O=OC/OU=myLab/CN=OCserverName/" -config req.conf
The certificate looks like below.
///////////////////////////////////////////////////////////
bash-3.00$ less OCkey.pem
-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,EA1DBF8D142621BF
BYyZuqyqq9+L0UT8UxwkDHX7P7YxpKugTXE8NCLQWhdS3EksMsv4xNQsZSVrJxE3
Ft9veWuk+PlFVQG2utZlWxTYsUVIJg4KF7EgCbyPbN1cyjsi9FMfmlPXQyCJ72rd
... ...
cBlG80PT4t27h01gcCFRCBGHxiidh5LAATkApZMSfe6BBv4hYjkCmg==
-----END RSA PRIVATE KEY----- //////////////////////////////////////////////////////////////
Following is what I tried
byte[] privKeyBytes = new byte[(int)new File("C:/OCkey.pem").length()];
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(privKeyBytes));
but getting
"java.security.spec.InvalidKeySpecException:
java.security.InvalidKeyException: invalid key format"
Please help.
A: Make sure the privatekey is in DER format and you're using the correct keyspec. I believe you should be using PKCS8 here for the privkeybytes
Firstly, you need to convert the private key to binary DER format.
Heres how you would do it using OpenSSL:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
Finally,
public static PrivateKey getPrivateKey(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Hotmail - automatically encode the URL I'm developing an application with PHP that sends emails to customers. The body of the email contains a URL hyperlink back to our site kind of like this:
http://myserver/myfolder/test.cfm?id=una-bottiglia-di-vino-©-®
The above url contatins copyright and registered symbols
In Yahoo, GMail, Outlook, etc. the link displayed as I sent. However Hotmail displays the href url as encoded
http://myserver/myfolder/test.cfm?id=una-bottiglia-di-vino-%a9-%ae
A: In your mail you just do urlencode($myUrl);
More information: http://php.net/manual/en/function.urlencode.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the IP address of an amazon EC2 instance on reboot On reboot, the IP address of an amazon instance changes. How to find the new IP address using java API?
A: curl http://169.254.169.254/latest/meta-data/public-ipv4
A: Assuming you don't want to assign an Elastic IP address (and there are reasons why this is not always a solution) then simply call DescribeInstances on the rebooted instance, which returns a bunch of information including Public IP Address.
Here's the AWS EC2 Java API Documentation on the topic.
A: The public IPv4 address is also available from the EC2 instance like so:
curl checkip.amazonaws.com
And the public hostname is:
dig -x $(curl -s checkip.amazonaws.com) +short
A: this is how I did it on an Ubuntu 12.04 EC2 instance within a VPC:
curl ifconfig.me
not sure why but public-ipv4 was not found under the meta-data url
A: On reboot, the IP addresses of an EC2 instance do not change. They do generally change on stop/start of a non-VPC EBS boot instance.
See my answer to your related question here:
https://stackoverflow.com/questions/7533871/difference-between-rebooting-and-stop-starting-an-amazon-ec2-instance
That said, you can find the private and public IP addresses through the API call for DescribeInstances in your particular language.
If you are on the instance itself, you can also find the IP addresses through the user-data API using simple HTTP:
http://instance-data/latest/meta-data/local-ipv4
http://instance-data/latest/meta-data/public-ipv4
For example,
wget -qO- http://instance-data/latest/meta-data/public-ipv4
Elastic IP addresses are recommended for keeping a consistent (static) externally facing IP address for a particular service or server. These need to be re-assigned to an instance after a stop/start (but not after a reboot).
A: In order to fetch the public IP of the instance you first need to get the instance id of that instance. You can get the instance id of the instance by using the following java code.
List<Instance> instances = runInstancesResult.getReservation().getInstances();
String instanceId = instances.get(0).toString().substring(13, 23);
And now in order to get the public IP you can use the following java code.
public void fetchInstancePublicIP() {
DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds("i-d99ae7d2");
DescribeInstancesResult result= ec2.describeInstances(request);
List <Reservation> list = result.getReservations();
for (Reservation res:list) {
List <Instance> instanceList= res.getInstances();
for (Instance instance:instanceList){
System.out.println("Public IP :" + instance.getPublicIpAddress());
System.out.println("Public DNS :" + instance.getPublicDnsName());
System.out.println("Instance State :" + instance.getState());
System.out.println("Instance TAGS :" + instance.getTags());
}
}
}
A: They have util class which facilitates access to EC2 metadata.
For instance
EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicHostname();
EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicIPv4s();
A: Assuming your rebooting the instance and not launching from scratch than you can assign an elastic IP which always remains with the ec2 instance(unless you move the IP to another server). This allows you to point all your DNS to that one IP and not worry that a reboot will cause you issues.
I think thats what your asking but there are other things you could be asking. The internal IP of the server changes(if you relaunch the instance not reboot) and you can't 'reserve' it so you may need to create a script to keep you the new IP(if your pointing internal services to it).
hope that helps
A: you Can Use This.
var ipofnewServer = string.Empty;
while (string.IsNullOrEmpty(ipofnewServer))
{
var statusRequest1 = new DescribeInstancesRequest
{
InstanceIds = new List<string>() { instanceId }
};
var result = amazonEc2client.DescribeInstances(statusRequest1);
var status = result.Reservations[0].Instances.FirstOrDefault();
if (status != null)
{
ipofnewServer = status.PublicIpAddress;
}
}
A: You can use CLI CRUD aplication to AWS resources.
AWS-CRUD-Manager
To find all ec2 instances
./awsconsole.py ec2 all
To find all of data for one ec2 instances (including IP priv and public)
./awsconsole.py ec2 find -i <id-insta`ce>
A: I was using domain=$(hostname | cut -d "." -f1) however that was getting the ip as ip-1-2-3-4. Are you not able to use hostname -i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: Error in compiling VB6 active x dll I have an Active X dll created in VB6. I made some changes in the code and now when I am trying to compile it, it throws an error "Error Accessing the System Registry".Now I am not logged in to the machine as admin or in its group.
Any help would be much appreciated.
A: Are you running on Windows 7? If so, the User Account Control (UAC) is preventing the build. When you launch Visual Studio 6, first right click on the icon and choose to run as administrator. This should resolve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I implement a search service which uses proximity to a location as a ranking parameter I have a data set over which I need to implement a location based search service. I will filter the data initially based on keyword arguments and then I need to sort them based on proximity to the user's location. How do I go about implementing this, some pointers on the kind of algorithms/approaches to use, or tips on modeling the data will be really helpful.
A: You could use a database with geo support like postgis:
SELECT * FROM points ORDER BY distance(point1, point2)
A: Approach -
you can think of Apache Solr (open source search engine) @ http://lucene.apache.org/solr/
It will help you to search across keywords and provides geo spatial capabilities.
http://wiki.apache.org/solr/SpatialSearch
Caution - may be an overhead or completely out of context as well, suggested just as an option. As am not sure for the quatity of data, format of the data, what search capabilties you need.
A: When I add a listing to my DB, I run the address/postcode though a geocoding service such as Google or Yahoo. I then store these lat/lng values with the listing. When the user searches I take their location and again run this through a geocode, and then I can sort by proximity.
Similar to something like this:
http://maurus.net/resources/distance-queries/
A: Here's an idea where you build it without using API from other services.
I assume you want to show all the data to the client. If not you could query your DB with min max lat,lon values to restrict the area.
Let's imagine the client wants to see closest restaurants from coordinate x,y
From clientside you send webservice query showdata(lat,lon,type)
At serverside: First you query your DB, select where type == restaurant. This give you a list of restaurants with lat,lon coordinates. You iterate the list and calculate the distance from the clients lat,lon values and insert the result in the items list.
class Item
{
Distance
Name
Lat
Lon
}
List<Item> items
As the last step you sort your items list by Distance value and return the result to your client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DOS batchfile is skipping FOR delims I'm trying to parse a text file, and it's working apart from skipping a column if it's empty.
Here's the file format:
206695844 66583369 L CAT 1 1 4144042 214857 64378180 L 4144039 214853 Y
206669467 127810625 R CAT 38 1 4136724 213413 724749204 R 4136727 213420 Y
206445106 65588013 L CAT 4 1 4139084 210381 64363708 L 4139082 210372 Y
^
empty column
As you can see, there are 14 columns, each seperated by a tab character.
My parsing line is:
FOR /F "tokens=1,2,5,7,8,9" %%i in (datafile.txt) DO (
echo %%i %%j %%k %%l %%m %%n >> outputDatafile.txt
)
The problem is it's skipping the 9th column (blank in example), and using the 10th instead, as in:
206695844 66583369 1 4144042 214857 64378180
I want that 9th column - even if empty!
I've also tried using an explicit tab character as a delimiter, because the help for FOR says:
delims=xxx
- specifies a delimiter set. This replaces the default delimiter set of space and tab:
FOR /F "tokens=1,2,5,7,8,9* delims= " %%i in (datafile.txt) DO (
^tab
What am I doing wrong?
EDIT
jeb got it - thanks!
to spit out the result to my file, i just use:
echo (!col1!%tab%!col2!%tab%!col3!%tab%!col4!%tab%!col5!%tab%!col6!) >> outputFile.txt
A: The delim mechanism works the way that one ore more consecutive delims are reduced to a single delim, that's why you can't get an empty column this way.
But in your case it seems easy to replace the delims with a delim and a none delim character.
Like:
set "line=#!line:<TAB>=<TAB>#!"
Then each column is prefixed by a #, so you can get even "empty" columns.
You only need to remove always the first character.
setlocal EnableDelayedExpansion
set "tab= "
FOR /F "delims=" %%L in (datafile.txt) DO (
set "line=%%L"
set "line=#!line:%TAB%=%TAB%#!"
for /F "tokens=1,2,5,7,8,9 delims=%TAB%" %%1 in ("!line!") DO (
echo %%1, %%2, %%3, %%4, %%5, %%6
set "col1=%%1"
set "col1=!col1:~1!"
echo(!col1!
)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Javascript :checked function with a repeater in ASP.NET I am currently working on a project that needs to forward an email to every selected customer inside a repeater. I am working with a checkbox that I assign the email-address as value inside an asp repeater.
<ItemTemplate>
<div class="odd">
<asp:label ID="lblT" runat="server" style="visibility:collapse; margin-left:9999px;" Text='<%# Eval("exposantID") %>'></asp:label>
<input runat="server" type="checkbox" class="chkExpo" id="chkExpo" value='<%# Eval("exposantMail") %>' />
Now I'm using jQuery :checked statement to get every checked checkbox inside the repeater.
var n;
function countChecked() {
n = $("input:checked").length;
}
$(":checkbox").click(countChecked);
countChecked();
$("input").click(function () {
for (var i = 0; i < n; i++) {
alert($("input:checked").val());
}
});
The problem is I can only get the first checked value...I tried working with an index value but that didn't solve the problem. Does anyone have an idea how to get the value for each checkbox that is checked using this method?
Thanks,
Arnoud
A: $("input[type='checkbox']").click(function () {
$("input[type='checkbox']:checked").each(function(){
alert($(this).val());
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: smarty - two or more inequality conditions in one bracket? This is my code in smarty:
{if $cat!="1_5"} do something {/if}
If I add additional condition with or:
{if $cat!="1_5" or $cat!="2_30"} do something {/if}
Then it doesn't work in proper way. Why? Is this possible to use in one brackets two or more inequality conditions?
A: Alright, so we have the categories 1_5 and 2_30
let's see what happens in your if-condition when $cat="2_30"
$cat!="1_5" $cat!="2_30" $cat!="1_5" $cat!="2_30"
| | | |
TRUE FALSE TRUE FALSE
\ / \ /
\ / but: \ /
\ / \ /
OR AND
| |
TRUE FALSE
//do something //don't do something
So, you get the idea :) You have to use AND instead of OR:
{if $cat!="1_5" and $cat!="2_30"} do something {/if}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: best way to handle events and notifications from multiple sources to a main form in vb.net I have a vb.net application in which there is a main form. There are around 10 classes each having their own functionalities like tcpactions, fileactions, serialport actions etc. The user interacts with the main form and does certain actions which will invoke the methods in these classes. Now I have a notifications textarea in the mainform and i want to show the current action being performed in those classes and their results in the notifications area.
for example when a user clicks a "Start Process" Button in the form i invoke the method "launchprocess" in a class "ProcessActions". Now this method tries to launch about 7 different process and after launching it sends notification such as "process 1 launched" or if it fails it sends notifications such as "process 1 launch failed".
I currently use event handlers and use them to show notifications but with the amount of events i have to handle it is getting cumbersome and i might have to add even more classes in the future. So is there a better way of handling notifications from other classes.
A: I would suggest using a common custom event handler in all of the classes that the main form can respond to. First define a new EventArgs class to handle the notifications you're sending back:
Public NotInheritable Class NtfyEventArgs
Inherits EventArgs
Private _Action As String
Public ReadOnly Property Action As String
Get
Return _Action
End Get
End Property
Public Sub New(ByVal action As String)
_Action = action
End Sub
End Class
Next define a base class to raise the notifications:
Public Class Base
Public Event Ntfy(ByVal sender As Object, ByVal e As NtfyEventArgs)
Protected Sub RaiseNtfy(ByVal action As String)
RaiseEvent Ntfy(Me, New NtfyEventArgs(action))
End Sub
End Class
Have each of your other classes inherit from the base class. Then it becomes quite easy to send a notification:
Public Class ProcessActions
Inherits Base
Public Sub LaunchProcess
'Do stuff
RaiseNtfy("Process 1 launched")
'Do more stuff
RaiseNtfy("Process 2 launched")
End Sub
End Class
Finally in your main form, listen for any events raised by the child classes
Public Class Form1
Private WithEvents process As New ProcessActions
Private WithEvents file As New FileActions
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Add Event handlers
AddHandler process.Ntfy, AddressOf HandleNtfy
AddHandler file.Ntfy, AddressOf HandleNtfy
End Sub
'One procedure to handle all the incoming notifications
Private Sub HandleNtfy(ByVal sender as Object, ByVal e as NtfyEventArgs)
lblNtfy.Text = e.Action
'If need to take different actions based on the class sending notification
If TypeOf(Sender) Is ProcessActions Then
'Specific code for ProcessActions
End If
End Sub
End Class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Search Events and News via Calendar Portlet Event items are searchable in Plone's default calendar portlet. When clicking on a date when an event occurs, it uses search?review_state=published&start.query:record:list:date... to look for events. How can I add News Item, or even custom types to be searchable in calendar portlet?
A: In the ZMI there's a tool portal_calendar:
http://<localhost>:8080/plone/portal_calendar/manage_configure
In the configure tab there's a select list where you can specify any content type to be shown. The only condition is that they have to provide start & end attributes that return DateTime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to open HTML file having another extension in JTextPane I have a HTML file and I need to display it in JTextPane.
editor.setPage("file:///" + new File("test-resources/test.html").getAbsoluteFile());
This works properly. It uses my modified HTML editor kit and displays special tags as needed. But modified file is not exactly HTML. It should have another extension. But that's a problem.
editor.setPage("file:///" + new File("test-resources/test.xhtbm").getAbsoluteFile());
The file has been just renamed and is being displayed as plain text now. Is there some way to force JTextPane to open HTML file with extension XHTBM as HTML file? Am I forced to use HTML extension if using JTextPane?
A: One alternative is to use a JEditorPane and call JEditorPane.setContentType(String).
See setContentType(String) for details.
..For example if the type is specified as text/html; charset=EUC-JP the content will be loaded using the EditorKit registered for text/html and the Reader provided to the EditorKit to load unicode into the document will use the EUC-JP charset for translating to unicode..
A: The solution has been found (see the post JEditorPane and custom editor kit):
public void openFile(String fileName) throws IOException {
editor.setEditorKit(new ModifiedHTMLEditorKit());
ModifiedHTMLDocument doc = (ModifiedHTMLDocument)editor.getDocument();
try {
editor.getEditorKit().read(new FileReader(fileName), doc, 0);
}
catch (BadLocationException b) {
throw new IOException("Could not fill data into editor.", b);
}
}
This is the proper technique.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Are virtual machine images reverted in windows azure? If I deploy a virtual machine image to windows azure.
Will the virtual machine be able to keep state or will it be reverted to the original state sometimes?
e.g. if the virtual machine hosts sql server (e.g. to enable full text serach which is not present in sql azure)
is there a chance that I lose my data sometimes then?
A: (EDIT -- this answer was relevant for the PaaS style of Azure deployments; the new IaaS virtual machines do have persistent storage. See http://michaelwasham.com/2012/06/08/understanding-windows-azure-virtual-machines/ for more details)
No, the virtual machine will not, officially, keep any state at all. In theory a new virtual machine could be created and your traffic routed to that new instance without your knowledge, for example after a patch update or anything else for that matter.
So use AzureBlobDrive or table storage or SQL Azure if you want to store something that won't go away.
In practice, however, Azure instances currently have three drives:
*
*C: holds logs
*D: holds the operating system
*E: (and F:) hold your application
On a fresh deployment or a "reimage" these three drives are created from scratch.
On a reboot, however, it seems that C: and D: stay as they were, but the drive with your application is reset.
On an upgrade deployment things get interesting. Drives C: and D: stay unchanged, but after the host is taken offline by the load balancer a new drive F: is created with the new version of the application. Your IIS instance is reset to point to this new drive, then the old drive E: is removed, then the load balancer reconfigured to bring the host back on line. At the next upgrade your application will swap back to drive E:.
The advantage of this is that upgrades don't take nearly so long as full deployments. The downside is that changes to IIS configuration (e.g. endpoints, certificates) can't be done with an upgrade but need a full deploy instead.
So in practice it can be feasible to temporarily store data on C:, for something like logging. But don't rely on it.
A: The disks on a VM role are not durable. When the instance transitions (i.e. the OS moves from one machine to another) you're back to square one.
You could mount a VHD drive to persist data, however only one instance can write to the drive.
BTW, using a VM role to host a SQL Server is a bad idea, use SQL Azure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to pause visualizer for a few secs? I am recording the sounds using microphone and plotting a visualization based on the visualization, the visualizer goes pretty fast and i can't analyze the data. Is there any way i could pause the visualizer or slow down the visualizer?
A: You can use the debug mode and set break points to step into the function and analyze the data.
As you know the data is a 1024 byte array. You can check the size using getCaptureSize(),
And whenever you are using getFft() or getWaveForm(), you will be able to see the individual elements of the array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loading of a Dynamically created Entity by automatic dyscovery I have to work with a strange DB structure, where on production there could be more tables but with same columns. And we want to use JPA (Hibernate) with handle them, by entities/JPQL queries. The idea is to create entity classes for each table dynamically within JVM at runtime. This approach works fine. I create Entities with Javassist - using an already existing compiled entity, and I add annotations to it dynamically (Entity, Table):
public Class generateGroupStateEntity(String className,String tableName) {
ClassPool cp = ClassPool.getDefault();
InputStream is = new FileInputStream(new File("MyTemplateEntity.class"));
CtClass c = cp.makeClass(is);
c.setName(className);
ClassFile cf = c.getClassFile();
ConstPool constPool = cf.getConstPool();
AnnotationsAttribute annotAtr = new AnnotationsAttribute(constPool,AnnotationsAttribute.visibleTag);
Annotation annot = new Annotation("javax.persistence.Entity", constPool);
annotAtr.addAnnotation(annot);
Annotation annotTable = new Annotation("javax.persistence.Table", constPool);
annotTable.addMemberValue("name", new StringMemberValue(tableName,cf.getConstPool()));
annotAtr.addAnnotation(annotTable);
cf.addAttribute(annotAtr);
return c.toClass();
}
When I build a Hibernate SessionFactory by hand, from a Configuration object, adding this classes using addAnnotatedClass method to Configuration, it works fine. Problem is with automated discovery, the entity is not discovered/found neither by JPA, or by AnnotationSessionFactoryBean - when I use package scanning with within a spring context.
(I get: "QuerySyntaxException: [MyEntity] is not mapped" exception)
Class.forName(myNewEntityName) works that means the it is Initialized within the Classloader.
(Of course I know this is not an Ideal design patter for Handling these tables.)
The question is why and how to sole it?
(Javassist 3.15.0-GA, hibernate core 3.6.6.Final, hibernate-entitymanager 3.5.6-Final)
A: I think package scanning happens on the jars and folder in the classpath - not at the classloader level. This is to optimize not loading all the classes into memory. This article has some details of how it is done.
To solve it you might have to extend the AnnotationSessionFactoryBean - and add the list of classes dynamically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Terminology: is DHTML a predecessor of HTML5? In the end of 1990s everyone talked about how cool it is "to program DHTML". In fact, it was an umbrella term for HTML+CSS+JavaScript, there was no specific version of HTML, nor a public standard of what it means.
Now it's 2011 and everyone talks of HTML5, which is also a combination of HTML, CSS, JavaScript and some more additions like WebSockets, Localstorage etc.
So the question is, would it be correct to call DHTML a predecessor of HTML5, just the latter being a public standard? Or am I missing some point?
A: I personally still say "DHTML" when I mean "manipulating the DOM with Javascript", mostly to differentiate it from "Ajax" which for me involves making XHR to the server. And "HTML5" for me means making use of the new capabilities in HTML, such as canvas or local storage. If you are building a web app these days, you would most likely be using all of these techniques at the same time.
A lot of people, especially in marketing, use these terms as synonyms, though, and prefer the buzzword of the day, which was DHTML, then Ajax, now HTML5. They just don't want to sound like a person from 1998 by saying "DHTML".
A: No, it's just that the term HTML more or less has grown to include DHTML.
It's like the term "mobile phone" which is no longer separate from the term "phone", because there is nothing special about a phone being mobile any more. Instead you use "land line" if you need to specify a non-mobile phone.
In the same way, HTML and DHTML now means pretty much the same thing, and you have to specify "plain HTML" if you mean non-dynamic HTML.
A: Quoting Wikipedia: (Emphasis mine)
Following its immediate predecessors HTML 4.01 and XHTML 1.1, HTML5 is
a response to the observation that the HTML and XHTML in common use on
the World Wide Web is a mixture of features introduced by various
specifications, along with those introduced by software products such
as web browsers, those established by common practice, and the many
syntax errors in existing web documents. It is also an attempt to
define a single markup language that can be written in either HTML or
XHTML syntax. It includes detailed processing models to encourage more
interoperable implementations; it extends, improves and rationalises
the markup available for documents, and introduces markup and
application programming interfaces (API)s for complex web
applications.2
The D in DHTML stands for "Dynamic" which means javascript, HTML5 is simply predecessor of HTML as described by above wiki article. This means DHTML isn't predecessor of HTML5.
Compare the definitions of the two:
DHTML:
Dynamic HTML, or DHTML, is an umbrella term for a collection of
technologies used together to create interactive and animated web
sites1 by using a combination of a static markup language (such as
HTML), a client-side scripting language (such as JavaScript), a
presentation definition language (such as CSS), and the Document
Object Model.2
HTML5:
HTML5 is a language for structuring and presenting content for the
World Wide Web, a core technology of the Internet. It is the fifth
revision of the HTML standard (created in 1990 and standardized as
HTML4 as of 19971) and as of September 2011 is still under
development. Its core aims have been to improve the language with
support for the latest multimedia while keeping it easily readable by
humans and consistently understood by computers and devices (web
browsers, parsers, etc.). HTML5 is intended to subsume not only HTML4,
but XHTML1 and DOM2HTML (particularly JavaScript) as well.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How a probably NULL-valued attribute could still reference another attribute in MySQL Imagine MySQL table describing a folders in filesystem:
folder_id INT,
parent_folder_id INT,
folder_name VARCHAR(64)
And I want to add a constraint 'parent_folder_id REFERENCES folder_id' to be sure that no dead links are there in the DB.
But in case folder is in the top-level there is no parent folder, so it should be NULL. As far as I understand, constraint won't let me insert tuple with parent_folder_id = NULL.
How to design it properly?
A: I think you'd better using two triggers (one on insert and one on update) checking that parent_folder_id exists in your table in folder_id column; if not raise an error or discard the insert/update operation.
For root folder assign parent_folder_id = 0 and use a CASE statement in your trigger to make this valid.
EDITED: use this as pseudo-code
CREATE TRIGGER trig_ins BEFORE INSERT ON table
FOR EACH ROW BEGIN
IF (NEW.parent_folder_id > 0) THEN
IF (SELECT COUNT(folder_id) FROM table
WHERE folder_id = NEW.parent_folder_id) = 0 THEN
raise_an_error_here
END
END
END
A: You can just add a foreign key:
CREATE TABLE `folder` (
`folder_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`parent_folder_id` INTEGER UNSIGNED,
`folder_name ` VARCHAR(64) NOT NULL,
CONSTRAINT `PK_folder` PRIMARY KEY (`folder_id`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `folder` ADD CONSTRAINT `FK_folder_parent_folder`
FOREIGN KEY (`parent_folder_id`) REFERENCES `folder` (`folder_id`)
ON DELETE CASCADE ON UPDATE CASCADE;
The foreign key constraint won't kick in when parent_folder_id is NULL.
A: I should just add a record in the folder table, called "root", for which the parent_folder is himself. But I never tested it and do not know if the system will accept this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to run Android JUnit tests from multiple projects in eclipse? I'm wondering how to run multiple projects containing Android JUnit Robotium test from eclipse at once...
I hope someone could help.
Thanks a lot!
A: I was caught up in the similar situation. I used command line to run my test. You can use the following commands
For a single Test
adb shell am instrument -e your class -w your package/android.test.InstrumentationTestRunner
For all your Tests
adb shell am instrument -w your package/android.test.InstrumentationTestRunner
Hope it helps.
A: You can run JUnit tests across multiple projects using the open source Classpath Suite.
Create an Eclipse project which contains a dependency on all the projects you want to test.
Write a suite:
@RunWith(ClasspathSuite.class)
public class MySuite
Take a look on this article: Roger Rabbit - JUnit Tests Runner Across Multiple Projects, it includes a step by step example and a code sample.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: local_import function does not work local_import function randomly does not import my modules from modules
directory. The Error is:
ImportError: No module named testapp.modules.mymodule
I have this problem when i use web2py with apache (with wsgi). I have no problem when i run locally with "python web2py.py" command.
Any suggestion?
A: As of version 1.96.1, local_import() has been deprecated. You should be able to do:
import mymodule
and it will look in your application's /modules folder before checking sys.path.
A: I will answer my own question :)
I started using mod_proxy and everything is ok.
A: Add testapp to your PYTHONPATH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Setting a ComboBox value using callback I have an Asp.net page with 3 combobox and 1 button. The first combobox selection will affect the other 2 combobox datasource. I'm setting the datasource for the other combobox using a callback function.
After the user choose from all the combobox, the user click the button and a postback is generate.
My Problem is that the server side code, is not aware of the selections made in the page,
if i try to get the value from the combobox I get null allways.
looking for a solution.
Thank you.
Code
Code of aspx
<script type="text/javascript">
// <![CDATA[
function OnProductChange(cb_Products) {
cb_Packing.PerformCallback(cb_Products.GetValue().toString());
cb_ProductionSite.PerformCallback(cb_Products.GetValue().toString());
}
function OnPackChange(cb_Products) {
ASPxComboBox1.PerformCallback(cb_Packing.GetValue().toString());
}`enter code here`
function OnFactoryChange(cb_Products) {
cb_ProductionSite.PerformCallback();
}
// ]]>
</script>
<PanelCollection>
<dx:PanelContent runat="server" SupportsDisabledAttribute="True">
<dx:ASPxLabel ID="ASPxLabel1" runat="server" Font-Bold="True" Font-Names="Snap ITC"
Font-Size="Medium" Font-Underline="True" ForeColor="#333333" Text="Production Form (DEMO)">
</dx:ASPxLabel>
<br />
<br />
<dx:ASPxLabel ID="ASPxLabel2" runat="server" Font-Names="Berlin Sans FB Demi" Font-Size="Medium"
Text="Select Product" ForeColor="#FF3300">
</dx:ASPxLabel>
<dx:ASPxComboBox ID="cb_Products" runat="server" ValueType="System.String" Font-Names="Berlin Sans FB Demi"
DataSourceID="EntityDataSource1" Spacing="3" TextField="PC_Name" EnableSynchronization="False"
ValueField="PCID" ClientIDMode="Static" DropDownStyle="DropDownList">
<Columns>
<dx:ListBoxColumn Caption="Product's name" FieldName="PCID" Visible="false" />
<dx:ListBoxColumn Caption="Product's name" FieldName="PC_Name" />
</Columns>
<ClientSideEvents SelectedIndexChanged=" function(s,e) { OnProductChange(s); }" />
</dx:ASPxComboBox>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=TrackQREntities"
DefaultContainerName="TrackQREntities" EnableFlattening="False" EntitySetName="TrackQR_ProductsCatalog"
Select="it.[PC_Name], it.[PCID]" Where="it.[ClientID] == 11">
</asp:EntityDataSource>
<br />
<br />
<dx:ASPxLabel ID="ASPxLabel3" runat="server" Font-Names="Berlin Sans FB Demi" Font-Size="Medium"
Text="Packing Options" ForeColor="#FF3300">
</dx:ASPxLabel>
<dx:ASPxComboBox ID="cb_Packing" runat="server" Font-Names="Berlin Sans FB Demi"
ValueType="System.String" ClientIDMode="Static" DropDownStyle="DropDown" EnableSynchronization="False"
OnCallback="Packing_Callback" TextField="PackQuantity"
ValueField="PackID" ClientInstanceName="cb_Packing"
EnableCallbackMode="True">
<Columns>
<dx:ListBoxColumn FieldName="PackID" Visible="False" />
<dx:ListBoxColumn Caption="Pack Quantity" FieldName="PackQuantity" />
</Columns>
<ClientSideEvents SelectedIndexChanged=" function(s,e) { OnPackChange(s); }" />
</dx:ASPxComboBox>
<br />
<br />
<dx:ASPxLabel ID="ASPxLabel4" runat="server" Font-Names="Berlin Sans FB Demi" Font-Size="Medium"
Text="Production Site" ForeColor="#FF3300">
</dx:ASPxLabel>
<dx:ASPxComboBox ID="cb_ProductionSite" runat="server" Font-Names="Berlin Sans FB Demi"
ValueType="System.String" ClientIDMode="Static" DropDownStyle="DropDown" EnableSynchronization="False"
TextField="LLName" ValueField="LLID"
ClientInstanceName="cb_ProductionSite" EnableCallbackMode="True"
OnCallback="cb_ProductionSite_Callback"
>
<Columns>
<dx:ListBoxColumn FieldName="LLID" Visible="False" />
<dx:ListBoxColumn Caption="Factory Name" FieldName="LLName" />
</Columns>
<ClientSideEvents SelectedIndexChanged=" function(s,e) { OnFactoryChange(s); }" />
</dx:ASPxComboBox>
<br />
<br />
<dx:ASPxLabel ID="ASPxLabel5" runat="server" Font-Names="Berlin Sans FB Demi" Font-Size="Medium"
Text="Number of Products" ForeColor="#FF3300">
</dx:ASPxLabel>
<dx:ASPxTextBox ID="atb_Quantity" runat="server" Width="170px">
</dx:ASPxTextBox>
<br />
<dx:ASPxButton ID="ab_Produce" runat="server" Text="Produce"
Font-Names="Arial Black" Font-Size="Medium" OnClick="ab_Produce_Click"
CssFilePath="~/App_Themes/SoftOrange/{0}/styles.css" CssPostfix="SoftOrange"
SpriteCssFilePath="~/App_Themes/SoftOrange/{0}/sprite.css">
</dx:ASPxButton>
<dx:ASPxComboBox ID="ASPxComboBox1" runat="server" Font-Names="Berlin Sans FB Demi"
ValueType="System.String" ClientIDMode="Static" DropDownStyle="DropDown" EnableSynchronization="False"
TextField="LLName" ValueField="LLID"
ClientInstanceName="cb_ProductionSite" EnableCallbackMode="True"
OnCallback="cb_ProductionSite_Callback"
>
<Columns>
<dx:ListBoxColumn FieldName="LLID" Visible="False" />
<dx:ListBoxColumn Caption="Factory Name" FieldName="LLName" />
</Columns>
<ClientSideEvents SelectedIndexChanged=" function(s,e) { OnFactoryChange(s); }" />
</dx:ASPxComboBox>
<br />
<br />
</dx:PanelContent>
Code of aspx.cs
protected void Packing_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
//if (e.Parameter != "")
//{
using (TrackQREntities te = new TrackQREntities())
{
int id = int.Parse(e.Parameter);
var product = te.TrackQR_ProductsCatalog.Where(s => s.PCID == id).FirstOrDefault();
cb_Packing.DataSource = product.TrackQR_PacksType.ToList();
cb_Packing.DataBind();
cb_Products.SelectedIndex = id;
// }
}
}
protected void cb_ProductionSite_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
if (e.Parameter != "")
{
using (TrackQREntities te = new TrackQREntities())
{
cb_ProductionSite.DataSource = te.TrackQR_LogisticLocations.Where(s => s.LLTypesID == 1).ToList();
cb_ProductionSite.DataBind();
}
}
}
protected void ab_Produce_Click(object sender, EventArgs e)
{
cb_ProductionSite.Value.ToString(); <--- Error Value is null
A: Check whether or not the ASPxComboBox.ValueType property is specified correctly according to the “Data Type Mappings (ADO.NET)” table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF "Coloured binding" I have few labels I use for displaying results.
Basically, they display numbers in following format
string.Format("{0:0.#}", number)
Their Text property is binded to objects. Result should be plus or minus signed.
Is there a way to set Foreground property of label according to result sign? For example green plus results and red minus results?
A: A solution could be to add a ValueConverter that transforms the value to a brush.
Bind the value to the Foreground property using the converter.
Here is an example
EDIT
Another option would be to add an extra property to the object you are binding to.
The property would be a Brush that changes with the number to the correct color.
Then just bind the Foreground to the property. This approach is common in MVVM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JUnit testing with spring I am trying to create a junit test for a spring controller method but I keep receiving the following error
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request,
or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message,
your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:123)
I have added both the things it tells me I need (I've tried each one separately) and currently my web.xml contains
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and the method I'm trying to test is something along the lines of
@Controller
@RemotingDestination
public class MyController {
public Response foo()
{
//...
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession httpSession = attr.getRequest().getSession(true);
//...
}
and my junit test simply calls myController.foo() and checks the reponse. So I can't create a mock object to pass into the method to get around this issue.
So I suppose my question is, does there exist some configuration or trick that I have yet to stumble upon that will make this run without having to refactor my controller method?
A: The error message is pretty clear. Unfortunately your code requires a bit of a rewrite.
First of all while testing your controller you (obviously) are not inside a web request. That's why RequestContextHolder.currentRequestAttributes() does not work. But you can make your test to pass and refactor the code to be much more readable using the following technique (assuming you need an HTTP session to get some actual attribute from it):
public Response foo(@SessionAttribute("someSessionAttribute") int id)
This way Spring MVC will automatically fetch the session and load someSessionAttribute when inside a web request (and even perform required conversion). But when you are testing the controller, just call the method with fixed parameter. No request/session infrastructure code. Much cleaner (note that the two lines in foo you've provided aren't needed at all).
The other solution is to register RequestScope manually. See example here. This should work without modifying any of your code with mocked request and session.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Safari Extension, accessing page/content directly from toolbar? IS it possible to access web content directly from the (Safari) toolbar? I can now access it from a contextmenu, but no idea how i get the same functionaliy to a toolbar.
This is what i got:
// injected
document.addEventListener("contextmenu", handleMessage, false);
function handleMessage(msgEvent) {
var sel = '';
sel = window.parent.getSelection()+'';
safari.self.tab.setContextMenuEventUserInfo(msgEvent, sel);
}
// global
safari.application .addEventListener("command", performCommand, false);
function performCommand(event) {
console.log('performCommand');
if (event.command == "abc") {
var query = event.userInfo;
console.log(query);
alert(query);
}
}
But how do i this content directly from the toolbar ??
A: OK, basically it works like this:
*
*in global the performCommand get called (by clicking on the toolbar), dispatching a event
*this event is caught in handleGextText
*in handleGextText, you do what you need to do and call safari.self.tab.dispatchMessage this dispatches a event back to global
*in global you the event get caught by handleEvent
>
// Global Script
safari.application.addEventListener("command", performCommand, false);
safari.application.addEventListener("message", handleEvent, false);
// send message
function performCommand(event) {
console.log('command:' + event.command);
if (event.command == "abc") {
console.log("msg: my message");
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("msg", "do-something");
}
}
function handleEvent(event) {
var messageName = event.name;
console.log("evenname:" + event.name);
if (messageName === "did-something") {
var msg = event.message;
// do something
}
}
// Injected Script
if (window.top === window) { // inject only once!
console.log("add event listners [injected.js]");
safari.self.addEventListener("message", handleGextText, false);
}
function handleGextText(event) {
console.log("evenname:" + event.name);
console.log("evenmsg :" + event.message);
var messageName = event.name;
var messageData = event.message;
if (messageName === "msg") {
if (messageData === "do-something") {
console.log('msg received: ' + event.name);
var sel = '';
// do what you need to do and dispatch message back to Global
console.log("send message to toolbar");
safari.self.tab.dispatchMessage("did-something", sel);
}
}
}
A: OK, well found it. I solved it with messages.
I send in 'global' a message, which is catches by the injected script. That function get the selected text (puts it in userinfo), and sends a message back to global.
Thats it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: XPath - abbreviation of position() function Can anyone explain what's the difference between
/root/a[position()=1 or position()=2
and
/root/a[1 or 2]
?
I'd assume the 2nd to be abbreviated form of the 1st, but Java XPath (Sun JDK 1.6.0) processor thinks otherwise. Following is my test application.
libxml2 library and also db2 XPath processor consider these paths different too. So it doesn't look like JDK bug.
import java.io.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
public class XPathTest {
public static void main(String[] args) throws Exception {
//String xpathStr = "/root/a[position()=1 or position()=2]";
String xpathStr = "/root/a[1 or 2]";
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
Reader irdr = new StringReader(
"<root><a name=\"first\"/><a name=\"second\"/><a name=\"third\"/></root>");
InputSource isrc = new InputSource(irdr);
XPathExpression expr = xp.compile(xpathStr);
Object result = expr.evaluate(isrc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Element element = (Element) node;
System.out.print(element.getNodeName() + " " + element.getAttributeNode("name"));
System.out.println();
}
}
}
A: I don't think [1 or 2] is evaluating how you think it is evaluating. or works on two boolean values. I suspect both 1 and 2 are evaluating as true. Therefore this expression is evaluating as true and essentially doing nothing, and will return all elements.
In general, position() can be used in expressions like [position() <= 5] whereas the index address can only ever select one element like [5].
A: If the value in square brackets is a number [N], it is interpreted as [position()=N]. But [1 or 2] is not a number, so this rule does not apply.
A: [1 or 2] evaluates to an "always true" predicate in .Net as well, so this behaviour appears consistent:
Here's the output from a the XPath of a .NET 3.5 XmlDocument
// Returns first, second
var ndl = dom.SelectNodes(@"/root/a[position()=1 or position()=2]");
// Returns first, second and third
ndl = dom.SelectNodes(@"/root/a[1 or 2]");
// Returns first, second
ndl = dom.SelectNodes(@"/root/a[1] | /root/a[2]");
Edit
In XPath 2, you can use the sequence functions index-of and exists to determine whether the given position is contained in a sequence of values:
/root/a[exists(index-of((1,2), position()))]
A: A numeric value in [] is treated as an index. The OR doesn't work for indexes on a way like yours ( [1 or 2] ). The right way is using position().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Import big files/arrays with mathematica I work with mathematica 8.0.1.0 on a Windows7 32bit platform. I try to import data with
Import[file,”Table”]
which works fine as long as the file (the array in the file) is small enough. But for bigger files(38MB)/array(9429 times 2052) I get the message:
No more memory available. Mathematica kernel has shut down. Try quitting other applications and then retry.
On my Windows7 64bit platform with more main memory I can import bigger files, but I think that I will have there the same problem one day when the file has grown/the array has more rows.
So, I try to find a solution to import big files. After searching for some time, I have seen here a similar question: Way to deal with large data files in Wolfram Mathematica.
But it seems that my mathematica knowledge is not good enough to adapt the suggested OpenRead, ReadList or similar to my data (see here the example file).
The problem is that I need for the rest of my program information of the array in the file, such as Dimensions, Max/Min in some columns and rows, and I am doing operations on some columns and every row.
But when I am using e.g. ReadList, I never get the same information of the array as I have got with Import (probably because I am doing it in the wrong way).
Could somebody here give me some advice? I would appreciate every support!
A: For some reason, the current implementation of Import for the type Table (tabular data) is quite memory - inefficient. Below I've made an attempt to remedy this situation somewhat, while still reusing Mathematica's high-level importing capabilities (through ImportString). For sparse tables, a separate solution is presented, which can lead to very significant memory savings.
General memory-efficient solution
Here is a much more memory - efficient function:
Clear[readTable];
readTable[file_String?FileExistsQ, chunkSize_: 100] :=
Module[{str, stream, dataChunk, result , linkedList, add},
SetAttributes[linkedList, HoldAllComplete];
add[ll_, value_] := linkedList[ll, value];
stream = StringToStream[Import[file, "String"]];
Internal`WithLocalSettings[
Null,
(* main code *)
result = linkedList[];
While[dataChunk =!= {},
dataChunk =
ImportString[
StringJoin[Riffle[ReadList[stream, "String", chunkSize], "\n"]],
"Table"];
result = add[result, dataChunk];
];
result = Flatten[result, Infinity, linkedList],
(* clean-up *)
Close[stream]
];
Join @@ result]
Here I confront it with the standard Import, for your file:
In[3]:= used = MaxMemoryUsed[]
Out[3]= 18009752
In[4]:=
tt = readTable["C:\\Users\\Archie\\Downloads\\ExampleFile\\ExampleFile.txt"];//Timing
Out[4]= {34.367,Null}
In[5]:= used = MaxMemoryUsed[]-used
Out[5]= 228975672
In[6]:=
t = Import["C:\\Users\\Archie\\Downloads\\ExampleFile\\ExampleFile.txt","Table"];//Timing
Out[6]= {25.615,Null}
In[7]:= used = MaxMemoryUsed[]-used
Out[7]= 2187743192
In[8]:= tt===t
Out[8]= True
You can see that my code is about 10 times more memory-efficient than Import, while being not much slower. You can control the memory consumption by adjusting the chunkSize parameter. Your resulting table occupies about 150 - 200 MB of RAM.
EDIT
Getting yet more efficient for sparse tables
I want to illustrate how one can make this function yet 2-3 times more memory-efficient during the import, plus another order of magnitude more memory-efficient in terms of final memory occupied by your table, using SparseArray-s. The degree to which we get memory efficiency gains depends much on how sparse is your table. In your example, the table is very sparse.
The anatomy of sparse arrays
We start with a generally useful API for construction and deconstruction of SparseArray objects:
ClearAll[spart, getIC, getJR, getSparseData, getDefaultElement, makeSparseArray];
HoldPattern[spart[SparseArray[s___], p_]] := {s}[[p]];
getIC[s_SparseArray] := spart[s, 4][[2, 1]];
getJR[s_SparseArray] := Flatten@spart[s, 4][[2, 2]];
getSparseData[s_SparseArray] := spart[s, 4][[3]];
getDefaultElement[s_SparseArray] := spart[s, 3];
makeSparseArray[dims : {_, _}, jc : {__Integer}, ir : {__Integer},
data_List, defElem_: 0] :=
SparseArray @@ {Automatic, dims, defElem, {1, {jc, List /@ ir}, data}};
Some brief comments are in order. Here is a sample sparse array:
In[15]:=
ToHeldExpression@ToString@FullForm[sp = SparseArray[{{0,0,1,0,2},{3,0,0,0,4},{0,5,0,6,7}}]]
Out[15]=
Hold[SparseArray[Automatic,{3,5},0,{1,{{0,2,4,7},{{3},{5},{1},{5},{2},{4},{5}}},
{1,2,3,4,5,6,7}}]]
(I used ToString - ToHeldExpression cycle to convert List[...] etc in the FullForm back to {...} for the ease of reading). Here, {3,5} are obviously dimensions. Next is 0, the default element. Next is a nested list, which we can denote as {1,{ic,jr}, sparseData}. Here, ic gives a total number of nonzero elements as we add rows - so it is first 0, then 2 after first row, the second adds 2 more, and the last adds 3 more. The next list, jr, gives positions of non-zero elements in all rows, so they are 3 and 5 for the first row, 1 and 5 for the second, and 2, 4 and 5 for the last one. There is no confusion as to where which row starts and ends here, since this can be determined by the ic list. Finally, we have the sparseData, which is a list of the non-zero elements as read row by row from left to right (the ordering is the same as for the jr list). This explains the internal format in which SparseArray-s store their elements, and hopefully clarifies the role of the functions above.
The code
Clear[readSparseTable];
readSparseTable[file_String?FileExistsQ, chunkSize_: 100] :=
Module[{stream, dataChunk, start, ic = {}, jr = {}, sparseData = {},
getDataChunkCode, dims},
stream = StringToStream[Import[file, "String"]];
getDataChunkCode :=
If[# === {}, {}, SparseArray[#]] &@
ImportString[
StringJoin[Riffle[ReadList[stream, "String", chunkSize], "\n"]],
"Table"];
Internal`WithLocalSettings[
Null,
(* main code *)
start = getDataChunkCode;
ic = getIC[start];
jr = getJR[start];
sparseData = getSparseData[start];
dims = Dimensions[start];
While[True,
dataChunk = getDataChunkCode;
If[dataChunk === {}, Break[]];
ic = Join[ic, Rest@getIC[dataChunk] + Last@ic];
jr = Join[jr, getJR[dataChunk]];
sparseData = Join[sparseData, getSparseData[dataChunk]];
dims[[1]] += First[Dimensions[dataChunk]];
],
(* clean - up *)
Close[stream]
];
makeSparseArray[dims, ic, jr, sparseData]]
Benchmarks and comparisons
Here is the starting amount of used memory (fresh kernel):
In[10]:= used = MemoryInUse[]
Out[10]= 17910208
We call our function:
In[11]:=
(tsparse= readSparseTable["C:\\Users\\Archie\\Downloads\\ExampleFile\\ExampleFile.txt"]);//Timing
Out[11]= {39.874,Null}
So, it is the same speed as readTable. How about the memory usage?
In[12]:= used = MaxMemoryUsed[]-used
Out[12]= 80863296
I think, this is quite remarkable: we only ever used twice as much memory as is the file on disk occupying itself. But, even more remarkably, the final memory usage (after the computation finished) has been dramatically reduced:
In[13]:= MemoryInUse[]
Out[13]= 26924456
This is because we use the SparseArray:
In[15]:= {tsparse,ByteCount[tsparse]}
Out[15]= {SparseArray[<326766>,{9429,2052}],12103816}
So, our table takes only 12 MB of RAM. We can compare it to our more general function:
In[18]:=
(t = readTable["C:\\Users\\Archie\\Downloads\\ExampleFile\\ExampleFile.txt"]);//Timing
Out[18]= {38.516,Null}
The results are the same once we convert our sparse table back to normal:
In[20]:= Normal@tsparse==t
Out[20]= True
while the normal table occupies vastly more space (it appears that ByteCount overcounts the occupied memory about 3-4 times, but the real difference is still at least order of magnitude):
In[21]:= ByteCount[t]
Out[21]= 619900248
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Looping through XPathNodeIterator problem I've created a XPathNodeIterator that contains a few short XML segments (each with a file description):
XPathNodeIterator segments = node.SelectDescendants("Segment", node.NamespaceURI, false);
Now, when trying to loop them, it seems that only the first segment is picked every time. Here are two versions of the loops I've tried (File/Files classes only for example):
while (segments.MoveNext())
{
File f = GetSingleFileDataFromSegment(segments.Current);
files.Add(f);
}
Another try:
foreach (XPathNavigator seg in segments)
{
File f = GetSingleFileDataFromSegment(seg);
files.Add(f);
}
When viewing a single segment in a loop with Watch or Quickwatch, it looks as it should, all different segments are selected one at a time - but end result is that "files" contain multiple copies of the first segment.
Is this normal behavior with XPathNodeIterator? Or is something missing here? I'm currently using .NET Framework 3.5.
A: The problem was in GetSingleFileDataFromSegment -method, which used XPath to get the proper segment. The segment attributes had namespaces in them, and that required the use of a NamespaceManager.
Faulty XPath expression:
f.Location = seg.XPathSelectElement("//*[local-name()='Location']").Value;
Corrected version:
System.Xml.XmlNamespaceManager nsmanager = new System.Xml.XmlNamespaceManager(seg.ToXmlDocument().NameTable);
nsmanager.AddNamespace("ns", seg.Elements().FirstOrDefault().GetDefaultNamespace().NamespaceName);
f.Location = seg.XPathSelectElement("./ns:Location", nsmanager).Value;
Code above was in the method that received the segment as parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Directx9 methods of drawing models I was wondering if there is any other method beside the classical
DrawIndexedPrimitive
DrawIndexedPrimitiveUP
DrawPrimitive
DrawPrimitiveUP
DrawRectPatch
DrawTriPatch
for drawing models on the screen.
A: if you mean that model is a mesh (set of vertex and textures) and you have file with that model you can try something like this:
// Loading the mesh
LPD3DXBUFFER materialBuffer = NULL;
DWORD numMaterials = 0;
LPD3DXMESH mesh = NULL;
hr=D3DXLoadMeshFromX("d:\\temp\\tiger.x", D3DXMESH_SYSTEMMEM,
d3dDevice, NULL,
&materialBuffer,NULL, &numMaterials,
&mesh );
if(FAILED(hr))
THROW_ERROR_AND_EXIT("hr=D3DXLoadMeshFromX");
// Loading the material buffer
D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)materialBuffer->GetBufferPointer();
// Holding material and texture pointers
D3DMATERIAL9 *meshMaterials = new D3DMATERIAL9[numMaterials];
LPDIRECT3DTEXTURE9 *meshTextures = new LPDIRECT3DTEXTURE9[numMaterials];
// Filling material and texture arrays
for (DWORD i=0; i<numMaterials; i++)
{
// Copy the material
meshMaterials[i] = d3dxMaterials[i].MatD3D;
// Set the ambient color for the material (D3DX does not do this)
meshMaterials[i].Ambient = meshMaterials[i].Diffuse;
// Create the texture if it exists - it may not
meshTextures[i] = NULL;
if (d3dxMaterials[i].pTextureFilename)
D3DXCreateTextureFromFile(d3dDevice, d3dxMaterials[i].pTextureFilename, &meshTextures[i]);
}
materialBuffer->Release();
//render mesh
d3dDevice->Clear(0,NULL,D3DCLEAR_TARGET, D3DCOLOR_XRGB(255,255,255),1.0f,0);
// Turn on wireframe mode
d3dDevice->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
d3dDevice->BeginScene();
for (DWORD i=0; i<numMaterials; i++)
{
// Set the material and texture for this subset
d3dDevice->SetMaterial(&meshMaterials[i]);
d3dDevice->SetTexture(0,meshTextures[i]);
// Draw the mesh subset
mesh->DrawSubset( i );
}
d3dDevice->EndScene();
d3dDevice->Present(NULL, NULL, NULL, NULL);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Deleting a branch with an invalid name in Git I've been using Dropbox to keep my source folder synced between two computers. This folder contains my source-code which I version handle with Git.
it seems that there was a file conflict and when I did a push, my Git client, pushed an invalid branch to the remote. The branch name is rel_1 (Mridang-PC's conflicted copy 2011-09-16).0-alpha2. I need to delete this branch but an unable to do so. Ad you can see the name has spaces and single-quote too.
When I try and check out the branch by running: git checkout "rel_1 (Mridang-PC's conflicted copy 2011-09-16).0-alpha2". I get an error saying: fatal: git checkout: we do not like 'rel_1 (Mridang-PC's conflicted copy 2011-09-16).0-alpha2' as a branch name.
Is there a way I can fix this?
Thanks.
A: Look in the folder ".git/refs/heads", you will find the file which has that branch name.
(By the way, the branch was renamed that way by Dropbox).
Rename that file, and you should be fine.
A: I had an issue with a branch named '-t' ( which I definitely did not push to another box)
I ended up going into my .git directory running
find . |xargs grep "-t"
and removing lines associated with the -t from all the files
specifically
./packed-refs,
./config ( the whole section associated with it)
./into/refs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sqlite database problem android I have a problem in sqlite database.First i created database externally and then put it in the assets folder.The following code copy the database.
public class DbH extends SQLiteOpenHelper{
private Context mycontext;
private String DB_PATH = "/data/data/com.android.quotes/databases/";
private static String ROW_ID="_id";
private static String DB_NAME = "mdb1.db";
public SQLiteDatabase myDataBase;
/*private String DB_PATH = "/data/data/"
+ mycontext.getApplicationContext().getPackageName()
+ "/databases/";
*/
public DbH(Context context) throws IOException {
super(context,DB_NAME,null,1);
this.mycontext=context;
boolean dbexist = checkdatabase();
if(dbexist){
//System.out.println("Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}
}
public void createdatabase() throws IOException{
boolean dbexist = checkdatabase();
if(dbexist){
System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try{
copydatabase();
} catch(IOException e){
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try{
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
SQLiteDatabase.openDatabase
(myPath,null,SQLiteDatabase.OPEN_READWRITE);
checkdb = dbfile.exists();
} catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
return checkdb;
}
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream(outfilename);
// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0){
myoutput.write(buffer,0,length);
}
//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();
}
public void opendatabase() throws SQLException{
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(
mypath, null, SQLiteDatabase.OPEN_READWRITE
);
}
public synchronized void close(){
if(myDataBase != null){
myDataBase.close();
}
super.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Empty
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
}
In main activity i first call createdatabase and then opendatabase.
Now i craeted only two table in sqlite database one is android_metadata and second is mTable.when i run the program the following errors occur.
*
*Although database is created and i can see it using file explorer in eclipse but only android_metadata table is there and mTable is not there.
*So it says no such table exists while selecting * from mTable.
Any suggestion where i m going wrong. I m pulling my hair from one week me. Please help.
Thanks in advance.
A: First Of all check database database exists in internal storage if not than copy
private void checkDatabase() {
StringBuffer dbPath = new StringBuffer();
File databaseFile;
// Location of the database file, where it will be stored to access
// throughout the program.
dbPath.append("/data/data/");
dbPath.append(getBaseContext().getPackageName());
dbPath.append("/databases/");
// Location of the database file stored in assets folder.
String storedDatabase = Constants.DATABASE_FILE_NAME;
// copy the database
try {
databaseFile = new File(dbPath.toString(), Constants.DATABASE_FILE_NAME);
if (databaseFile.exists()) {
Log.i("database", "database already Exists");
} else {
SQLiteDatabase database = openOrCreateDatabase(Constants.DATABASE_FILE_NAME,
SQLiteDatabase.OPEN_READONLY, null);
database.close();
copyDatasbase(getBaseContext().getAssets(), storedDatabase,
dbPath + Constants.DATABASE_FILE_NAME);
}
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (Exception exception) {
exception.printStackTrace();
}
}
if database not exists then copy from asset to internal storage
private void copyDatasbase(AssetManager manager, String sourceFileName,
String destinationFileName) throws IOException {
// Read file from AccessManager
InputStream inputStream = manager.open(sourceFileName);
OutputStream outputStream = new FileOutputStream(destinationFileName);
Log.d("-->", "src: " + sourceFileName);
Log.d("-->", "Des: " + destinationFileName);
byte[] buffer = new byte[3072];
int length;
while ((length = inputStream.read(buffer)) > 0) {
// Write the database file to the folder "databases"
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
outputStream = null;
inputStream = null;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: phone gap in blackberry I am using the phonegap in my blackberry application.I need to get the button clicked and go to the next form.please tell me for that i need to use the phone.js or to create my own javascript file.
A: You need to use a javascript framework to make your life easy :)
Try http://jquerymobile.com/ that works very good in BB OS v5+, Android, Iphone and so on.
Good Luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Custom Tree Model updating problem Here is structure of the tree:
root
-branches
--leafs
I use for TreeModel DefaultTreeModel and my objects implement TreeNode interface
leaf is some Object:
public class Leaf implements TreeNode
{
// implementation
branch has List of leafs:
public class Branch implements TreeNode
{
private List<Leaf> leafs;
// implementation
And root is container of branches:
public class Root implements TreeNode
{
private List<Branch> branches;
// implementation
When I add new leaf, my tree doesn't updated, when I add leaf and create new DefaultTreeModel with my root object it's updated. I watch DefaultMutableTreeNode implementation, there isn't any event firing on inserting childs... What am I doing wrong? Before, I tried to implement TreeModel interface wich looks much better then implementing TreeNode interface for three classes, but result was similar. I also read about GlazedLists, but I dislike their tree conception. For me, the best is implementation TreeModel interface conception, but how to update model when some inner List in model add new element?...
A: Without seeing the code, it's hard to be sure - nevertheless I'll bet on my guess: you don't notify the TreeModel about your insertions ;-)
A code snippet of what you have to do if your node implementation is not of type MutableTreeNode:
// do the parent wiring in your custom TreeNode
int position = myBranch.addChild(node);
// notify the model
model.nodesWhereInserted(myBranch, new int[] {pos});
If it is of type MutableTreeNode, the easier way is via the convenience methods in DefaultTreeModel
model.insertNodeInto(node, myBranch, position)
A: that look like as issue with Concurrency in Swing, maybe updates are out of EDT,
you have add new Object, then to test DefaultTreeModel if contains new Object, if Objects exists, then you have to wrap (all updates) into invokeLater, for Serializable or Observate would be better look for invokeAndWait
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to inject a Provider using Guice I want to inject a Provider<T>, in something like this:
class Work {
Provider<Tool> provider;
@Inject
Work (Provider<Tool> provider) { this.provider = provider; }
}
My Module looks something like this:
protected void configure () {
bind (Tool.class).to(MyTool.class);
// Q: How do I bind this:
bind (new TypeLiteral<Provider<Tool>> {}).to (????);
// A: Turns out deleting these last 3 lines makes everything just right.
}
I want to inject a Provider<T> because Work class needs to create more Tool objects and work with them. Also, I'm not sure there really needs to be a binding for TypeLiteral<Provider<Tool>> but I think it's closest approach for this case.
A: Have you tried just not binding it? I'd expect Guice to just build you a provider which resolves the non-provider binding each time.
From "Injecting Providers":
For every binding, annotated or not, the injector has a built-in binding for its provider.
So I think that just binding Tool will be enough. It's at least worth a try :) (I'd love to sound more confident, but I don't have as much Guice-fu as I'd like...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Mac C++ GUI coding - comparison to Win32 I am struggling to find a good tutorial on how a Mac C++ GUI application is structured. Coming from Windows programming I'm used to message loops and window handles... is it comparable on Macs or totally different?
Any links or examples are welcome, particularly those aimed at transitioning from Win32 rather than assuming I'm a noob to programming in general.
update: I should point out this is for a game-like application so I don't need to access common controls; I essentially just need a window to render in and a message loop. I don't know if that's below the Cocoa/Carbon API level or if one or the other still has to be used.
A: I once was in the same situation as you. I would suggest checking out the Mac Dev Center and reading their "Getting Started" guide.
A: I had done a development on Mac OS X with C++. I was forced to use Carbon with it.
Then we used Qt as solution for C++ development with Mac. But I always had to compromise with bugs already present in Qt Framework. But its worth looking into to get few ideas.
Other than that Objective C++ is also nice. Though you will have to follow Cocoa Design Patterns to come with good application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hibernate Criteria runtime class This is my hierarchy:
// Table a
class A {}
// Table(" b
class B extends A {}
// Table my_class
class MyClass {
A a;
}
I want to retrieve all MyClass objects from database with a relation to B but not to A.
B is a joined-subclass (extension of the table a by id).
My idea was something :
Criteria criteria = session.createCriteria(MyClass.class);
criteria.add(Restrictions.eq("a.class", B.class);
But it outputs an error:
could not resolve property: a.class of a.b.MyClass
This is the simplest way I could put it. Bear in mind that the query is a bit more complicated.
Regards.
Udo.
A: I usually write a DetachedCriteria which selects all B's and filter MyClass where A in AllBs:
DetachedCriteria allBs = DetachedCriteria
.forClass(B.class)
.setProjection( Projections.property("id") );
Criteria criteria = session.createCriteria(MyClass.class)
.add(Subqueries.In("a", allBs);
(There may be errors, I'm not a java programmer.)
Creates something like:
select ...
from MyClass
where A in (select id from A inner join B on ...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UI-Relative layout I am trying to create a UI using relative layout where in the UI should look as such:
*
*In the top of the screen i have a TextView
*followed by another TextView
*followed by scroll view where in i have to display the text in the
scrollable format
*in the end i have a imageview.
How can i achieve this.
I have tried using the combination of Relative and Linear Layout but the elements gets overlapped. Anyone have any suggestions on how to proceed?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@drawable/background_main" android:id="@+id/g_description">
<TextView android:id="@+id/titleBar" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:background="@drawable/header"
android:layout_alignParentTop="true" android:gravity="center"
android:text="@string/aboutus" android:textAppearance="? android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView android:id="@+id/wd_name"
android:layout_width="fill_parent" android:layout_below="@id/titleBar"
android:layout_height="wrap_content" android:textStyle="bold"
android:textColor="#FFFFFF" android:textSize="18dip"
android:background="@drawable/background_main" android:gravity="center" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrolltext" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_below="@id/wd_name"
android:padding="5dip">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/wd_description"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textSize="14dip" android:textColor="#FFFFFF">
</TextView>
</LinearLayout>
</ScrollView>
<ImageView android:id="@+id/bottomBar" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:src="@drawable/bottom_bar"
android:layout_alignParentBottom="true" />
A: you can achieve it like this:
*
*Take relative layout and put textview in it.
*Take another textview and add this to it android:layout_below="id of the 1st textview".
*Take scrollview and add this to it android:layout_below="id of the 2nd textview".
*Take linear layout inside scrollview.
*Put textview inside linear layout.
*Take imageview and add this to it android:layout_below="id of the scrollview".
Now your layout is ready and if you get any error then let me know with your code....
A: If you have a series of elements that you want to flow down the screen, then it sounds like you just need a LinearLayout.
A: It goes as below. Placing a TextView inside scrollview will make it scrollable. Reset is selfexplanary.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Below TOP TextView" android:id="@+id/TextView01" android:layout_alignParentTop="true"></TextView>
<TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="TOP TextView" android:id="@+id/TextView02" android:layout_below="@id/TextView01"></TextView>
<ScrollView android:layout_height="wrap_content" android:layout_width="fill_parent" android:fillViewport="true" android:layout_below="@id/TextView02">
<TextView android:id="@+id/textView1" android:layout_height="wrap_content" android:text="Scrollable textViewafkasjf;laksjflaskjf;lasjf;alsfjal;sfj;aslfj;aslfja;slfj;aslkfj;asldfj;aslkfjasl;dfj;a asfj aslfj asldfjk as;lfjk asfjka;sldf jl;asj df;asdfjasfj aslfj asljf asjfl;asfasj fasj f;asj flas jf;lasjf;asjkf;las f;asj df;as jf;lasjf ;asjf;asjf;asjf;asjf;asjf;jasf;asfja s;dfa;sf asf jf asf a; sldfja;slfj;asldfjk" android:layout_width="fill_parent"></TextView>
</ScrollView>
<ImageView android:src="@drawable/icon" android:layout_height="wrap_content" android:id="@+id/imageView1" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_width="fill_parent"></ImageView>
</RelativeLayout>
A: It works fine with setting android:orientation="vertical" for each text view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Couldn't access values of form after $.POST call? I'm having a form and using the $.POST for posting it to the some url..
From there i couldn't access the form values. I dont know what the error may be??
The form is like
<form id="registration-form" >
<input type="hidden" name="Profile[fb_uid]" value='1232323'></input>"
<select name="Profile[feet]" id="feet">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<a class="btnLgBlueGrad" href="#" name="closeModal" id="profileSubmit">Start</a>
</form>
the js call is like this
$( "#profileSubmit" ).click(function() {
$.post("?r=site/addBasicProfile",
function(data){
alert(data); // this is alerting as empty
if(data==1)
window.location.href="?r=site/index";
});
});
The actual method which is called is
public function actionAddBasicProfile(){
echo $_REQUEST['profile'];
// when i echo something static it is reflected in the ajax callback function
}
I'm sure the url is correct and ajax request is passed.
A: That's because you don't pass any data to the $.post(), from the jquery website:
jQuery.post( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
So you should pass some data to your php script:
$.post("?r=site/addBasicProfile",
$('#registration-form').serialize(), // this will serialize the form data
function(data){
alert(data); // this is alerting as empty
if(data==1)
window.location.href="?r=site/index";
}
);
And as a side note you should use $_POST to get POST values since $_REQUEST can also get you the GET values.
A: or serialize form and also could use lowercase in names.
A: you need to pass the form parameters as data with the $.post call.
examples @ http://api.jquery.com/jQuery.post/
You can also use ajaxSubmit available with the JQuery forms plugin, which will handle it for you. @ http://jquery.malsup.com/form/
$('#form').ajaxSubmit({
success: handle_success,
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best way to store a huge list with hashes in Javascript I have a list with 10.000 entrys.
for example
myList = {};
myList[hashjh5j4h5j4h5j4]
myList[hashs54s5d4s5d4sd]
myList[hash5as465d45ad4d]
....
I dont use an array (0,1,2,3) because i can check
very fast -> if this hash exist or not.
if(typeof myObject[hashjh5j4h5j4h5j4] == 'undefined')
{
alert('it is new');
}
else
{
alert('old stuff');
}
But i am not sure, is this a good solution?
Is it maybe a problem to handle an object with 10.000 entries?
EDIT:
I try to build an rss feed reader which shows only new feeds. So i calculate an hash from the link (every news has an uniqe link) and store it in the object (mongoDB). BTW: 10.000 entrys is not the normal case (but it is possible)
A: You can use the in operator:
if ('hashjh5j4h5j4h5j4' in myList) { .. }
However, this will also return true for members that are in the objects prototype chain:
Object.prototype.foo = function () {};
if ("foo" in myList) { /* will be true */ };
To fix this, you could use hasOwnProperty instead:
if (myList.hasOwnProperty('hashjh5j4h5j4h5j4')) { .. }
Whilst you yourself may not have added methods to Object.prototype, you cannot guarantee that other 3rd party libraries you use haven't; incidentally, extending Object.prototype is frowned upon, so you shouldn't really do it. Why?; because you shouldn't modify things you don't own.
A: My advice:
*
*Use as small of a hash as possible for the task at hand. If you are dealing with hundreds of hashable strings, compared to billions, then your hash length can be relatively small.
*Store the hash as an integer, not a string, to avoid making it take less room than needed.
*Don't store as objects, just store them in a simple binary tree log2(keySize) deep.
Further thoughts:
*
*Can you come at this with a hybrid approach? Use hashes for recent feeds less than a month old, and don't bother showing items more than a month old. Store the hash and date together, and clean out old hashes each day?
A: 10.000 is quite a lot. You may consider storing the hashes in a database and query it using ajax. It maybe takes a bit longer to query one hash but your page loads much faster.
A: It is not a problem in modern browser on modern computers in any way.
10k entries that take up 50 bytes each would still take up less than 500KB ram.
As long as the js is served gzipped then bandwidth is no problem - but do try to serve the data as late as possible so they don't block perceived pageload performance.
All in all, unless you wish to cater to cellphones then your solution is fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Extra BR tag appears between P tags on Facebook fan page notes We have a Facebook page that imports notes from our RSS feed. Content from our feed is like
<p>Foo bar.</p>
<p>Bar foo.</p>
At our Facebook page, when the note is imported, content is like
<p>Foo bar.</p><br /><p>Bar foo.</p>
Apparently the \n in the original content is replaced with a br tag.
As a result, this FB note is a burden to read.
I haven't yet tried removing the \n between paragraphs in original content. I was hoping this issue could be fixed without such artificial maneuvers.
Our feed goes through Feedburner. Not sure if that's related.
Any ideas how to get rid of this extra line break?
A: Set the open graph og:title and og:description meta tags as described here: http://developers.facebook.com/docs/opengraph/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPad live view overlay I would like to draw a simple animation over the "live view" of my IPad camera. Simplest way to do so?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android - Thumb of fastscroll in expandablelistview doesnt scroll list correctly i am using an expandablelistview to show a list of groups containing different counts of children. sometimes the list is very long, so i wanted to enable fastscroll. i did this and everything is working fine when i scroll the list with the finger in the usual way.
but when i grab the thumb and drag it to the bottom, the list is scrolled to the last position when i have moved the thumb about 1/3 of the height from the top. what can i do to have the thumb position the list according to the full height of the scrollbar?
A: Last answer went missing.
This is a known bug in Android FastScroller.
See my code attached to http://code.google.com/p/android/issues/detail?id=24635
it contains a work-around that works for some specific cases.
A: I posted a workaround here. It uses a OnScrollListener to act differently if the user scrolls via touch or via thumb.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: cannot install django-filebrowser app I did exactly as it says here: http://readthedocs.org/docs/django-filebrowser/en/latest/quickstart.html#quickstart (only used easy_install instead of pip)
it seems that I get an import error when trying to connect to admin interface:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.3
Exception Type: ImportError
Exception Value:
No module named sites
Exception Location: c:\workspace\expedeat\..\expedeat\urls.py in <module>, line 5
Python Executable: c:\Tools\Python26\python.exe
Python Version: 2.6.4
the import the exception comes from is: from filebrowser.sites import site in urls.py
Also testing filebrowser fails with this message:
Creating test database for alias 'default'...
.......F......
======================================================================
FAIL: test_directory (filebrowser.tests.settings.SettingsTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Tools\Python26\lib\site-packages\django_filebrowser-3.3.0-py2.6.egg\filebrowser\tests\set
tings.py", line 29, in test_directory
self.assertEqual(os.path.exists(os.path.join(MEDIA_ROOT,DIRECTORY)), 1)
AssertionError: False != 1
----------------------------------------------------------------------
Ran 14 tests in 0.008s
FAILED (failures=1)
Destroying test database for alias 'default'...
I must be doing something wrong. Any help would be appreciated.
A: the sites.py module does not exist in version you are using, so the error message is correct.
the installation doc you are using is for version 3.4. The pip install is 3.3. The difference being in the urls.py
3.4
from filebrowser.sites import site
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
3.3
urlpatterns = patterns('',
(r'^admin/filebrowser/', include('filebrowser.urls')),
)
A: The test fails because it's looking for a non-existing directory.
To find out what directory it's looking for, do the following:
% python ./manage.py shell
>>> from django.conf import settings
>>> import filebrowser.settings
>>> filebrowser.settings.MEDIA_ROOT
'/srv/repositories/project/media'
>>> filebrowser.settings.DIRECTORY
'uploads/'
Based on the output, you know what directory it's looking for, /srv/repositories/project/media/uploads in this example. Create the directory and you should be one step further on your way.
A: Using the "FILEBROWSER_" prefix, you can supply configuration for the filebrowser app.
I use the following in my settings.py :
FILEBROWSER_DIRECTORY = MEDIA_ROOT
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing system properties to tomcat managed webapp when started by another process The startUp script of webapp is going to be executed by a standalone java management process. I understand that -D system properties can be set to CATALINA_OPTS in catalina.sh. So is the only way to pass system properties is for the java management process to go write into catalina.sh? I
A: I think this should be possible, but dont have the exact answer.
If it can be passed in an ant task like shown on this link, I assume it should be able to call the
org.apache.catalina.startup.Bootstrap load() passing in JVM args
<target name="tomcat-start">
<java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
<jvmarg value="-Dcatalina.home=${tomcat.home}"/>
</java>
</target>
<target name="tomcat-stop">
<java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
<jvmarg value="-Dcatalina.home=${tomcat.home}"/>
<arg line="stop"/>
</java>
</target>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check installed Excel version and launch it I am trying in my application to launch Microsoft Excel with specific arguments (ie. additional xla & xll).
For now it works fine because all of my users only have Office11 (=2003) installed.
My company is going to switch to Windows 7 & Office 2010 and I logically can't launch any excel since the .exe is not located in C:\Program Files:\Microsoft Office\Office11\EXCEL.EXE
I ran a quick check in the registry to see that I can definitely check what version is currently installed. There are also plenty of articles explaining how to get the currently installed Office version.
However, I'd like to know if it is possible to find anything (such as a good registry key) directly giving me the .exe path so as to launch Excel.
Using my current machine (Win XP x86, Office11), I can find it in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\11.0\Excel\InstallRoot
Using this key I can, basically, find a workaround to get the actual path. Problem: there is no such key in Windows 7's registry with Office 2010 (= Office 14) installed.
Do you guys know any way to launch the currently installed excel from C#?
FYI, here is the current code section, launching Office11 from a x64 / x86 machine:
private void LaunchExcel(string arguments)
{
if (!Is64BitsOS())
{
Process process = new Process();
process.StartInfo.FileName = "excel";
process.StartInfo.Arguments = arguments;
process.Start();
}
else
{
Process process = new Process();
process.StartInfo.FileName = "c:/Program Files (x86)/Microsoft Office/Office11/excel.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.Arguments = arguments;
process.Start();
}
}
Any ideas to make this code more generic?
A: If you start Excel to open an Excel file, you can start a Process with the Excel file as FileName and let the Windows shell do all the work to find the associated application. You'd need an exception handler, obviously.
This would make you independent of Office and Windows versions and registry keys.
Otherwise you could take a different approach and find the associated application, like here.
The point of these suggestions is: presently, you have to change your code as soon as a new Office version is installed or a different Windows version is used, while there is a way to avoid these dependencies.
A: The 32 bit version of Excel 2010 running on a 64 bit version of Windows (XPx64,Vistax64,Win7x64) will have the following key.
I think this is the key you are looking for
HKLM\SOFTWARE\Wow6432Node\Microsoft\Office\14.0\Excel\InstallRoot
The 64 bit version of Excel 2010 running on a 64 bit version of Windows (XPx64,Vistax64,Win7x64) will have the following key
HKLM\SOFTWARE\Microsoft\Office\14.0\Excel\InstallRoot
copied from here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with CLLocationManager in iOS Simulator I try to show a location on the map, here is the code:
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager.location initWithLatitude:latitude longitude: longitude];
NSLog(@"%f", [selectedBuilding.latitude doubleValue]);
[locationManager startUpdatingLocation];
However, no matter what coordinates I provide, the blue dot always locates in California which seems the default behaviour, is there anything additional I need to do? Thanks.
A: In simulator CLLocationManager is always in headquarters of Apple. It's from CLLocation Class reference:
coordinate
The geographical coordinate information. (read-only)
@property(readonly, nonatomic) CLLocationCoordinate2D coordinate
Discussion
When running in the simulator, Core Location assigns a fixed set of coordinate values to this property. You must run your application on an iPhone OS–based device to get real location values.
Availability
Available in iPhone OS 2.0 and later.
Declared In
CLLocation.h
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Vim, word frequency function and French accents I have recently discovered the Vim Tip n° 1531 (Word frequency statistics for a file).
As suggested I put the following code in my .vimrc
function! WordFrequency() range
let all = split(join(getline(a:firstline, a:lastline)), '\A\+')
let frequencies = {}
for word in all
let frequencies[word] = get(frequencies, word, 0) + 1
endfor
new
setlocal buftype=nofile bufhidden=hide noswapfile tabstop=20
for [key,value] in items(frequencies)
call append('$', key."\t".value)
endfor
sort i
endfunction
command! -range=% WordFrequency <line1>,<line2>call WordFrequency()
It works fine except for accents and other french specifics (latin small ligature a or o, etc…).
What am I supposed to add in this function to make it suit my needs ?
Thanks in advance
A: The pattern \A\+ matches any number of consecutive non-alphabetic characters which — unfortunately — includes multibytes characters like our beloved çàéô and friends.
That means that your text is split at spaces AND at multibyte characters.
With \A\+, the phrase
Rendez-vous après l'apéritif.
gives:
ap 1
apr 1
l 1
Rendez 1
ritif 1
s 1
vous 1
If you are sure your text doesn't include fancy spaces you could replace this pattern with \s\+ that matches whitespace only but it's probably to liberal.
With this pattern, \s\+, the same phrase gives:
après 1
l'apéritif. 1
Rendez-vous 1
which, I think, is closer to what you want.
Some customizing may be necessary to exclude punctuations.
A: For 8-bit characters you can try to change the split pattern from \A\+ to
[^[:alpha:]]\+.
A: function! WordFrequency() range
" Whitespace and all punctuation characters except dash and single quote
let wordSeparators = '[[:blank:],.;:!?%#*+^@&/~_|=<>\[\](){}]\+'
let all = split(join(getline(a:firstline, a:lastline)), wordSeparators)
"...
endfunction
If all punctuation characters should be word separators, the expression shortens to
let wordSeparators = '[[:blank:][:punct:]]\+'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the LPTSTR equivalent of _strnicmp in windows? Is there a LPTSTR equivalent of _strnicmp which takes in 2 LPTSTR strings, and number of TCHARs to compare until?
using the c winapi btw
A: It is _tcsncicmp, see the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: problem with url when calling wcf service by httpWebRequest When I call manually wcf service what should I type in url place :
HttpWebRequest httpWebRequest = WebRequest.Create(url)as HttpWebRequest;
should be there url to my svc file
http://localhost/service/LMTService.svc
or wsdl
http://localhost/service/LMTService.svc?wsdl
or url to service action ?
http://localhost/service/LMTService.svc/soap/GetSerializedSoapData
A: It depends on the binding of the endpoint. If using a SOAP binding (i.e., basicHttpBinding, wsHttpBinding, etc), the request URI should be the endpoint address (not the service address). Also, in some SOAP versions (such as SOAP11, used in basicHttpBinding), you need to specify the action as a HTTP header. If you're using webHttpBinding (with webHttp behavior) the address is the address of the endpoint, plus the UriTemplate (which by default is just the method name) of the operation you want to call.
The code below shows a HttpWebRequest-based request being sent to two endpoints, a one using BasicHttpBinding, one using WebHttpBinding.
public class StackOverflow_7525850
{
[ServiceContract]
public interface ITest
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Add(int x, int y);
}
public class Service : ITest
{
public int Add(int x, int y)
{
return x + y;
}
}
public static string SendRequest(string uri, string method, string contentType, string body, Dictionary<string, string> headers)
{
string responseBody = null;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Method = method;
if (headers != null)
{
foreach (string headerName in headers.Keys)
{
req.Headers[headerName] = headers[headerName];
}
}
if (!String.IsNullOrEmpty(contentType))
{
req.ContentType = contentType;
}
if (body != null)
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
req.GetRequestStream().Close();
}
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
resp = (HttpWebResponse)e.Response;
}
if (resp == null)
{
responseBody = null;
Console.WriteLine("Response is null");
}
else
{
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
foreach (string headerName in resp.Headers.AllKeys)
{
Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
}
Console.WriteLine();
Stream respStream = resp.GetResponseStream();
if (respStream != null)
{
responseBody = new StreamReader(respStream).ReadToEnd();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("HttpWebResponse.GetResponseStream returned null");
}
}
Console.WriteLine();
Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
Console.WriteLine();
return responseBody;
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "basic");
host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "web").Behaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Host opened");
string soapBody = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Body>
<Add xmlns=""http://tempuri.org/"">
<x>44</x>
<y>55</y>
</Add>
</s:Body>
</s:Envelope>";
SendRequest(baseAddress + "/basic", "POST", "text/xml", soapBody, new Dictionary<string, string> { { "SOAPAction", "http://tempuri.org/ITest/Add" } });
SendRequest(baseAddress + "/web/Add", "POST", "text/xml", "<Add xmlns=\"http://tempuri.org/\"><x>55</x><y>66</y></Add>", null);
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to add a line as a gesture while moving from one image to another? I am making my own Pattern Lock for android phone, i have Done the coding as when i click on an image it stores an integer in an array and when the user re-enters the same password it matches both the arrays and Open the lock accordingly, my code is working fine But Now i have to add gesture in the form of a line while going from one image to another (as in pattern lock) also i want to store the integers in the array when i touch an image instead of clicking it...
guide me how to do this below is my sample code for image click events
public void Image1(View view) {
// Toast.makeText(this, "You clicked Image 1!",
// Toast.LENGTH_SHORT).show();
myArray[0] = 1;
// builder.append("" + myArray[0] + " ");
// Toast.makeText(this, myArray, Toast.LENGTH_LONG).show();
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image2(View view) {
// Toast.makeText(this, "You clicked Image 2!",
// Toast.LENGTH_SHORT).show();
myArray[1] = 2;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image3(View view) {
// Toast.makeText(this, "You clicked Image 3!",
// Toast.LENGTH_SHORT).show();
myArray[2] = 3;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image4(View view) {
// Toast.makeText(this, "You clicked Image 4!",
// Toast.LENGTH_SHORT).show();
myArray[3] = 4;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image5(View view) {
// Toast.makeText(this, "You clicked Image 5!",
// Toast.LENGTH_SHORT).show();
myArray[4] = 5;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image6(View view) {
// Toast.makeText(this, "You clicked Image 6!",
// Toast.LENGTH_SHORT).show();
myArray[5] = 6;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image7(View view) {
// Toast.makeText(this, "You clicked Image 7!",
// Toast.LENGTH_SHORT).show();
myArray[6] = 7;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image8(View view) {
// Toast.makeText(this, "You clicked Image 8!",
// Toast.LENGTH_SHORT).show();
myArray[7] = 8;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
public void Image9(View view) {
// Toast.makeText(this, "You clicked Image 9!",
// Toast.LENGTH_SHORT).show();
myArray[8] = 9;
ImageView kk = (ImageView) view;
Drawable d = getResources().getDrawable(R.drawable.unlock);
kk.setImageDrawable(d);
}
A: Implement onTouchEvent(MotionEvent ev), with ACTION_DOWN, ACTION_MOVE, ACTION_UP. As your finger moving, draw a line from previous Coordinate to current Coordinate.
Get coordinate by using ev.getX() ev.getY()
I've just thought of two solution currently:
*
*When detecting touch event, at ACTION_DOWN, draw a transparent VIEW on top of parent view, make it Canvas and draw as long as ACTION_MOVE is under processing.
*Use SurfaceView instead of regular View. A sample on SurfaceView to draw: http://www.droidnova.com/playing-with-graphics-in-android-part-ii,160.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows service rights to write in log file I have created a Windows service using C# that writes logs (with NLog) in C:\ProgramData.
When I debug the service (on my Windows 7) (using the code written above), the log file is correctly created and log records correctly written.
But when I install the service on my server which runs on Windows server 2008 (x86), no log file is created (I have also checked in C:\Windows\System32\, nothing there).
I suspect that it is an authorization problem so how can I know what rights is my service using?
PS: I have installed my service using the command line C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PathToMyService\MyService.exe with Administrator rights.
A: Run services.msc, find your service right click and select Properties. Check the Log On tab to see which account your service is running under.
As for your problem, by default I think most services run under the Local System Account which I would assume has permissions to write to the C:\ProgramData directory. Have you made sure the nlog.config file is deployed with your service?
A: You should see your service in the windows control panel fpr services. In the contextmenu you can see the user which runs your service. You can even change the user running your service there.
You have to give that user the right to write in your log directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Problem with using PHPMailer for SMTP I have used PHPMailer for SMTP and there is problem in sending mail with error "Mailer Error: The following From address failed: no-reply@mydomain.org.uk"
My code is as follows:
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "localhost;"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = ""; // SMTP username
$mail->Password = ""; // SMTP password
$mail->From = $email_address;
$mail->FromName = $email_address;
$mail->AddAddress($arrStudent[0]["email"]);
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Subject";
$theData = str_replace("\n", "<BR>", $stuff);
$mail->Body = $theData; // "This is the <b>HTML body</b>";
$mail->AltBody = $stuff;
if (!$mail->Send()) {
$sent = 0;
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
i researched everything and when i debug inside class.smtp.php i found error the function "get_lines()" is returning error value "550 Authentication failed"
The code was working fine previously, i am wondering how this problem came suddenly.
Desperate for some help.
Thanks,
Biplab
A: public function sendEmail ( $subject, $to, $body, $from = FALSE ) {
require_once('mailer.class.php');
$mailer = new PHPMailer();
//do we use SMTP?
if ( USE_SMTP ) {
$mailer->IsSMTP();
$mailer->SMTPAuth = true;
$mailer->Host = SMTP_HOST;
$mailer->Port = SMTP_PORT;
$mailer->Password = '';
$mailer->Username = '';
if(USE_SSL)
$mailer->SMTPSecure = "ssl";
}
$mailer->SetFrom($from?$from:ADMIN_EMAIL, ADMIN_NAME);
$mailer->AddReplyTo ( ADMIN_EMAIL, ADMIN_NAME );
$mailer->AddAddress($to);
$mailer->Subject = $subject;
//$mailer->WordWrap = 100;
$mailer->IsHTML ( TRUE );
$mailer->MsgHTML($body);
require_once('util.class.php');
$mailer->AltBody = Util::html2text ( $body );
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if ( ! $mailer->Send() ) {
return FALSE;
}
else {
$mailer->ClearAllRecipients ();
$mailer->ClearReplyTos ();
return TRUE;
}
}
I've used like that... SetFrom should be used in place of From... that's your error buddy... :))
A: try adding belowe line to php.ini
extension=php_openssl.dll
restart and try again
A: I am using YII's Mailer with PHPMailer, and this works for me:
$mail = Yii::createComponent('application.extensions.mailer.EMailer');
$mail->Username = $this->SMTP_USERNAME; // SMTP username
$mail->Password = $this->SMTP_PASSWORD; // SMTP password
$mail->SMTPAuth = true;
$mail->From = $this->fromAddress;
$mail->Host = $this->SMTP_SERVER_ADDRESS;
$mail->FromName = $this->fromName;
$mail->CharSet = 'UTF-8';
$mail->Subject = Yii::t('mailer', $this->subject);
$mail->Body = $this->message;
$mail->AddReplyTo($this->toAddress);
$mail->AddAddress($this->toAddress);
$mail->IsSMTP(true);
$mail->IsHTML(true);
$mail->Send();
Hope that helps?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Accordion - How To Add clickable item in the header title?
Possible Duplicate:
How to make only specific text clickable on accordion header - jquery?
I'm looking for a way to add clickable item in the jQuery Accordion Title (header). I'm using the default Accordion (http://jqueryui.com/demos/accordion/#default):
<div id="accordion">
<h3><a href="#">Section 1</a></h3>
<div>
<p>blah</p>
</div>
<h3><a href="#">Section 2</a></h3>
<div>
<p>blah blah</p>
</div>
<h3><a href="#">Section 3</a></h3>
<div>
<p>blah blah blah</p>
</div>
</div>
And I would like to have something similar to:
<div id="accordion">
<h3><a href="#">Section 1</a><span style="align:right"><a href="http://www.stackovweflow.com">SO</a> - <span style="align:right"><a href="http://www.stackovweflow.com">SO2</a></span></h3>
<div>
<p>blah</p>
</div>
<h3><a href="#">Section 2</a><span style="align:right"><a href="http://www.stackovweflow.com">SO</a> - <span style="align:right"><a href="http://www.stackovweflow.com">SO2</a></span></h3>
<div>
<p>blah blah</p>
</div>
<h3><a href="#">Section 3</a><span style="align:right"><a href="http://www.stackovweflow.com">SO</a> - <span style="align:right"><a href="http://www.stackovweflow.com">SO2</a></span></h3>
<div>
<p>blah blah blah</p>
</div>
</div>
where "Section X" actions the accordion and other links are independents. Any ideas ?
Here the "span" are on a new lines...
EDIT:
Ok get it:
How to make only specific text clickable on accordion header - jquery?
<div id="accordion" class="ui-accordion2-group">
<h3 class="ui-accordion2-header"><a href="#">Section 1</a>
<div class="tools">
<a href="http://www.stackovweflow.com">SO</a>
<a href="http://www.stackovweflow.com">SO2</a>
</div>
</h3>
<div>
<p>blah</p>
</div>
</div>
<style>
.ui-accordion2-header .tools{
position: absolute;
right: 1px;
top: 8px;
width: 300px;
}
.ui-accordion2-header .tools a {
width: auto;
display: inline;
}
</style>
Does the trick!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use the underlying Socket/ServerSocket in a SocketChannel/ServerSocketChannel? I'm trying the Java.nio-package for non-blocking communication. So I got my ServerSocketChannel and all my connected clients (SocketChannel) in a Selector and wait for data (OP_ACCEPT/OP_READ) using Selector.select().
My question is: Can I - instead of using a ByteBuffer and read directly with SocketChannel.read() - use the underlying Socket, get an InputStream and read using that stream? Or will that mess up the selector-stuff?
A: You can't.
http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#getInputStream%28%29
If this socket has an associated channel then the resulting input stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the input stream's read operations will throw an IllegalBlockingModeException.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Noise in recording in mac app I am using QTKit for recording and playing, but when i am recording the resultant file having lot of noise(air pressure).
I am using
QTCaptureDevice *audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeSound];
and capture session
captureSession = [[QTCaptureSession alloc] init];
And these
QTCaptureDecompressedAudioOutput *captureAudioDataOutput;
AudioUnit effectAudioUnit;
ExtAudioFileRef extAudioFile;
AudioStreamBasicDescription currentInputASBD;
AudioBufferList *currentInputAudioBufferList;
Also these lines (may be the reason of noise is here)
/* Create an effect audio unit to add an effect to the audio before it is written to a file. */
OSStatus err = noErr;
AudioComponentDescription effectAudioUnitComponentDescription;
effectAudioUnitComponentDescription.componentType= kAudioUnitType_Effect;
effectAudioUnitComponentDescription.componentSubType = 0;
effectAudioUnitComponentDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
effectAudioUnitComponentDescription.componentFlags = 0;
effectAudioUnitComponentDescription.componentFlagsMask = 0;
Please some one help me.
A: You should not be getting any noise if you set it up correctly. Basically, you do not need to setup the audio device at all. You need to get one and use it. The list if available audio devices in your system can be obtained from the QTCaptureDevice class:
[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeSound]
Select the one you need and get the audio input for it:
[STCaptureDeviceInput captureDeviceInputWithDevice:audioDevice type:STCaptureDeviceAudio]
Set the input to the capture session before recording:
[_captureSession addInput:captureAudioDeviceInput error:&error]
It should just work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Submitting a Certificate Signing Request for Approval I've looked at the "How To" docs provided in the Provisioning portal and under the "Submitting a Certificate Signing Request for Approval" link. It says that by clicking on Certificates > Development I can upload the CSR for approval but when I click on Certificates > Development I only can view the "Current Development Certificates" and "Team Signing Requests (0)".
Why can't I find a way to upload a CSR in the Provisioning Portal, Could it be that I dont have the right permissions I am using the companies login to the portal as they want the app to be submitted through their account.
The member I'm logging in with is the team agent (apparently), could this be causing the problem or is there something else i'm missing?
Thanks
Brett
A: Because your are login with the team agent credentials you see your team agent's development certificate. Because this certificate has not expire yet, you cannot upload a new CSR to create a new certificate. You have three different options to solve this problem, I will order them from the best to the worst :
*
*Ask your team agent to register you as a new team member and, after login with your new credentials, create your own development certificate.
*Download your team agent's development certificate and ask your team agent to export his development private key for you in order to use the certificate properly.
*Revoke you team agent's development certificate and create a new one. You will have to export your new certificate and your new private key to other members of your team.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Noob seeking help with Database [Access] I'm fairly new at access and I have no clue how to handle this situation. I dont even know where to start so any help would be greatly appreciated.
So I have to design this data base that has items such as "audio board X.xx" When a customer orders lets say "audio board 2.4", the database will know that the board requires 2x4K Resisters and 4x2uf Capacitors and 2X4401 BJTs. And it would automatically pull them from the inventory when processing this order so later on I can just look at the inventory list lets say at the end of the week and will know what parts i would need to order to restock.
now, i looked for help online, the only thing i could find similar was something called "Bill of Materials" AKA "BOM" sheets or something... but none of them told me how to make one or anything like that.
I'm really new at this, and am a total noob. I'm using Access 2010. Any Help would be appreciated.
A: First, read http://r937.com/relational.html
You will need a design on the lines of:
Parts
ID -->Primary key
Description
Etc
Components
ID -->Primary key
Description
Etc
PartsComponents --> Junction table
PartID ---) ??
ComponentID ---)
If a part can have only one of each component, life is simple enough and PartID + ComponentID is your primary key, if a part can only have a set number of a particular component, it may be possible to treat the set as a single item, if the part can have a variable number of a component, things get a little more complicated. A quantity field in the junction table would probably work, though.
You then have a fairly standard set of tables for customers and orders, including an order detail table, which gets updated by an append query from the junction table information when a customer selects a part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: loading traineddata for tesseract-android-tools (android) I am working on android app.
What I need is directly path to traineddata file (to init tesseract).
Look like best option is to set the resource in raw.
I am getting resource ID this way (file name is : deu.traineddata):
int rID = resources.getIdentifier("deu", "raw", "my.code.package");
OK, 'rID' > 0, now getting Stream :
InputStream is = resources.openRawResource(rID);
ok, 'is' != null.
But now getting problem ,by reading 'is' IOException has been throw, with no stack trace :
byte[] bytes = new byte[is.available()];
is.read(bytes);
I try also to read file from asset , but is the same problem by reading from InputStream.
What i'am doing wrong, ist there any other way to get the resource path ?
thanx
andrej
A: If you look at the native code in tesseract-android-tools (under jni), you will see that the library will access a file. I am in the same boat at the moment. After some digging, my plan is to store the traineddata file as a resource along with the project, and write to the private file on load.
The pseudo code is something like this:
on load, check for private file,
if it doesn't exist, load the traineddata from raw dir and write to the private file.
initialize tesseract with the private file.
ref:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
http://developer.android.com/guide/topics/resources/providing-resources.html
Cheers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the right way of making of blinking text I have a textview and I have many buttons. One of the button should be able to start the 'animation' well it is not animation in anim, it just need to make the text go red for a 2 seconds than the text should go green for 2 seconds than again back to red....
-one of the buttons should stop the 'animation' and set the text to white
-one should make the text back for 1 sec, than blue for 2sec and again back to black...
the point is the buttons should be able to be pressed by the user in any time.
I think I should use Handler but I am not sure for the patter , I do not know how the stoping of the thread should look like, I mean when I start thread , later on I should tell him to stop... What is the best way to do this ?
I always code this kind of thinks with stupid tricks , and I do not know what is the pattern, what is the right way to do this ?
Thanks
here is some code of how I do it, but I feel that this is not the right way
private boolean flagForStop=true;
private Handler handler1=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
flagForStop=false;
case 1:
flagForStop=true;
break;
case 2:
new Thread(){
public void run(){
while(true){
if(flagForStop)break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//do something
}
}
}.start();
break;
default:
break;
}
}
};
and than i the listener something like
handler1.sendEmptyMessage(0);
A: Here is how I would do it, it's not perfect but it should work for all the types of animations you've mentioned above.
First create a class called AnimStep which contains two fields: time and color. Constructor is AnimStep(int time, String color)
Then create a class called AnimSequence which contains an array of AnimStep objects. You get a specific step with this.getStep(index).
For instance AnimSequence for "pink 2 seconds then magenta 3 seconds then black forever" would contain the following array of AnimSteps: {new AnimStep(0, "pink"), new AnimStep(2, "magenta"), new AnimStep(5, "black")}
Then create a class called Animation which runs permanently in a separate thread and wakes up regularly (e.g. every 100ms). This class has three fields:
*
*sequence: a pointer to an AnimSequence object
*startTime: a timestamp
*step: an integer which represents the index of an element in an array of AnimStep
When you click a button, you pass an AnimSequence to Animation. This sets this.sequence to the given AnimSequence, this.startTime = , this.step = 1. It also sets the color of the text to the color of you first AnimStep in AnimSequence.
Now each time the Animation wakes up, it does the following:
if (this.step >= this.sequence.size()) return // do nothing
currentStep = this.sequence.getStep(this.step)
elapsedTime = <current time stamp for now> - this.time
if (elapsedTime >= currentStep.time) {
this.step++
yourtext.color = currentStep.color
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP: including pages - html tags or not? I'm designing a template for a webpage and I'm building separate parts of the template in different pages that will all be included in one page (ie, leftdiv.php, maindiv.php, header.php, footer.php etc). The website will contain Greek characters and I'm using utf-8 encoding.
Now I have leftdiv.php which contains greek chars but I've left out the html & meta tags that define the page encoding and as a result, I'm having problems displaying the page in the right encoding, probably because when index.php requires leftdiv.php, there isn't a meta tag for the proper encoding.
Should I leave the meta tags on each included file or not? What other options do I have?
A: Meta tags doesn't matter.
You have to set up encoding in the real HTTP headers, not in meta substitution.
So, set your encoding in the PHP code by
header('Content-type: text/html; charset=utf-8');
and leave meta tags alone.
I am also wondering why you're using so much template files (leftdiv.php, header.php, footer.php etc) instead of placing them all in one main template.
A: My guess is that it goes wrong when uploading the file. Try binary mode (ftp), as some characters may not be ascii chars.
Further; don't worry about meta tags etc. in a template part; when outputting to the browser, all parts are concatenated by php and sent as one html page. The browser doesn't know anything about your different parts, just sees the whole picture. So check the html source in your browser. If the source is properly marked up, and the proper meta tag is in the , everything should be allright. To test it, just upload a simple html file. If it works, then extend it to different parts.
A: You have to store the files with UTF-8 encoding on your disc. Then the meta tag is okay without sending extra header.
<meta charset="UTF-8" />
A: Meta tags should be only in the head section of a page. And by page I mean the document that is shown by your web browser, not the PHP scripts behind it. So don't put meta tags in footer.php for example.
A: if you set header('Content-type: text/html; charset=utf-8'); with page by saved using UTF-8 encoding everything will be fine.
A: The browser doesn't know anything about your different parts, just sees the whole picture. So check the html source in your browser.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Polymorphic lift-json deserialization in a composed class I am trying to automatically deserialize json object to a scala class using Lift-Json with a coordinate class inside used to store GeoJson information.
case class Request(name:String, geometry:Geometry)
sealed abstract class Geometry
case class Point(coordinates:(Double,Double)) extends Geometry
case class LineString(coordinates:List[Point]) extends Geometry
case class Polygon(coordinates:List[LineString]) extends Geometry
I want to deserialize a json string like this:
{
name:"test",
geometry:{
"type": "LineString",
"coordinates": [ [100.0, 0.0], [101.0, 1.0] ]
}
}
into a Request case class with the right LineString runtime class in the Geometry field. I guess I should use a TypeHint but how?. Is this the correct approach or should I create three different Request (RequestPoint,RequestLineString and RequestPolygon)?
This would be the Scala code to deserialize:
val json = parse(message)
json.extract[Request]
A: Yes, you need to use type hints for sum types like Geometry. Here's one example:
implicit val formats = DefaultFormats.withHints(ShortTypeHints(List(classOf[Point], classOf[LineString], classOf[Polygon])))
val r = Request("test", LineString(List(Point(100.0, 0.0), Point(101.0, 1.0))))
Serialization.write(r)
{
"name":"test",
"geometry":{
"jsonClass":"LineString",
"coordinates":[{"jsonClass":"Point","coordinates":{"_1$mcD$sp":100.0,"_2$mcD$sp":0.0}},{"jsonClass":"Point","coordinates":{"_1$mcD$sp":101.0,"_2$mcD$sp":1.0}}]}
}
Not quite what you wanted. Since you want to change the default serialization scheme for Points, you need to provide a custom serializer for that type.
class PointSerializer extends Serializer[Point] {
private val Class = classOf[Point]
def deserialize(implicit format: Formats) = {
case (TypeInfo(Class, _), json) => json match {
case JArray(JDouble(x) :: JDouble(y) :: Nil) => Point(x, y)
case x => throw new MappingException("Can't convert " + x + " to Point")
}
}
def serialize(implicit format: Formats) = {
case p: Point => JArray(JDouble(p.coordinates._1) :: JDouble(p.coordinates._2) :: Nil)
}
}
// Configure it
implicit val formats = DefaultFormats.withHints(ShortTypeHints(List(classOf[Point], classOf[LineString], classOf[Polygon]))) + new PointSerializer
Serialization.write(r)
{
"name":"test",
"geometry":{
"jsonClass":"LineString",
"coordinates":[[100.0,0.0],[101.0,1.0]]
}
}
Better, but you need one more configuration if you need to change the default field named as 'jsonClass' to 'type':
implicit val formats = new DefaultFormats {
override val typeHintFieldName = "type"
override val typeHints = ShortTypeHints(List(classOf[Point], classOf[LineString], classOf[Polygon]))
} + new PointSerializer
Serialization.write(r)
{
"name":"test",
"geometry":{
"type":"LineString",
"coordinates":[[100.0,0.0],[101.0,1.0]]
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Another LazyInitializationException (in combination with Spring+GSON) I guess I'm another newbie guy who fails to understand Hibernate sessions, may be Spring's TransactionTemplate, dunno. Here's my story.
I'm using Hibernate 3.5.5-Final, Spring 3.0.4.RELEASE, trying to live only with annotations (for Hibernate as well as Spring MVC).
My first try was to use @Transactional annotations in combination with properly setup transaction manager. Seemed to work at first, but in long run (about 36hours) I started to receive "LazyInitializationExceptions" over and over again (from places that were running just fine in previous hours!).
So I switched to manual transactions using Spring TransactionTemplate.
Basically I'm having something like this protected stuff in my BaseService
@Autowired
protected HibernateTransactionManager transactionManager;
protected void inTransaction(final Runnable runnable) {
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
transaction.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus status) {
try {
runnable.run();
return true;
} catch (Exception e) {
status.setRollbackOnly();
log.error("Exception in transaction.", e));
throw new RuntimeException("Exception in transaction.", e);
}
}
});
}
And using this method from the service's impls worked OK, I did not see LazyInitializationException for 10 days (running Tomcat with this single app 24*7 for 10days, no restarts) ... but than hoops! It has popped again :-/
The LazyInitializationException comes from place under "inTransaction" method and there is no "inTransaction recursion" involved, so I'm pretty sure I should be in the same transaction alas in the same Hibernate session. There is no "data from previous session" involved (as far as my code goes that service layer opens the transaction, gathers all data from Hibernate it needs, process it and returns some result == service does not recall other top-services)
I have not profiled my app (I don't even know how to do that properly in long runs such as 10 days), but my only guess is that I'm leaking memory somewhere and JVM hits heap-limit...
Is there some "SoftReferences" involed inside Spring or Hibernat? I don't know...
Another funny thing is that the exception always happen when I try to serialize the result into JSON using Google GSON serializer. I know, it does not use getters ... I have my own patched version that is using getters instead of actual fields (so I'm making sure not to bypass Hibernate proxy mechanisms), do you think it may play some role here?
Last funny thing is that the exception is always happing in the single service method (not anywhere else), which is driving me nuts because this method is as simple-stupid as it could be (no extrem DB operations, just loads data and serialize them to JSON using lazy-fetching), huh???
Does anybody have any suggestions what should I try? Do you have some similar experiences?
Thanks,
Jakub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How 'Input/Output' ports are mapped into memory? I have been trying to understand I/O ports and their mappings with the memory & I/O address space. I read about 'Memory Mapped I/O' and was wondering how this is accomplished by OS/Hardware. Does OS/Hardware uses some kind of table to map address specified in the instruction to respective port ?
A: Implementations differ in many ways. But the basic idea is that when a read or write occurs for a memory address, the microprocessor outputs the address on its bus. Hardware (called an 'address decoder') detects that the address is for a particular memory-mapped I/O device and enables that device as the target of the operation.
Typically, the OS doesn't do anything special. On some platforms, the BIOS or operating system may have to configure certain parameters for the hardware to work properly.
For example, the range may have to be set as uncacheable to prevent the caching logic from reordering operations to devices that care about the order in which things happen. (Imagine if one write tells the hardware what operation to do and another write tells the hardware to start. Reordering those could be disastrous.)
On some platforms, the operating system or BIOS may have to set certain memory-mapped I/O ranges as 'slow' by adding wait states. This is because the hardware that's the target of the operation may not be as fast as the system memory is.
Some devices may allow the operating system to choose where in memory to map the device. This is typical of newer plug-and-play devices on the PC platform.
In some devices, such as microcontrollers, this is all done entirely inside a single chip. A write to a particular address is routed in hardware to a particular port or register. This can include general-purpose I/O registers which interface to pins on the chip.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android pre-market publish (legal) questions
*
*I live in a country outside the supported countries of google to sell applications on the android market. Despite this I want to sell my apps on the market (pls don't suggest other appstores, like amazon). I thought I obtain an american IP (is that legal? there are plenty of websites selling US IP-s) and registrate as if i lived in the US. Does google accept it (they don't have to know that I am from a different country)?
What do you think?
*I also read that i have to registrate as a business when I want a google merchant account? I am a simple person who wants to sell his application. I don't own a business, or a firm. I have an active paypal account, that's all. What should I do?
*I also read that after I created the merchant account and set my country, I cannot change it later. But what if I move abroad (I am planning to)?
*If I want to create a website for my apps (it is not compulsory, right?), can I use an image of a phone? Or do I have to contact e.g. HTC for a picture that I can download from their site, or google?
Thanks
A: *
*I'm sure Google will find out. This could get you banned or maybe worse, I suggest not doing it.
*You DONT need to create a google merchant account. Yo DO need to create a google Checkout account. The checkout account is needed for google to deposit payments on. This account is then linked to your bank account and every month google will deposit your earnings on your bank account. For Google Checkout, have a look here: https://checkout.google.com/sell
*I do not know about this, sorry.
*You can always use a "generic phone image" if you want to use an image of a phone per-se, but I think you are allowed to take an image of say an HTC desire, just mention at the bottom of your page that it contains content made by HTC or somethign similar and not claim it your own. I'm not 100% sure about this though. I know there is a google site about branding here: http://www.android.com/branding.html But it doesnt say anything about phone images.
A: *
*Nope you can't do it. Google will find it out when you submit your
credit card details etc. So don't attempt it. if you don't like
other app stores then you may give a try to some third party app
brokers. They'll sell the app on your behalf on Android Market and
share the revenue with you.
*No need to have a business. there are hundreds of indivuduals selling apps on appstore so don't worry much about it. You can make your google check out merchant account if you are from accepted country.
*PayPal also having same policy. You gonna have to delete your account and re-create one. I'm not sure whether Google check out imposes such policy.
*As far as I know there wont' be much issue as you are not stealing atnything from HTC. But you can simply drop a mail to HTC customer care and see how they respond. Else you can use some generic Android Phone mock ups. If you are referring to the app screen shot only (only the LCD display) then don't worry. You are the one created it, you can use it on your will.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Adding next and previous button in Grid view I am showing a Grid view in Alert dialog. Grid view consists of images which are stored in an array.
I am showing 9 images at a time in grid view, now there are two buttons below grid view
"Next" & "Previous".
If click on "Next" it will show next 9 images from the array and similarly with "Previous". Please tell me how to proceed and if possible provide me some sample code.
I tried this code, please say if i can use any other logic..
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
imageView = new ImageView(mContext);
if(no_of_image < mThumbIds.length && no_of_image < screen_no)
{
if (convertView == null) // if it's not recycled, initialize some attributes
{
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(8, 8, 8, 8);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[no_of_image]);
no_of_image++;
}
return imageView;
screen_no is the no. of images to be shown in one grid view. in my case it is 9.
and mThumbIds is the array from where i am loading the images.
A: You have to write your own custom adapter for gridview by extending any existing adapter classes.
Now when you click on Next the you will just change the dataset of the adapter and call
notifydatasetchaged() method on adapter this will refresh gridview automatically.
But keep mind that you should change the dataset if and only if you are having next images to be shown.
This is just the overlall logic I am sharing with you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: FxCop, compose list of callers from dependent assembly I'm building a couple of customs FxCop rules and one of the rules needs to enforce that a constructor is called in specific methods. For that, I need to create a list of callers, to that specific constructor, prior to performing the actual test. How is this possible? Is there some kind of handle to acquire a list of all loaded assemblies in the ApplicationDomain, where I can iterate through the classes and find the constructor Method object? Ideally the list of callers should be composed in the BeforeAnalysis method.
A: The Microsoft.FxCop.Sdk.CallGraph.CallersFor(Method) method may give you what you want. However, the general approach you seem to be describing is rarely a good idea because it would typically assign the problems to the wrong target. For example, in the scenario you describe, it would presumably be desirable to attribute the problems to the methods that should but do not contain the target contructor call. However, if your analysis target is the constructor, the detected problems will be attributed to the constructor rather than the methods that should have called it.
A: I think I haven't explained the question very well, but I see your point.
I have 3 different assemblies and for certain method calls from one assembly to another, I need to ensure that a benchmark constructor invoked. The benchmark class resides in a 4th assembly. Now my problem was that only VS2010 only loads one target assembly for analysis and when I used the CallGraph to construct the a list of methods calling the constructur, it would not find any. When Invoking FxCopCmd.exe manually I could just add the dependent assemblies manually with the /file: parameter.
My solution is to load the different assemblies manually (not relying on the loaded assembly in RuleUtilities.AnalysisAssemblies and contruct the list of callers in the BeforeAnalysis method.
RuleUtilities.GetAssembly(
RuleUtilities.AnalysisAssemblies
.First().Directory + "\\" + additionalAssemblyFilename)
.Types.SelectMany(type => type.Members)
.Where(member => member.IsPublic)
.Where(CanBeCastedToMethod)
.Cast<Method>()
.SelectMany(CallGraph.CallersFor);
With this approach I can contruct a list of callers, for each of the assemblies and for the benchmark class constructor. Works perfectly i VS2010.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: simple jquery function doesn't work when included in wordpress? help? I'm replacing class name generated by one of the plugins with mine. I found this easier than fiddling with plugin on every upgrade. Anyways, in WP this simply doesn't do anything! When I test it on non wp (same template xhtml) it works!
what could be the conflict? I have jquery included.
$(document).ready(function(){
$(".slideright img").removeClass("ngg-singlepic").addClass("cover");
//$(".ngg-singlepic").addClass("cover");
});
A: Try this:
jQuery(document).ready(function($){
$(".slideright img").removeClass("ngg-singlepic").addClass("cover");
//$(".ngg-singlepic").addClass("cover");
});
The problem is that I think wordpress includes other libraries that conflict with the $ when used with jquery.
To get around this you need to explicitly call jQuery the first time and if you pass $ into the function then it will let you use the familiar $ within the scope of the jquery function.
Hope that helps.
A: Maybe there is some other framework included in your page. Try the following:
jQuery( function($) {
$(".slideright img").removeClass("ngg-singlepic").addClass("cover");
});
And if that does not help, you can even try to put jQuery.noConflict(); before the snippet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django 1.3 removing images Django 1.3 do not removes file which was deleted from database. I'm not found how to set Django remove deleted files. Is it possible? If so, how?
A: Simple:
Override the delete and save and method in your model. Remember that a file can both be dereferenced by the deletion of the object, but also by uploading a new file. But beware that the delete method is not called when you delete in bulk, ie. QuerySet.delete().
https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods
You can also use signals:
https://code.djangoproject.com/wiki/Signals
But beware! The reason why Django does not automatically delete the file, is that it cannot guarantee that the file is not refered to by some other application or model. But if you can guarantee that as a programmer, go ahead.
This blog article gives you the best possible info, I think:
http://haineault.com/blog/147/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I display a string as a combination of password chars and original form in asp.net Textbox control ? I have a Textbox control in which user can add/edit/delete values through this control.It only allows 10 digit numeric value. The first 5 digits should be shown as password chars and last 5 digit should be shown as its original form. (Eg: The value 1234567890 should be shown as ***67890).
How can I implement this in asp.net Textbox control?
A: Perhaps make two textboxes that appear close together. Even given the first box behaviour that when the first 5 characters are filled, that the focus is given to the seonc box.
Another way is to have one textbox and one hidden box. As the characters are typed, they go into the hidden. The hidden is rendered to the textbox where after the first 5 characters, you replace any other characters with *
A: Separate out the two textboxes like so and then combine the two (possibly into a composite control) exposing the concatenated value of the two textboxes as a property.
Markup
<div>
<asp:TextBox ID="passwordPortionTextBox" runat="server" TextMode="Password" MaxLength="5"></asp:TextBox>
<asp:TextBox ID="normalPortionTextBox" runat="server" MaxLength="5"></asp:TextBox>
</div>
Script
$(function () {
$('#<%= passwordPortionTextBox.ClientID %>').keypress(function () {
if ($(this).val().length == 4) {
$('#<%= normalPortionTextBox.ClientID %>').focus();
}
});
});
A: You cannot implement this in a single control. Use two text box controls (side-by-side) and set one as a password field and the other as a plain text field. And of course, set max length to 5 on both.
A: I think this behavior is very specific, maybe the best approach would be to create your own Textbox which derives from the asp.net Textbox Control and then add your functionality to it.
That's not so easy. :D Maybe you could work with Client side code too and look for the text changed or key stoke and change the characters to password characters, but then you have to store somewhere the original string too.
I'm not really an expert on ASP.NET but i hope my answer helps you a little bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to - Facebook Connect with existing user table I have a registration-login system on my own website yet I want to add Facebook Connect too. I have some required parts of my user table as:
Username
Password
Email
The first thing that came to my mind is, setting userId as username, userId@facebook.com as email and setting the password to null and check if a record exists with these details in my user table. If not insert a new user with these details, if exists return that user details.
Is this a good design? How should I connect facebook connect to my website?
Thank you
A: I would suggest you to take this into a more deep ASP.NET, and start an MVC project
then use the Microsoft Facebook API SDK to play around with the API, it's very easy and because they are using the new dynamic type, now that Facebook changed the Open Graph, it will continue to work great as well.
in your login page, add a facebook login button and ask for permissions, for example:
<fb:login-button perms="email" size="medium">
redirect-uri="http://yourdomain.com/FBLogin/"
Subscribe using Facebook</fb:login-button>
in your FBLogin controller, login the user using the FB credentials, if the user uses your normal form, use the normal login
If you create a custom MemberShip Provider, you can easily use that for both accesses... I write a simple start to a custom Membership provider here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implementation of Reddit,StumbleUpon,del.icio.us and Digg in iPhone app I want to know, Is it possible to integrate Reddit, StumbleUpon, del.icio.us and Digg in iPhone app? I have to implement all this in my iPhone app. Please give me the some any example link about all these points.
A: For Delicious you can use sharKit
A: Digg has a REST API clearly documented here: http://developers.digg.com/documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: objects in NSArray out of scope I have a function with populates the array and then returns it. But in the calling function, the array is not out of scope but all the objects inside it are out of scope.
(NSMutableArray *)createObjectWith:(NSString *)result
{
NSMutableArray *array =[NSMutableArray array];
for (int i=0 i<20;i++){
Wp *newWp =[[Wp alloc]init] ;
newWp.name= @"a";
[array addObject:newWp];
}
return array;
}
calling function:
data =[self createObjectWith:stringResult];
A: [NSMutableArray array]
returns an auto released array.. If you want to use that array better retain it.
data =[[self createObjectWith:stringResult] retain];
Also you must release your Wp object after adding to array
Wp *newWp =[[Wp alloc]init] ;
newWp.name= @"a";
[array addObject:newWp];
[newWp release];
btw what are you doing with variable result?
A: Finally got to know that its a prob with the debugger. Objects inside are not out of scope. But the debugger says so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: unified_thread fql table available to public or not? I see facebook removed the banner from the unified_thread documentation page (which previously stated it was for developers accounts only) but I still get the "must be a developer" error. Am I doing something wrong, or did FB just remove it by mistake?
A: My testing shows a "ERROR: Error 298 You must be a developer of the application".
I assume they removed it by mistake, because other pages, such as the Graph API Thread documentation still shows the message.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: paypal error code 15005 I'm using ubercart paypal module as a mean for credit card transaction and it's doing grate job for me. But in some of the order detail i found this type of message in admin comment box -
First : for same transaction
Authorize and capture immediately failed.
Error: 15005: This transaction cannot be processed.
Address: Nothing matched; transaction declined
CVV2: Match
Secondly : for same transaction
Authorize and capture immediately
Success: 100.00 USD
Address: Nothing matched; transaction declined
CVV2: Match
I wants to know that error code: 15005 going to hurt my client badly?
what does it mean? -
1] Address: nothing matched, transaction declined
2] Authorize and capture immediately failed
Any suggestion or advice on this issue will gonna be helpful to me.
A: Address: nothing matched, transaction declined means that the address details provided by the payer did not match those of the cardholder. It's a security check performed by pretty much every online payment facility these days.
According to the Paypal API Error Codes page error 15005 means:
The transaction was declined by the issuing bank, not PayPal. The merchant should attempt another card.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple nature for a single project in eclipse is it possible to add multiple nature to a single project in eclipse ?
eg: i want to add Python and Ruby nature to a Java project.
the purpose.
I have solutions to projecteuler.net problems in Java,Ruby,Scala,Clojure and Python.
But the solutions are in different projects.
I need them in a single project.
A: The GUI does not have any option for creating such a multilanguage projects.
However, technically, project natures can be added independently from each other. So if you manage to programmatically create the required environment, it would work. If you want to do it manually, find the .project file in the project root, and add all natures and builders to one (you can look the required elements from other projects - do a copy-paste).
This would add the project natures and builders, but not any additional configuration required - e.g. in Java projects .classpath files are used to describe the source folders, in other languages different configurations are needed.
Alltogether, if you need to do this multiple times, create a plug-in that manages this configuration for you; if you need it for a single project, think about it whether it is worth the huge effort required.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: MPIEXEC wrapper I use MPIEXEC wrapper program to execute my programs in MPICH2. After my program performed its task Break button doesn't become passive, similarly Execute button doesn't become active. Though my program reaches to the end, I have to press Break button. If I run my program directly by mpiexec command in the Windows Command Prompt, everything is ending normally.
If I don't press Break button, and If I press Ctrl+C (for example for a copy/paste process), then the MPIEXEC wrapper displays a warning "unable to forward stdin, send failed, error 10054, An existing connection was forcibly closed by the remote host." at the end of line.
What is happening?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Prevent comma-separated list of numbers being interpreted as single large value 33266500,332665100,332665200,332665300 was the original value, cell should look like this: 33266500,332665100,332665200,332665300 but what I see as the cell value in excel is 3.32665E+34
So the question is I want to convert it into the original string. I have found format function on google and I used it like these
format(3.32665E+34,"standard")
giving it as 332,6650,033,266,510,000,000,000
How to parse it or get back the orginal string? I belive format is the function in vba.
A: Excel has a 15 digit precision limit. If the numbers are already shown like this when you access the file, there is no way to get the number back - you have already lost some digits. VBA code and formulas will not help you.
If this is not the case, you can add a single quote ' mark before the number to store it as text. This will ensure Excel does not try to treat it as a number and thus lose precision.
A: If you want the value kept exactly, store the data as a string, not as a number. The data type you are using simply doesn't have the ability to do what you are asking it to do.
A: The value needs to be entered into the cell as a string. You need to make whatever it is that inserts the value preceed the value with a '.
A: If you're starting with an Excel file that has already been created then you've already lost the information: Excel has tried to understand what it was given and its best guess has turned out to be wrong. All you can do (if you can't get the source data) is go back to the creator of the Excel file and tell them what's wrong.
If you're starting with, say, a text file that you're importing, then the news is much better:
If you're importing manually using the Text Import Wizard, then at "Step 3 of 3" you need to set "Column Data Format" for the problem field to "Text".
If you're using a macro, you'll need to specify a value for the TextFileColumnDataTypes property that does the same thing. The easiest way to get it right is to use the Macro Recorder.
If you want the four values in the string to be separate cells, then again, look at the Text Import Wizard settings: in Step 1 of 3 you need to set "Delimited" data type (usually the default) and in Step 2 make sure that "Comma" is checked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: List and Linq To Sql Performance Issue I Have One Table (My Sql) with 2 millions records and one List with 100 Records. I have List Except lamda expression for finding all those Urls that is in List but Not in Table.
Now Issue is that it's taking lot of time around 5 mins. I am working in powerful VPS and code and database in same server.
Please suggest me All possible way to increase the performance of linq to sql and linq to entity.
My Code Is`return
Urls.Except(DbContext.postedurllists.Select(crawl => crawl.PostedUrl).ToList()).ToList();`
Where Urls Is List Which Contain 100 Urls And postedurllists is a table that contains 2 Millions record.
Thanks
A: You're currently pulling all of the URLs from the database. That's not a good idea. Instead, I would suggest pulling the intersection from the database by effectively passing your Urls list into the database, and doing an except based on the results:
var commonUrls = DbContext.postedurllists
.Select(c => c.PostedUrl)
.Where(url => Urls.Contains(url))
.ToList();
var separateUrls = Urls.Except(commonUrls);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7525930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.