Friday, April 20, 2012

Why I am getting Could not find multi_json-1.3.1 in any of the sources?

Hi folks I have simple Rails application.I want to deploy it in Heroku.When I run the below command



git push heroku master


The below error message is displayed.



 Could not find multi_json-1.3.1 in any of the sources
!
! Failed to install gems via Bundler.
!
! Heroku push rejected, failed to compile Ruby/rails app


Here is my Gemfile



 gem 'rails', '3.2.3'
gem 'pg'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'therubyracer', :platform => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'


Any help is appreciated.Thank you.





JavaScript to Convert Byte[] to Image in Html page [closed]

I'm creating one application to display the selected image from Windows Phone library to webpage. I have converted the choosen photo to byte[] and then string, passed to html page.



<script type="text/javascript">
function CallBack(jsonstring)
{
var bytes = [];
for (var i = 0; i < jsonstring.length; ++i)
{
bytes.push(jsonstring.charCodeAt(i));
}
var bMap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
document.getElementById('myimg').src =bMap;
}
</script>


But it is not working... getting unknown error.



Could anybody help me please!!!





How to override compiler options for referenced c++ project in visual studio

I am using visual stuido 2010.



I have a static library call "common library". This common library is referenced by many other projects. These projects use the common library by "add new reference" (in project properties -> common properties -> add new reference).



All these projects have their special compiler options/predefined macros. Common library needs to conform their settings, or the compilation fails. Is there any simple way to achieve this?



The current solution is: copy a new "common library" project file for each project, and set the options/macros in the new project file. It is very painful.





SQL Server lock issue (distributed transactions with WCF)

I'm having a problem with distributed transactions.



I'm using SQL Server 2008 R2, Windows 7, .Net 4.0.



Here's what I actually want to do:




  • I have a buffer database (named A)

  • I have another database (named B)

  • I want to send data from database A to database B through a WCF webservice (SOAP over HTTP, A and B not on the same machine)

  • If the data is successfully sent to database B, data is removed from database A



Everything is part of a transaction, so the whole operation is atomic.



Here's what I'm currently trying to do sequentially (everything in a transaction):




  1. I read a chunk from database A (say 50 rows)

  2. I update rows read in step 1 (I actually set the boolean Sent column of rows with the value true, so in the future I know that these rows are sent)

  3. I consume (client side) a WCF webservice (SOAP 1.2, wsHttpBinding) that is part of the transaction flow (blocking synchronous call). The webservice request sends the data read in step 1

  4. The webservice implementation (server side) inserts data in database B (data that is contained in the webservice request)


    • if no exception is received from the server, data with the Sent value as true are removed from database A

    • if a specific FaultException is received from the server, data with the Sent value as true are removed from database A

    • for other FaultExceptions and other exceptions (endpoint not found, or anything else), data with the Sent value as true are not removed from database A




Note: there are actually multiple buffer databases (A1, A2, A3..., AN) and multiple target databases (B1,.... BN). There are N threads to deal with N databases.



If I run my server and my client, everything is working just fine. Data is "transferred" atomically per chunks from database A to database B.
When I brutally stop my client in the middle of the transaction (process killed), most of the time everything is fine (i.e. data is not removed from database A nor added to database B).



But sometimes (this is my actual problem), my database B becomes locked. The only option to unlock it is to terminate the server process.



When the problem occurs, I can see in MSDTC that there is an active transaction (note that in the screenshot there are 3 transactions as I'm currently dealing with 3 buffer databases and 3 target databases, but sometimes there is only 1 transaction even if there are 3 DB).



enter image description here



I see that database B is locked when trying to run a SELECT againt database B. As you can see in the picture below, my SELECT request is blocked by session ID 67 which corresponds to an INSERT in database B by the server process.



enter image description here



The lock remains forever (no transaction timeout, even after 1+ hour) until the server process is terminated. I can't validate or cancel the transaction in MSDTC, I get a warning saying that "it cannot be aborted because it is not "In Doubt"".



Why does the database B remained locked? If the client is terminated, shouldn't the transaction fail and the lock on database B be released after some timeout?



Here's my code for server side:



// Service interface
[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContract(typeof(MyClass))]
[TransactionFlow(TransactionFlowOption.Allowed)]
void SendData(DataClass data);
}

// Service implementation
[ServiceBehavior()]
public partial class Service : IService
{
[OperationBehavior(TransactionScopeRequired = true)]
public void SendData(DataClass data)
{
if (data == null)
{
throw new FaultException<MyClass>(new MyClass());
}

try
{
// Inserts data in database B
using (DBContextManagement ctx = new DBContextManagement())
{
// Inserts data using Entity Framework
// This will add some entities to the context
// then call context.SaveChanges()
ctx.InsertData(data);
}
}
catch (Exception ex)
{
throw new FaultException<MyClass>(new MyClass());
}
}
}


Here's my server side configuration (self-hosted WCF service):



<system.serviceModel>
<services>
<service name="XXXX.MyService">
<endpoint binding="wsHttpBinding" bindingConfiguration="WsHttpBinding_IMyService" contract="XXXX.IMyService" />
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="WsHttpBinding_IMyService" transactionFlow="true" allowCookies="true" >
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxStringContentLength="2147483647" />
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceTimeouts transactionTimeout="00:00:20" />
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>


Here's my client code:



try
{
using (DBContextManagement ctx = new DBContextManagement())
{
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted, Timeout = new TimeSpan(0, 0, 30) }, EnterpriseServicesInteropOption.None))
{
// First of all, retrieves data from database A
// Internally queries the database A through Entity Framework
var data = ctx.GetData();

// Mark data as sent to the server
// Internally updates the database A through Entity Framework
// This actually set the Sent property as true, then call
// context.SaveChanges()
ctx.SetDataAsSent(data);

try
{
// Send data to the server
MyServiceClient proxy = new MyServiceClient();
MyServiceClient.SendData(data);

// If we're here, then data has successfully been sent
// This internally removes sent data (i.e. data with
// property Sent as true) from database A through entity framework
// (entities removed then context.SaveChanges)
ctx.RemoveSentData();
}
catch (FaultException<MyClass> soapError)
{
// SOAP exception received
// We internally remove sent data (i.e. data with
// property Sent as true) from database A through entity framework
// (entities removed then context.SaveChanges)
ctx.RemoveSentData();
}
catch (Exception ex)
{
// Some logging here
return;
}

ts.Complete();
}
}
}
catch (Exception ex)
{
// Some logging here (removed from code)
throw;
}


Here's my client configuration:



<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WsHttpBinding_IMyService"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
allowCookies="false"
bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"
transactionFlow="true"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
messageEncoding="Text"
textEncoding="utf-8"
useDefaultWebProxy="true">

<readerQuotas maxDepth="32"
maxStringContentLength="2147483647"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>

<client>
<endpoint address="http://localhost:8080/MyService.svc"
binding="wsHttpBinding"
bindingConfiguration="WsHttpBinding_IMyService"
contract="XXX.IMyService"
name="WsHttpBinding_IMyService" />
</client>

</system.serviceModel>


So my questions are:




  • Is my pattern/design with distributed transactions a valid and robust design?

  • What could cause my database B to be locked for infinite time if my client's transaction is brutally terminated?

  • What should I change (config and/or code and/or design) to make it work as expected (i.e. if my client process dies/crashes, I want the transaction to be aborted so the database B is not locked)?



Thanks.






EDIT



I do think I over-simplified my use case. It looks like I'm actually doing a simple data replication between multiple SQL Server instances. That's not well explained (my bad), that's not what I'm trying to achieve.



I'm not simply duplicating data. I read from A on machine M1 then write to B on machine M2, but what's written is not what I've read but some calculated value that comes from what was read.
I'm pretty sure SQL Server replication services could handle business computation for me, but I can't go this way for some reasons:




  • I can't change the webservices thing because the interface is now defined and fixed.

  • I can't use SQL Server replication because I'm actually not responsible of the server side (which writes to database B). I'm even not sure that there will be SQL Server on the other side (could be a Java backoffice with MySQL, PostgreSQL or anything)

  • I can't use SQL Server service broker or any message-oriented-middleware (which would fit IMO) for same reason (potentially heterogeneous databases and environments)



I'm stuck by WCF, and I can't even change the binding configuration to use MSMQ or whatever because of interoperability requirements. MSMQ is great for sure (I'm already using it in another part of the project), but it's Windows only. SOAP 1.2 is a standard protocol, and SOAP 1.2 transactions are standard too (WS-Atomic implementation).



Maybe the WCF transaction thing is not a good idea, actually.



If I have understood correctly how it actually works (please correct me if I'm wrong), it simply allows to "continue" the transaction scope on server side, which will require a transaction coordinator to be configured on server side, which probably breaks my interoperability needs (again, there could be a database on server side that does not integrate well with the transaction coordinator).





Adding ID and Class on template dynamically using backbone views

I want to add a ID and CLASS attribute to my view template.
this is what i tried but failed.



$("#login").html( _.template( LoginTemplate ) );
this.loginmodel = new LoginModel();
this.loginview = new LoginView({
el: $("#loginContainer"),
model: this.loginmodel,
className: "test"
});

<div id="loginContainer">
<div id="loginForm">
<input class="user-input formContainerInput" id="username" placeholder="Username" required="required"/>
<input class="user-input formContainerInput" id="password" type="password" placeholder="Password" required="required"/>
<a class="connection-btn" data-role="button">Connection</a>
<a class="login-btn" data-role="button">Log In</a>
</div>




I want to assign id and class using the views and not on the html itself. How will i do it?





javascript - Twitter bootstrap jquery plugins compiled for production but not understood by the browser

I'm developing a 3.1 Rails app with Twitter Bootstrap using seyhunak's gem.



On the production mode, I was able to use basic bootstrap CSS and JS through pipeline precompilation:



RAILS_ENV=production bundle exec rake assets:precompile


Using the gem file :



group :assets do
gem 'sass-rails', '~> 3.1.5'
gem 'coffee-rails', '~> 3.1.1'
gem 'uglifier', '>= 1.0.3'
gem "twitter-bootstrap-rails"
end


And the application.js file:



//= require_tree .

//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require bootstrap-tab
//= require bootstrap-modal
//= require bootstrap-dropdown
//= require bootstrap-popover


The application worked fine except for for the bootstrap plugins such as modals and dropdowns. These plugins exist as static javascript libraries existing inside the vendor assets directory:



/vendor/assets/javascripts/bootstrap-dropdown.js
...


It seems to me that these files are not being precompiled, how can I manage to do so?



Update:



I opened the precompiled application.js and found that the plugins code do exist within it! I still have no idea why the browser is not able to load them properly.





What is the maximum iframe width of a facebook page? (July 2011)

What is the maximum iframe width of a facebook page?





JDBC to SQL Server connection

I'm trying to connect to a SQLServer DB using JDBC. I'm using jre 1.6 and I've added the 'sqljdbc/jar' to my class path on my OS. I've also added that jar far to my build path. When my code hits this line
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
it explodes. I can navigate to the class in the package explorer, I can also type out the namespace and eclipse intellisense picks it up as well, yet when it loads I get
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver.
I'm using Eclipse Indigo Release 2 w/ Spring STS plugin, can any one tell me whats going on? btw: I can connect to my db using the DB using DB Explorer in Eclipse.





Are there problems with implementing a listener in a View subclass?

I need to subclass TextView to have it hold some additional data for me. I'm placing these new View objects into a ListView using a custom ListAdapter.



I have an action I want to perform onClick(), and it is the same action for all elements of the ListView, based on the additional data.



Would this definition, have any downsides or cause any problems?



public class UserTextView extends TextView implements OnClickListener {

public int userId;

public UserTextView(Context context) {
super(context);

this.setClickable(true);
this.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

}

}


I would expect that the code in my onClick() implementation wouldn't actually be copied, but would only exist once in memory and be called with the specific UserTextView's data. So I don't expect extra memory usage. And in fact, not having an extra Class and Object (anonymous or not) might improve performance (though not in a real, meaningful way).



If needed, the setOnClickListener() method could be invoked to change the Listener if I needed different behavior for a specific object.



It just seems to fit well into what I need:




  1. A TextView that can hold extra data (userId)

  2. A TextView class that will have the same default behavior

  3. Can be created and managed easily by a ListAdapter



I just feel that I have never seen this done this way, and am suspicious that there is something I'm missing.





Limit to number of "named ranges" in Range method

I am using the following code:



Dim rng As Range

Set rng = Workbooks("import sheet.xls").Sheets("import").Range("project_name,project_author,project_code,project_breaker,default_fault_ac_mcb,default_fault_ac_mccb,default_fault_dc,default_fault_acb,default_rvdrop,default_svdrop,default_eff,default_pfactor,default_ratio,default_freq,default_sfactor_ac,default_spfactor")

For Each cell In rng.Cells
MsgBox cell
Next cell


Now project_name,project_author are different named ranges in the sheet,the problem is when i add another named range to the above list (already defined) i get a runtime error 1004 (select method of range class failed)



Is there a limit to the number of named ranges u can add to range object ?





Android: How to Remove Selected Tab Highlight Color & On Press Highlight on TabWidget

I am now working with Android TabWidget.
I build this TabWidget based on http://mobileorchard.com/android-app-development-tabbed-activities/

I've already add background to the TabWidget,

but apparently the highlight of selected tab and pressed tab is always visible and I cant turn it off yet.



Here is the picture (sorry cant directly add image because still a newb). :

1. default selected tab : http://postimage.org/image/9ryed6w5b/

2. on pressed tab : http://postimage.org/image/gwg7m83en/



What I want is the default selected tab color and on pressed tab color to be invisible or turned off, so the image background will fully shown, not blocked by those colors.



Any response will be appreciated. Thank you :)



the code:



public void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(EpolicyMainActivity.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(EpolicyMainActivity.this, true);

super.onCreate(savedInstanceState);
setContentView(R.layout.epolicy);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
tabHost.getTabWidget().setBackgroundColor(0);
tabHost.getTabWidget().setBackgroundResource(R.drawable.epolicy_menu_bar);

TabSpec spec1=tabHost.newTabSpec("Tab 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("",getResources().getDrawable(R.drawable.epolicy_menu_home));

TabSpec spec2=tabHost.newTabSpec("Tab 2");
spec2.setContent(R.id.tab2);
spec2.setIndicator("",getResources().getDrawable(R.drawable.epolicy_menu_nab));

TabSpec spec3=tabHost.newTabSpec("Tab 3");
spec3.setContent(R.id.tab3);
spec3.setIndicator("",getResources().getDrawable(R.drawable.epolicy_menu_contact));

TabSpec spec4=tabHost.newTabSpec("Tab 4");
spec4.setContent(R.id.tab4);
spec4.setIndicator("",getResources().getDrawable(R.drawable.epolicy_menu_agen));




How to split a bitmap by a line

I'm working on a project for android devices. I want to split a bitmap by a line into 2 bitmaps. How do I do. Please help!





Windows 8 Metro Style Apps : Lambda expressions

Are the lambda expressions supported while developing Metro Style Apps using C#/XAML ?
I've tried to define a delegate via lambda expression and got whole bunch of syntax errors.
WHY ? What about anonymous methods ?





Difference between "fuzz testing" and "monkey test"

I have recently been thinking of the difference between fuzz testing and monkey test. According to wiki, it seems monkey test is "only" a unit test and fuzz test isn't. Android has UI/Application Exerciser monkey and it doesn't seems like unit test.



Is there any difference between these testing methods?





jQuery - How to position, resize and move one image over another

What I'm trying to achieve is: position one image over another and be able to move it within the region of the containing image, also to be able to resize the top image, by keeping its ratio. Then I need to know the size (w, h) and position (x, y) of the top image within the containing image container.



What I want is actually something like jCrop, but the highlight region to be a png image, and not a semitransparent rectangle.





Gettext on php/iis/win7, wrong charset

I am refactoring some old app in php 5.2.17 and converting it to UTF-8 charset. App uses gettext, but for some reason, gettext returns data in cp1250 (on win7 witch czech national environment) even if all texts are now UTF-8 and catalog texts too. I did try to create one brand new in UTF-8 from beginning, restarting IIS7.5, but still getting wrong charset (not UTF-8 but cp1250). (I am new in win7, on new pc, maybe it is in some php config, mbstring and iconv has set UTF-8 as internal encoding)



Edit:
This is header of my .po file.I generating .mo every time again:



"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
"X-Poedit-Basepath: ../../../\n"
"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
"X-Poedit-Language: Czech\n"
"X-Poedit-Country: CZECH REPUBLIC\n"
"X-Poedit-SourceCharset: utf-8\n"
"X-Poedit-SearchPath-0: .\n"


All codes and html header is now utf-8. What about any IIS chache? But restart of IIS hase no efect.



Do you have any idea what can be wrong?
Thank you for answer.





Runnign an application as an Administrator without prompting for elevation

I'm installing my app using Innosetup, to launch when then user logs in using SOFTWARE\Microsoft\Windows\CurrentVersion\Run. How can I start the app as if I've right-clicked and selected Run as Administrator, without the UAC prompt?





loading div with jquery mobile

I have a problem when loading in content with



$('#next').click(function(){
$('#boundary').load('options.html #pagecontent').page();


});


The problem is the #pagecontent div residing in options.html loads in but not in intended jquery mobile elements.



the in options.html with id=page content renders fine if you preview that page. its only when i load try and load it into another page div with id="boundary" that all the jquery mobile rendering fails, and the elements instead just load in as native html elements.



in the options.html: a standard div holding some ui elements.



<div id="pagecontent">
// Jquery mobile button
<a href="results.php" data-transition="fade" id="result" data-role="button" data-theme="e" rel="external">View results</a>
</div>


Thanks





HTTP POST on Android

I want to make a simple HTTPRequest to a php script and I have tried to make the very most basic of apps to get the functionality working. I want to test that my app is sending the data I feed it so I've made the android app send to a server and that server is supposed to send me the data I've put into the app. The code for the "postData" function is to send data from android to the server and the code for the "default.php" is the recieving php file on a webserver which then forwards the data to my email address (not given). Here is the code



    public void postData() {

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://somewhere.net/default.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("thename", "Steve"));
nameValuePairs.add(new BasicNameValuePair("theage", "24"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);

// Execute HTTP Post Request
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);

//Just display the response back
displayToastMessage(responseBody);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}


as well as for "default.php"



<?php 
$thename=$_GET["thename"];
$theage=$_GET["theage"];

$to = "someemail@gmail.com";
$subject = "Android";
$body = "Hi,\n\nHow are you," . $thename . "?\n\nAt " . $theage . " you are getting old.";
if (mail($to, $subject, $body))
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>


Here are the links to the code in pastebin:
postData() and default.php



I recieve an email however the data sent "thename" and "theage" seem to be empty. The exact email received is
"Hi,
How are you,?
At you are getting old."
which indicates to me that the server is sending thename and theage as empty. Have any of you tried this before? What am I doing incorrectly?
Thank you so much for taking the time out to read my code and if possible to reply to my questions.





Converting iPhone code to Android

I put up a problem on Android and didn't get any answer but I've found a similar problem on the iPhone platform with the answer but I don't know how to translate this into Java code. Please can anyone who is well versed in both languages give this a try.



NSString* userAgent = @"Mozilla/5.0";

NSURL *url = [NSURL URLWithString:[@"http://www.translate.google.com/translate_tts?tl=el&q=????????"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];

[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];


[data writeToFile:@"/var/tmp/tts.mp3" atomically:YES];




how to go to "/var/mobile/Applications/some value/Documents" folder iPhone

i want to check my saved files in the path "/var/mobile/Applications/somevalue/Documents" of my iphone device.



can anyone tell how can i go to that path...



i need to test this path to see whether my file is saved in the path are not, i can't check through iPhone simulator because i am using MPMusicPlayer, so i can't play and save the song using simulator





mysql update all columns which has value say 'ram'

I have many columns in a table which needs to be checked against some value and values needs to be replaced if match found..



So basically I am looking for a query which takes column name as sort of variable and loops through the table and updates the column value if matched..



I could do that with php, having as many quries as columns..But thats wat i dont want..





How to convert CMYK eps to CMYK jpeg with ghostscript?

Ghostscript changes colospace to RGB when converting CMYK eps to jpeg.The problem is to keep colorspace untouched during conversion. Thanx in advance.





copy existing database on SD card

when i am running android application it store database directly in internal memory of emulator but application(.apk file) store in external storage.i am using 230 mb database ..i done following setting also



<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<manifest android:installLocation="preferExternal" >


in androidmainfest.xml file



public void copyDatabase() throws IOException 
{
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
Toast.makeText(mycontext,"External Sd card not mounted", Toast.LENGTH_LONG).show();
}
try
{
InputStream in=mycontext.getAssets().open("Demo.db");
File outFile =new File(Environment.getExternalStorageDirectory()+File.separator+ "Demo.db);
outFile.createNewFile();
OutputStream out= new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf))> 0)
{
out.write(buf,0,len);
}
out.close();
in.close();
Log.i("copyDatabase","Database Has been transferred");

}
catch(IOException e)
{
Log.i("CopyDatabase","could not copy database");
}

}
public boolean checkDatabase()
{
SQLiteDatabase checkdb=null;
try
{
String myPath="/sdcard/demo.db";
checkdb=SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

Log.i("checkDatabase database path",checkdb.getPath());
}
catch(SQLiteException e)
{
Log.e("Database doesn`t exist",e.toString());
}
if(checkdb!=null)
{
checkdb.close();
}
return checkdb != null ? true : false;


}
public void openDatabase() throws SQLException
{
String myPath="/sdcard/demo.db"
myDatabase=SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}


I am getting this error INSTALL_FAILED_DEXOPT





Can I implement ScrollToHorizontalOffset() functionality in XAML? (for a dynamic list)

Here's the problem: I have a data-bound list of items, basically a way for users to map a request to a response. The response is an xml-based file. I'm letting them queue these up, so I've used a combobox for responses. The responses will include the full path, so they get a bit long. I want the displayed text of the combobox to be right-justified so the user can see the file name. For my static controls, I just use ScrollToHorizontalOffset() when a file is loaded and I'm done. For this dynamic list, I'd like to do it in xaml.



The "somewhat ugly" solution would be to store all the ComboBox objects as they load... then I can call ScrollToHorizontalOffset() directly, but I'd really prefer to do it a cleaner way than that! EDIT: (Actually, this may not be reasonable. A quick look at trying to hack around this issue gets into some really awkward situations trying to map my datasource items to the controls)



I've tried HorizontalContentAlignment, that only impacts the "dropped-down" portion of the ComboBox.



I've also tried to hook other various loading events, but haven't found one that works.





Enterprise Library SqlCacheDependency

I am working with Enterprise Library Application Block in my application and need to use SqlCacheDependency, but Caching block does not have SqlDependency Expiration available, Tried to search, found a post with broken link (david hyden), there must be some way to use sql notification in it.





Apache restrict access unless from localhost

The below code is in .htaccess file in /home/cuddle/test/



AuthUserFile "/home/cuddle/.htpasswds/test/passwd"
AuthType Basic
AuthName "Secure Area"
Require valid-user


This works fine, it will prompt for username & password, however when I add another rule to allow internal requests:



Allow from 127.0.0.1
Satisfy Any


It no longer prompts for password for outside users (non localhost) and seems to let all users through, no matter if they validate or what IP they are from. There are no other permissions/allow/deny present within .htaccess





DIV element not being pushed down by content inside it

I have a div which is not being pushed down by the content inside it. Instead the content just overlaps the div. I assume this is because there's a PHP while loop between the div tags? How do I fix this?



<?php 
session_start();
if (!$_SESSION["user_name"])
{
header("Location: index.php");
}
include('header.php');
$id = $_GET['id'];
if(isset($id)) {
connect_to_db();
mysql_query("DELETE FROM content WHERE id='$id'");
$deleted = 'Content Successfully Deleted.<br>';
}
echo '<div id="content">';
echo '<h2>Delete Content</h2>';
if(isset($deleted)){
echo $deleted;
}
connect_to_db();
$query="SELECT id, date, title, image FROM content ORDER BY date DESC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){
echo '<div id="delete" align="center">';
echo '<a href="delete.php?id='.$row['id'].'"><img src="'.$row['image'].'" style="border:1px solid black; width:100px;"><br>Delete</a>';
echo '</div>';
}
echo '</div>';
?>




How to refer to Embedded Resources from XAML?

I have several images that i want to be Embedded into the exe.



When i set the Build Action to Embedded Resource
I get through out the code an error that the Resource isn't available and asking me to set the Build Action to Resource



I Tried several different methods :



 <ImageSource x:Key="Image_Background">YearBook;component/Resources/Images/darkaurora.png</ImageSource>

<ImageSource x:Key="Image_Background">Images/darkaurora.png</ImageSource>

<ImageSource x:Key="Image_Background">pack://application:,,,/Resources/Images/darkaurora.png</ImageSource>


This code sits in a Resource file.
But none worked, they all throw this error :



Cannot convert the string 'pack://application:,,,/Resources/Images/darkaurora.png' into a 'System.Windows.Media.ImageSource' object. Cannot locate resource 'resources/images/darkaurora.png'.  Error at object 'Image_Background' in markup file 'YearBook;component/Resources/ImageResources.xaml' Line 4 Position 6.


And in different places in code i get :



the file 'YearBook;component/Resources/Images/shadowdrop.png' is not a part of the project or its 'Build Action' property is not set to 'Resource'


So, What am i doing wrong?





How to download audio/video files from internet and store in iPhone app?

I am developing an iPhone app for music. I want to give some options to the user so they can listen the song/music by streaming or they can download the music in the app. I know how to stream the audio files in the app programmatically. But, i don't know how to download the audio files in the app and play the audio after download. And also user can pause the download while it is in download. Is it possible to do ? Can anyone please guide me and please share any sample code or tutorial for me? I have one more doubt: Can you please help me to create a folder inside of the app? Please help me. Thanks in advance.