Search Results

Search found 417 results on 17 pages for 'sb chatterjee'.

Page 11/17 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • F# - Facebook Hacker Cup - Double Squares

    - by Jacob
    I'm working on strengthening my F#-fu and decided to tackle the Facebook Hacker Cup Double Squares problem. I'm having some problems with the run-time and was wondering if anyone could help me figure out why it is so much slower than my C# equivalent. There's a good description from another post; Source: Facebook Hacker Cup Qualification Round 2011 A double-square number is an integer X which can be expressed as the sum of two perfect squares. For example, 10 is a double-square because 10 = 3^2 + 1^2. Given X, how can we determine the number of ways in which it can be written as the sum of two squares? For example, 10 can only be written as 3^2 + 1^2 (we don't count 1^2 + 3^2 as being different). On the other hand, 25 can be written as 5^2 + 0^2 or as 4^2 + 3^2. You need to solve this problem for 0 = X = 2,147,483,647. Examples: 10 = 1 25 = 2 3 = 0 0 = 1 1 = 1 My basic strategy (which I'm open to critique on) is to; Create a dictionary (for memoize) of the input numbers initialzed to 0 Get the largest number (LN) and pass it to count/memo function Get the LN square root as int Calculate squares for all numbers 0 to LN and store in dict Sum squares for non repeat combinations of numbers from 0 to LN If sum is in memo dict, add 1 to memo Finally, output the counts of the original numbers. Here is the F# code (See code changes at bottom) I've written that I believe corresponds to this strategy (Runtime: ~8:10); open System open System.Collections.Generic open System.IO /// Get a sequence of values let rec range min max = seq { for num in [min .. max] do yield num } /// Get a sequence starting from 0 and going to max let rec zeroRange max = range 0 max /// Find the maximum number in a list with a starting accumulator (acc) let rec maxNum acc = function | [] -> acc | p::tail when p > acc -> maxNum p tail | p::tail -> maxNum acc tail /// A helper for finding max that sets the accumulator to 0 let rec findMax nums = maxNum 0 nums /// Build a collection of combinations; ie [1,2,3] = (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) let rec combos range = seq { let count = ref 0 for inner in range do for outer in Seq.skip !count range do yield (inner, outer) count := !count + 1 } let rec squares nums = let dict = new Dictionary<int, int>() for s in nums do dict.[s] <- (s * s) dict /// Counts the number of possible double squares for a given number and keeps track of other counts that are provided in the memo dict. let rec countDoubleSquares (num: int) (memo: Dictionary<int, int>) = // The highest relevent square is the square root because it squared plus 0 squared is the top most possibility let maxSquare = System.Math.Sqrt((float)num) // Our relevant squares are 0 to the highest possible square; note the cast to int which shouldn't hurt. let relSquares = range 0 ((int)maxSquare) // calculate the squares up front; let calcSquares = squares relSquares // Build up our square combinations; ie [1,2,3] = (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) for (sq1, sq2) in combos relSquares do let v = calcSquares.[sq1] + calcSquares.[sq2] // Memoize our relevant results if memo.ContainsKey(v) then memo.[v] <- memo.[v] + 1 // return our count for the num passed in memo.[num] // Read our numbers from file. //let lines = File.ReadAllLines("test2.txt") //let nums = [ for line in Seq.skip 1 lines -> Int32.Parse(line) ] // Optionally, read them from straight array let nums = [1740798996; 1257431873; 2147483643; 602519112; 858320077; 1048039120; 415485223; 874566596; 1022907856; 65; 421330820; 1041493518; 5; 1328649093; 1941554117; 4225; 2082925; 0; 1; 3] // Initialize our memoize dictionary let memo = new Dictionary<int, int>() for num in nums do memo.[num] <- 0 // Get the largest number in our set, all other numbers will be memoized along the way let maxN = findMax nums // Do the memoize let maxCount = countDoubleSquares maxN memo // Output our results. for num in nums do printfn "%i" memo.[num] // Have a little pause for when we debug let line = Console.Read() And here is my version in C# (Runtime: ~1:40: using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace FBHack_DoubleSquares { public class TestInput { public int NumCases { get; set; } public List<int> Nums { get; set; } public TestInput() { Nums = new List<int>(); } public int MaxNum() { return Nums.Max(); } } class Program { static void Main(string[] args) { // Read input from file. //TestInput input = ReadTestInput("live.txt"); // As example, load straight. TestInput input = new TestInput { NumCases = 20, Nums = new List<int> { 1740798996, 1257431873, 2147483643, 602519112, 858320077, 1048039120, 415485223, 874566596, 1022907856, 65, 421330820, 1041493518, 5, 1328649093, 1941554117, 4225, 2082925, 0, 1, 3, } }; var maxNum = input.MaxNum(); Dictionary<int, int> memo = new Dictionary<int, int>(); foreach (var num in input.Nums) { if (!memo.ContainsKey(num)) memo.Add(num, 0); } DoMemoize(maxNum, memo); StringBuilder sb = new StringBuilder(); foreach (var num in input.Nums) { //Console.WriteLine(memo[num]); sb.AppendLine(memo[num].ToString()); } Console.Write(sb.ToString()); var blah = Console.Read(); //File.WriteAllText("out.txt", sb.ToString()); } private static int DoMemoize(int num, Dictionary<int, int> memo) { var highSquare = (int)Math.Floor(Math.Sqrt(num)); var squares = CreateSquareLookup(highSquare); var relSquares = squares.Keys.ToList(); Debug.WriteLine("Starting - " + num.ToString()); Debug.WriteLine("RelSquares.Count = {0}", relSquares.Count); int sum = 0; var index = 0; foreach (var square in relSquares) { foreach (var inner in relSquares.Skip(index)) { sum = squares[square] + squares[inner]; if (memo.ContainsKey(sum)) memo[sum]++; } index++; } if (memo.ContainsKey(num)) return memo[num]; return 0; } private static TestInput ReadTestInput(string fileName) { var lines = File.ReadAllLines(fileName); var input = new TestInput(); input.NumCases = int.Parse(lines[0]); foreach (var lin in lines.Skip(1)) { input.Nums.Add(int.Parse(lin)); } return input; } public static Dictionary<int, int> CreateSquareLookup(int maxNum) { var dict = new Dictionary<int, int>(); int square; foreach (var num in Enumerable.Range(0, maxNum)) { square = num * num; dict[num] = square; } return dict; } } } Thanks for taking a look. UPDATE Changing the combos function slightly will result in a pretty big performance boost (from 8 min to 3:45): /// Old and Busted... let rec combosOld range = seq { let rangeCache = Seq.cache range let count = ref 0 for inner in rangeCache do for outer in Seq.skip !count rangeCache do yield (inner, outer) count := !count + 1 } /// The New Hotness... let rec combos maxNum = seq { for i in 0..maxNum do for j in i..maxNum do yield i,j }

    Read the article

  • ArchBeat Link-o-Rama for October 17, 2013

    - by OTN ArchBeat
    Oracle Author Podcast: Danny Coward on "Java WebSocket Programming" In this Oracle Author Podcast Roger Brinkley talks with Java architect Danny Coward about his new book, Java WebSocket Programming, now available from Oracle Press. Webcast: Why Choose Oracle Linux for your Oracle Database 12c Deployments Sumanta Chatterjee, VP Database Engineering for Oracle discusses advantages of choosing Oracle Linux for Oracle Database, including key optimizations and features, and talks about tools to simplify and speed deployment of Oracle Database on Linux, including Oracle VM Templates, Oracle Validated Configurations, and pre-install RPM. Oracle BI Apps 11.1.1.7.1 – GoldenGate Integration - Part 1: Introduction | Michael Rainey Michael Rainey launches a series of posts that guide you through "the architecture and setup for using GoldenGate with OBIA 11.1.1.7.1." Should your team use a framework? | Sten Vesterli "Some developers have an aversion to frameworks, feeling that it will be faster to just write everything themselves," observes Oracle ACE Director Sten Vesterli. He explains why that's a very bad idea in this short post. Free Poster: Adaptive Case Management in Practice Thanks to Masons of SOA member Danilo Schmiedel for providing a hi-res copy of the Adaptive Case Management poster, now available for download from the OTN ArchBeat Blog. Oracle Internal Testing Overview: Understanding How Rigorous Oracle Testing Saves Time and Effort During Deployment Want to understand Oracle Engineering's internal product testing methodology? This white paper takes you behind the curtain. Thought for the Day "If I see an ending, I can work backward." — Arthur Miller, American playwright (October 17, 1915 – February 10, 2005) Source: brainyquote.com

    Read the article

  • DataTable ReadXmlSchema and ReadXml Resulting in error

    - by MasterMax1313
    I'm having some trouble with the ReadXmlSchema and ReadXml methods for a DataTable. I'm getting the error "DataTable does not support schema inference from Xml". Code Snippet: I've tried Table.ReadXmlSchema(new StringReader(File.ReadAllText(XsdFilePath))); Table.ReadXml(new StringReader(File.ReadAllText(XmlFilePath))); And Table.ReadXmlSchema(XsdFilePath); Table.ReadXml(XmlFilePath); Xml Snippet: <ScreenSets> <ScreenSet id="Credit 1"> <Screen xmlFile="sb-credit1.en.xml" tabText="Recommendation" isCached="false"> <Buttons> <Button id="btnClosePresentation"/> </Buttons> </Screen> </ScreenSet> <ScreenSet id="Credit 2"> <Screen xmlFile="sb-credit2.en.xml" tabText="Recommendation" isCached="false"> <Buttons> <Button id="btnClosePresentation"/> </Buttons> </Screen> </ScreenSet> <ScreenSet id="Credit 3"> <Screen xmlFile="sb-credit3.en.xml" tabText="Recommendation" isCached="false"> <Buttons> <Button id="btnClosePresentation"/> </Buttons> </Screen> </ScreenSet> </ScreenSets> Xsd: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="ScreenSets"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="ScreenSet"> <xs:complexType> <xs:sequence> <xs:element name="Screen"> <xs:complexType> <xs:sequence> <xs:element name="Buttons"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="Button"> <xs:complexType> <xs:attribute name="id" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="xmlFile" type="xs:string" use="required" /> <xs:attribute name="tabText" type="xs:string" use="required" /> <xs:attribute name="isCached" type="xs:boolean" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

    Read the article

  • Unable to start ServiceIntent android

    - by Mj1992
    I don't know why my service class is not working although it was working fine before. I've the following service class. public class MyIntentService extends IntentService { private static PowerManager.WakeLock sWakeLock; private static final Object LOCK = MyIntentService.class; public MyIntentService() { super("MuazzamService"); } @Override protected void onHandleIntent(Intent intent) { try { String action = intent.getAction(); <-- breakpoint if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) <-- passes by { handleRegistration(intent); } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) { handleMessage(intent); } } finally { synchronized(LOCK) { sWakeLock.release(); } } } private void handleRegistration(Intent intent) { try { String registrationId = intent.getStringExtra("registration_id"); String error = intent.getStringExtra("error"); String unregistered = intent.getStringExtra("unregistered"); if (registrationId != null) { this.SendRegistrationIDViaHttp(registrationId); Log.i("Regid",registrationId); } if (unregistered != null) {} if (error != null) { if ("SERVICE_NOT_AVAILABLE".equals(error)) { Log.e("ServiceNoAvail",error); } else { Log.i("Error In Recieveing regid", "Received error: " + error); } } } catch(Exception e) { Log.e("ErrorHai(MIS0)",e.toString()); e.printStackTrace(); } } private void SendRegistrationIDViaHttp(String regID) { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("http://10.116.27.107/php/GCM/AndroidRequest.php?registrationID="+regID+"&[email protected]"); //test purposes k liye muazzam HttpResponse response = httpclient.execute(httpget); HttpEntity entity=response.getEntity(); if(entity!=null) { InputStream inputStream=entity.getContent(); String result= convertStreamToString(inputStream); Log.i("finalAnswer",result); // Toast.makeText(getApplicationContext(),regID, Toast.LENGTH_LONG).show(); } } catch (ClientProtocolException e) { Log.e("errorhai",e.getMessage()); e.printStackTrace(); } catch (IOException e) { Log.e("errorhai",e.getMessage()); e.printStackTrace(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { Log.e("ErrorHai(MIS)",e.toString()); e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { Log.e("ErrorHai(MIS2)",e.toString()); e.printStackTrace(); } } return sb.toString(); } private void handleMessage(Intent intent) { try { String score = intent.getStringExtra("score"); String time = intent.getStringExtra("time"); Toast.makeText(getApplicationContext(), "hjhhjjhjhjh", Toast.LENGTH_LONG).show(); Log.e("GetExtraScore",score.toString()); Log.e("GetExtratime",time.toString()); } catch(NullPointerException e) { Log.e("je bat",e.getMessage()); } } static void runIntentInService(Context context,Intent intent){ synchronized(LOCK) { if (sWakeLock == null) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock"); } } sWakeLock.acquire(); intent.setClassName(context, MyIntentService.class.getName()); context.startService(intent); } } and here's how I am calling the service as mentioned in the android docs. Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER"); registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); registrationIntent.putExtra("sender",Sender_ID); startService(registrationIntent); I've declared the service in the manifest file inside the application tag. <service android:name="com.pack.gcm.MyIntentService" android:enabled="true"/> I placed a breakpoint in my IntentService class but it never goes there.But if I declare my registrationIntent like this Intent registrationIntent = new Intent(getApplicationContext(),com.pack.gcm.MyIntentService); It works and goes to the breakpoint I've placed but intent.getAction() contains null and hence it doesn't go into the if condition placed after those lines. It says 07-08 02:10:03.755: W/ActivityManager(60): Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTER (has extras) }: not found in the logcat.

    Read the article

  • Generating .coverage file programmatic way with Visual Studio 2010

    - by prosseek
    I need to generate .coverage file programmatic way. This post explains a C# code to do it as follows. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Microsoft.VisualStudio.Coverage; using Microsoft.VisualStudio.Coverage.Analysis; // You must add a reference to Microsoft.VisualStudio.Coverage.Monitor.dll namespace Microsoft.VisualStudio { class DumpProgram { static void Main(string[] args) { Process p = new Process(); StringBuilder sb = new StringBuilder("/COVERAGE "); sb.Append("hello.exe"); p.StartInfo.FileName = "vsinstr.exe"; p.StartInfo.Arguments = sb.ToString(); p.Start(); p.WaitForExit(); // TODO: Look at return code – 0 for success // A guid is used to keep track of the run Guid myrunguid = Guid.NewGuid(); Monitor m = new Monitor(); m.StartRunCoverage(myrunguid, "hello.coverage"); // Complete the run m.FinishRunCoverage(myrunguid); Unfortunately, when I compile this code, I get the following error. bin2xml.cs(26,22): error CS0246: The type or namespace name 'Monitor' could not be found (are you missing a using directive or an assembly reference?) bin2xml.cs(26,38): error CS0246: The type or namespace name 'Monitor' could not be found (are you missing a using directive or an assembly reference?) As this post says, there are some changes between VS2008 and VS2010, I think the Monitor class is in some different namespace. What might be wrong? How can I generate the .coverage file programmatically with Visual Studio 2010? ADDED I added using System.Threading to run to get the following error. I run the command csc bin2xml.cs /r:Microsoft.VisualStudio.Coverage.Analysis.dll. bin2xml.cs(28,21): error CS0723: Cannot declare a variable of static type 'System.Threading.Monitor' bin2xml.cs(28,33): error CS0712: Cannot create an instance of the static class 'System.Threading.Monitor' bin2xml.cs(29,23): error CS1061: 'System.Threading.Monitor' does not contain a definition for 'StartRunCoverage' and no extension method 'StartRunCoverage' accepting a first argument of type 'System.Threading.Monitor' could be found (are you missing a using directive or an assembly reference?) bin2xml.cs(31,23): error CS1061: 'System.Threading.Monitor' does not contain a definition for 'FinishRunCoverage' and no extension method 'FinishRunCoverage' accepting a first argument of type 'System.Threading.Monitor' could be found (are you missing a using directive or an assembly reference?) ADDED2 I compiled the code with the following command. csc bin2xml.cs /r:Microsoft.VisualStudio.Coverage.Analysis.dll /r:Microsoft.VisualStudio.Coverage.Monitor.dll Then, I got these error messages. Monitor m = new Monitor(); is at the line 27. bin2xml.cs(27,21): error CS0246: The type or namespace name 'Monitor' could not be found (are you missing a using directive or an assembly reference?) bin2xml.cs(27,37): error CS0246: The type or namespace name 'Monitor' could not be found (are you missing a using directive or an assembly reference?)

    Read the article

  • javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context. Unable to find [comp] error with java scheduler

    - by Morgan Azhari
    What I'm trying to do is to update my database after a period of time. So I'm using java scheduler and connection pooling. I don't know why but my code only working once. It will print: init success success javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context. Unable to find [comp]. at org.apache.naming.NamingContext.lookup(NamingContext.java:820) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:158) at javax.naming.InitialContext.lookup(InitialContext.java:411) at test.Pool.main(Pool.java:25) ---> line 25 is Context envContext = (Context)initialContext.lookup("java:/comp/env"); I don't know why it only works once. I already test it if I didn't running it without java scheduler and it works fine. No error whatsoerver. Don't know why i get this error if I running it using scheduler. Hope someone can help me. My connection pooling code: public class Pool { public DataSource main() { try { InitialContext initialContext = new InitialContext(); Context envContext = (Context)initialContext.lookup("java:/comp/env"); DataSource datasource = new DataSource(); datasource = (DataSource)envContext.lookup("jdbc/test"); return datasource; } catch (Exception ex) { ex.printStackTrace(); } return null; } } my web.xml: <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <listener> <listener-class> package.test.Pool</listener-class> </listener> <resource-ref> <description>DB Connection Pooling</description> <res-ref-name>jdbc/test</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> Context.xml: <?xml version="1.0" encoding="UTF-8"?> <Context path="/project" reloadable="true"> <Resource auth="Container" defaultReadOnly="false" driverClassName="com.mysql.jdbc.Driver" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" initialSize="0" jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" jmxEnabled="true" logAbandoned="true" maxActive="300" maxIdle="50" maxWait="10000" minEvictableIdleTimeMillis="300000" minIdle="30" name="jdbc/test" password="test" removeAbandoned="true" removeAbandonedTimeout="60" testOnBorrow="true" testOnReturn="false" testWhileIdle="true" timeBetweenEvictionRunsMillis="30000" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/database?noAccessToProcedureBodies=true" username="root" validationInterval="30000" validationQuery="SELECT 1"/> </Context> my java scheduler public class Scheduler extends HttpServlet{ public void init() throws ServletException { System.out.println("init success"); try{ Scheduling_test test = new Scheduling_test(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(100); ScheduledFuture future = executor.scheduleWithFixedDelay(test, 1, 60 ,TimeUnit.SECONDS); }catch(Exception e){ e.printStackTrace(); } } } Schedule_test public class Scheduling_test extends Thread implements Runnable{ public void run(){ Updating updating = new Updating(); updating.run(); } } updating public class Updating{ public void run(){ ResultSet rs = null; PreparedStatement p = null; StringBuilder sb = new StringBuilder(); Pool pool = new Pool(); Connection con = null; DataSource datasource = null; try{ datasource = pool.main(); con=datasource.getConnection(); sb.append("SELECT * FROM database"); p = con.prepareStatement(sb.toString()); rs = p.executeQuery(); rs.close(); con.close(); p.close(); datasource.close(); System.out.println("success"); }catch (Exception e){ e.printStackTrace(); } }

    Read the article

  • mysql db connection

    - by Dragster
    hi there i have been searching the web for a connection between my android simulator and a mysql db. I've fount that you can't connect directly but via a webserver. The webserver wil handle my request from my android. I fount the following code on www.helloandroid.com But i don't understand. If i run this code on the simulator nothing happens. The screen stays black. Where does Log.i land. In the android screen or in the error log or somewhere else? Can somebody help me with this code? package app.android.ticket; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class fetchData extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //call the method to run the data retreival getServerData(); } public static final String KEY_121 = "http://www.jorisdek.nl/android/getAllPeopleBornAfter.php"; public fetchData() { Log.e("fetchData", "Initialized ServerLink "); } private void getServerData() { InputStream is = null; String result = ""; //the year data to send ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("year","1980")); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(KEY_121); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","id: "+json_data.getInt("id")+ ", name: "+json_data.getString("name")+ ", sex: "+json_data.getInt("sex")+ ", birthyear: "+json_data.getInt("birthyear") ); } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } } }

    Read the article

  • How to manipulate data after its retrieved via remote database

    - by bMon
    So I've used code examples from all over the net and got my app to accurately call a .php file on my server, retrieve the JSON data, then parse the data, and print it. The problem is that its just printing to the screen for sake of the tutorial I was following, but now I need to use that data in other places and need help figuring out that process. The ultimate goal is to return my db query with map coordinates, then plot them on a google map. I have another app in which I manually plot points on a map, so I'll be integrating this app with that once I can get my head around how to correctly manipulate the data returned. public class Remote extends Activity { /** Called when the activity is first created. */ TextView txt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create a crude view - this should really be set via the layout resources // but since its an example saves declaring them in the XML. LinearLayout rootLayout = new LinearLayout(getApplicationContext()); txt = new TextView(getApplicationContext()); rootLayout.addView(txt); setContentView(rootLayout); // Set the text and call the connect function. txt.setText("Connecting..."); //call the method to run the data retreival txt.setText(getServerData(KEY_121)); } public static final String KEY_121 = "http://example.com/mydbcall.php"; private String getServerData(String returnString) { InputStream is = null; String result = ""; //the year data to send //ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //nameValuePairs.add(new BasicNameValuePair("year","1970")); try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(KEY_121); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","longitude: "+json_data.getDouble("longitude")+ ", latitude: "+json_data.getDouble("latitude") ); //Get an output to the screen returnString += "\n\t" + jArray.getJSONObject(i); } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } return returnString; } } So the code: returnString += "\n\t" + jArray.getJSONObject(i); is what is currently printing to the screen. What I have to figure out is how to get the data into something I can reference in other spots in the program, and access the individual elements ie: double longitude = jArray.getJSONObject(3).longitude; or something to that effect.. I figure the class getServerData will have to return a Array type or something? Any help is appreciated, thanks.

    Read the article

  • Problem with serialization of svcutil synthetized classes

    - by user295502
    I used svcutil to generate classes to access the web service. I need to serialize them. The class is quite simple, here is how it looks [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="cosemAttributeDescriptor", Namespace="http://www.energiened.nl/Content/Publications/dsmr/P32")] public partial class cosemAttributeDescriptor : object, System.Runtime.Serialization.IExtensibleDataObject { private System.Runtime.Serialization.ExtensionDataObject extensionDataField; private ushort ClassIdField; private string InstanceIdField; private sbyte AttributeIdField; public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)] public ushort ClassId { get { return this.ClassIdField; } set { this.ClassIdField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, EmitDefaultValue=false)] public string InstanceId { get { return this.InstanceIdField; } set { this.InstanceIdField = value; } } [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=2)] public sbyte AttributeId { get { return this.AttributeIdField; } set { this.AttributeIdField = value; } } } Now, the problem is I can't serialize the class. Here is the serialization code: cosemAttributeDescriptor cAttrD = new cosemAttributeDescriptor(); cAttrD.ClassId = 3; cAttrD.InstanceId = "0100010800FF"; cAttrD.AttributeId = 0; DataContractSerializer dSer = new DataContractSerializer(typeof(cosemAttributeDescriptor)); StringBuilder sb = new StringBuilder(); XmlWriter xW = XmlWriter.Create(sb); dSer.WriteObject(xW, cAttrD); When I try to serialize the class, I get empty string. Any thoughts?

    Read the article

  • Problems with ltk (common lisp)

    - by Silvanus
    I installed ltk to Steel Bank Common Lisp with asdf-install, but I can't even start using it V_V. The code below is the simplest example in the documentation, and is copied almost verbatim. asdf:operate 'asdf:load-op :ltk) (defun hello-1() (with-ltk () (let ((b (make-instance 'button :master nil :text "Press Me" :command (lambda () (format t "Hello World!~&"))))) (pack b)))) (hello-1) This is the error message I get from sbcl: ; in: LAMBDA NIL ; (PACK B) ; ; caught STYLE-WARNING: ; undefined function: PACK ; (WITH-LTK NIL ; (LET ((B (MAKE-INSTANCE 'BUTTON :MASTER NIL :TEXT "Press Me" :COMMAND #))) ; (PACK B))) ; ; caught STYLE-WARNING: ; undefined function: WITH-LTK ; ; compilation unit finished ; Undefined functions: ; PACK WITH-LTK ; caught 2 STYLE-WARNING conditions debugger invoked on a SIMPLE-ERROR in thread #: There is no class named BUTTON. Type HELP for debugger help, or (SB-EXT:QUIT) to exit from SBCL. restarts (invokable by number or by possibly-abbreviated name): 0: [ABORT] Exit debugger, returning to top level. (SB-PCL::FIND-CLASS-FROM-CELL BUTTON NIL T)

    Read the article

  • C# PInvoke VerQueryValue returns back OutOfMemoryException?

    - by Bopha
    Hi, Below is the code sample which I got from online resource but it's suppose to work with fullframework, but when I try to build it using C# smart device, it throws exception saying it's out of memory. Does anybody know how can I fix it to use on compact? the out of memory exception when I make the second call to VerQueryValue which is the last one. thanks, [DllImport("coredll.dll")] public static extern bool VerQueryValue(byte[] buffer, string subblock, out IntPtr blockbuffer, out uint len); [DllImport("coredll.dll")] public static extern bool VerQueryValue(byte[] pBlock, string pSubBlock, out string pValue, out uint len); // private static void GetAssemblyVersion() { string filename = @"\Windows\MyLibrary.dll"; if (File.Exists(filename)) { try { int handle = 0; Int32 size = 0; size = GetFileVersionInfoSize(filename, out handle); if (size > 0) { bool retValue; byte[] buffer = new byte[size]; retValue = GetFileVersionInfo(filename, handle, size, buffer); if (retValue == true) { bool success = false; IntPtr blockbuffer = IntPtr.Zero; uint len = 0; //success = VerQueryValue(buffer, "\\", out blockbuffer, out len); success = VerQueryValue(buffer, @"\VarFileInfo\Translation", out blockbuffer, out len); if(success) { int p = (int)blockbuffer; //Reads a 16-bit signed integer from unmanaged memory int j = Marshal.ReadInt16((IntPtr)p); p += 2; //Reads a 16-bit signed integer from unmanaged memory int k = Marshal.ReadInt16((IntPtr)p); string sb = string.Format("{0:X4}{1:X4}", j, k); string spv = @"\StringFileInfo\" + sb + @"\ProductVersion"; string versionInfo; VerQueryValue(buffer, spv, out versionInfo, out len); } } } } catch (Exception err) { string error = err.Message; } } }

    Read the article

  • ADO.NET Batch Insert with over 2000 parameters

    - by Liming
    Hello all, I'm using Enterprise library, but the idea is the same. I have a SqlStringCommand and the sql is constructed using StringBuilder in the forms of "insert into table (column1, column2, column3) values (@param1-X, @param2-X, @parm3-X)"+" " where "X" represents a "for loop" about 700 rows StringBuilder sb = new StringBuilder(); for(int i=0; i<700; i++) { sb.Append("insert into table (column1, column2, column3) values (@param1-"+i+", @param2-"+i, +",@parm3-"+i+") " ); } followed by constructing a command object injecting all the parameters w/ values into it. Essentially, 700 rows with 3 parameters, I ended up with 2100 parameters for this "one sql" Statement. It ran fine for about a few days and suddenly I got this error =============================================================== A severe error occurred on the current command. The results, if any, should be discarded. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNon Any pointers are greatly appreciated.

    Read the article

  • Tieing Fullcalendar into my database

    - by Ed
    I am trying to figure out this fullcalendar and how to get events from database. I am using asp .net I am using a webservice that has something like this. I am just trying to put a test record first then I will tie it to the database once i get it working. Any help would be greatly appreciated! Thanks alot! Just trying to figure out how to tie my webservice. So my webservice goes like so. _ _ _ _ Public Class WebService1 Inherits System.Web.Services.WebService <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _ Public Function Getcalendar() As String Dim sb As New StringBuilder Dim sw As New IO.StringWriter(sb) Dim strOut As String = String.Empty Using writer As New JsonTextWriter(sw) writer.WriteStartObject() writer.WritePropertyName("id") writer.WriteValue("999") writer.WritePropertyName("title") writer.WriteValue("my test") writer.WritePropertyName("allday") writer.WriteValue("false") writer.WritePropertyName("start") writer.WriteValue("2010-04-14T11:00:00") writer.WritePropertyName("end") writer.WriteValue("2010-04-14T13:00:00") writer.WriteEndObject() strOut = sw.ToString End Using Return strOut End Function End Class And my html goes like this <script type="text/javascript"> $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, events: RVCSC.WebService1.Getcalendar() }); });

    Read the article

  • Fullcalendar tieing into my database

    - by Ed
    I am trying to figure out this fullcalendar and how to get events from database. I am using asp .net I am using a webservice that has something like this. I am just trying to put a test record first then I will tie it to the database once i get it working. Any help would be greatly appreciated! Thanks alot! Just trying to figure out how to tie my webservice. So my webservice goes like so. _ _ _ _ Public Class WebService1 Inherits System.Web.Services.WebService <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _ Public Function Getcalendar() As String Dim sb As New StringBuilder Dim sw As New IO.StringWriter(sb) Dim strOut As String = String.Empty Using writer As New JsonTextWriter(sw) writer.WriteStartObject() writer.WritePropertyName("id") writer.WriteValue("999") writer.WritePropertyName("title") writer.WriteValue("my test") writer.WritePropertyName("allday") writer.WriteValue("false") writer.WritePropertyName("start") writer.WriteValue("2010-04-14T11:00:00") writer.WritePropertyName("end") writer.WriteValue("2010-04-14T13:00:00") writer.WriteEndObject() strOut = sw.ToString End Using Return strOut End Function End Class And my html goes like this <script type="text/javascript"> $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, events: RVCSC.WebService1.Getcalendar() }); });

    Read the article

  • C# - File Encoding Problem.

    - by user301330
    Hello, I'm have a StringBuilder that is writing content to a file. Towards the end of each file, I'm writing the copyright symbol. Oddly, I have noticed that whenever the copyright symbol is written, it is preceeded by a "Â". My code that generates the content of the file looks like this: using (StringWriter stringWriter = new StringWriter()) { stringWriter = GetFileContent(); string targetPath = ConfigurationManager.AppSettings["TargetPath"]; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { StringBuilder sb = new StringBuilder(stringWriter.ToString()); // Attempted fix string content = sb.ToString(); content = content.Replace("Â", ""); streamWriter.Write(content); } } As you can tell, I tried to do a find-and-replace. In the process, I noticed that a "Â" was not in the content itself. This makes me believe there is something occurring in the streamWriter. However, I'm not sure what it could be. Can someone please tell me why a "Â" would be popping up before the "©" symbol and how to fix it? I believe it has something to do with encoding, but I'm not sure Thank you!

    Read the article

  • Get an Arduino and Android phone to communicate over the web

    - by Saleem
    I am writing an Android application to communicate with my Arduino over the web. The Arduino is running a web server through an Ethernet shield. I am attaching my code, but I will explain it here so you will understand what I am trying to do. The Android sends an HTTP request in the format http://192.168.1.148/?Lights=1. The Arduino gets the request, executes the command (in this case turning on some lights) and then responds to the Android device by simply sending the string "Lights=On". The Android will then change the color of the button to notify the user that the command was executed successfully. The Arduino is getting the instruction and executing it and sending the response but my button color is not changing. I know that the Android device is getting the string because I added a debug line to change the text on the button to the received response. The relevant code for the Android device is: ((Button) v).setText(sb.toString()); //This works and the button text changes to "Lights=On". //Test response and update button if(sb.toString()=="Lights=On"){ v.getBackground().setColorFilter(0xFFFFFF00, PorterDuff.Mode.MULTIPLY); Drawable d = lightOff.getBackground(); lightOff.invalidateDrawable(d); d.clearColorFilter(); } The Arduino code is: if(s=="Lights"){ switch(client.read()){ case '0': digitalWrite(LightPin,0); client.print("Lights=Off"); //debug Serial.println("Lights=Off"); break; case '1': digitalWrite(LightPin,1); client.print("Lights=On"); Serial.println("Lights=On"); break; } } Please let me know if you need more of the code to answer this question.

    Read the article

  • WCF and ASP.NET - Server.Execute throwing object reference not set to an instance of an object

    - by user208662
    Hello, I have an ASP.NET page that calls to a WCF service. This WCF service uses a BackgroundWorker to asynchronously create an ASP.NET page on my server. Oddly, when I execute the WCF Service [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public void PostRequest(string comments) { // Do stuff // If everything went o.k. asynchronously render a page on the server. I do not want to // block the caller while this is occurring. BackgroundWorker myWorker = new BackgroundWorker(); myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork); myWorker.RunWorkerAsync(HttpContext.Current); } private void myWorker_DoWork(object sender, DoWorkEventArgs e) { // Set the current context so we can render the page via Server.Execute HttpContext context = (HttpContext)(e.Argument); HttpContext.Current = context; // Retrieve the url to the page string applicationPath = context.Request.ApplicationPath; string sourceUrl = applicationPath + "/log.aspx"; string targetDirectory = currentContext.Server.MapPath("/logs/"); // Execute the other page and load its contents using (StringWriter stringWriter = new StringWriter()) { // Write the contents out to the target url // NOTE: THIS IS WHERE MY ERROR OCCURS currentContext.Server.Execute(sourceUrl, stringWriter); // Prepare to write out the result of the log targetPath = targetDirectory + "/" + DateTime.Now.ToShortDateString() + ".aspx"; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { // Write out the content to the file sb.Append(stringWriter.ToString()); streamWriter.Write(sb.ToString()); } } } Oddly, when the currentContext.Server.Execute method is executed, it throws an "object reference not set to an instance of an object" error. The reason this is so strange is because I can look at the currentContext properties in the watch window. In addition, Server is not null. Because of this, I have no idea where this error is coming from. Can someone point me in the correct direction of what the cause of this could be? Thank you!

    Read the article

  • ASP.NET - Webservice not being called from javascript

    - by Robert
    Ok I'm stumped on this one. I've got a ASMX web service up and running. I can browse to it (~/Webservice.asmx) and see the .NET generated page and test it out.. and it works fine. I've got a page with a Script Manager with the webservice registered... and i can call it in javascript (Webservice.Method(...)) just fine. However, I want to use this Webservice as part of a jQuery Autocomplete box. So I have use the url...? and the Webservice is never being called. Here's the code. [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class User : System.Web.Services.WebService { public User () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public string Autocomplete(string q) { StringBuilder sb = new StringBuilder(); //doStuff return sb.ToString(); } web.config <system.web> <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> And the HTML $(document).ready(function() { User.Autocomplete("rr", function(data) { alert(data); });//this works ("#<%=txtUserNbr.ClientID %>").autocomplete("/User.asmx/Autocomplete"); //doesn't work $.ajax({ url: "/User.asmx/Autocomplete", success: function() { alert(data); }, error: function(e) { alert(e); } }); //just to test... calls "error" function });

    Read the article

  • data transmission between two sites

    - by SaMSa
    I'm use Asp.Net Mvc 4 www.hostname.com to my site from my report.hostname2.com send and receive data to move directly to that address by the string bi codebehind. querysstring not, because sending a very long string I mean rapor.coskunoglu.net/Pdf address to send string data to move directly to that address PDF of the screen to make it appear so. How can I do this? Thank you, take it easy. I'm sorry, my english is not good. EDIT: I want to use POST. sb - my StringBuilder. byte[] bytt = Encoding.UTF8.GetBytes(sb.ToString()); WebRequest wr = WebRequest.Create("http://report.hostname2.com/Pdf"); wr.ContentType = "application/x-www-form-urlencoded"; wr.ContentLength = bytt.Length; wr.Method = "POST"; Stream st = wr.GetRequestStream(); st.Write(bytt, 0, bytt.Length); st.Close(); After you send the POST I want to go to report.hostname2.com. Did you see this my job?

    Read the article

  • Copy only files that are newer

    - by ErocM
    I am currently using this code: if (!Directory.Exists(command2)) Directory.CreateDirectory(command2); if (Directory.Exists(vmdaydir)) Directory.Delete(vmdaydir,true); if (!Directory.Exists(vmdaydir)) Directory.CreateDirectory(vmdaydir); var dir = Path.GetDirectoryName(args[0]); sb.AppendLine("Backing Up VM: " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(dir, vmdaydir); sb.AppendLine("VM Backed Up: " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); As you can see, I am deleting the directory, then I am copying the folder back. This is taking way to long since the directory is ~80gb in size. I realized that I do not need to copy all the files, only the ones that have changed. How would I copy the files from one folder to another but only copying the files that are newer? Anyone have any suggestions? ==== edit ==== I assume I can just do a file compare of each file and then copy it to the new directory, iterating through each folder/file? Is there a simpler way to do this?

    Read the article

  • Problem with ScriptManager when trying to email rendered contents of ASP.NET page

    - by pandojc
    I recently added a Telerik control to an ascx that is included in an aspx page. This page has a "Send email" button, which when clicked will email the user the rendered output of the page. The Telerik control I added requires a ScriptManager, so I added that to the ascx. However, now the email button won't work. I get the following error: The control with ID 'myIdHere' requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it. I know the script manager exists because the page works fine when I go that url, it is only failing when it tries to email the rendered output. Here's a code snippet, any ideas as to whether there is a problem with scriptmanager when doing this sort of thing? Page EmailPage = new EmailBasePage(); System.Web.UI.HtmlControls.HtmlForm EmailForm = new System.Web.UI.HtmlControls.HtmlForm(); EmailPage.Controls.Add(EmailForm); EmailForm.Controls.Add(contentTable); //this is the container with all the controls I want to email StringBuilder SB = new StringBuilder(); StringWriter html = new StringWriter(SB); HtmlTextWriter mhtmlWriter = new HtmlTextWriter(html); EmailPage.DesignerInitialize(); EmailPage.RenderControl(mhtmlWriter); mhtmlWriter.Close();

    Read the article

  • Entity Filter child without include

    - by Lic
    i'm a C# developer and i have a trouble with Entity Framework 5. I have mapped my database with Entity using the default code generation strategy. In particolar there are three classes: menus, submenus and submenuitems. The relationships about three classes are: one menu - to many submenus one submenu - to many submenuitems. All classes have a boolean attribute called "Active". Now, i want to filter all the Menus with the SubMenus active, and the SubMenus with the SubMenuItems active. To get this i've tried this: var tmp = _model.Menus.Where(m => m.Active) .Select => new { Menu = x, SubMenu = x.SubMenus.Where(sb => sb.Active) .Select(y => new { SubMenu = y, SubMenuItem = y.SubMenuItems.Where(sbi => sbi.Active) }) }) .Select(x => x.Menu).ToList(); But didn't work. Someone can help me? Thank you for your help!

    Read the article

  • Image is not displaying in email template on 2nd time forward

    - by Don
    Good day Friends, I've a mass mailing program with simple mail templates (HTML and few Images). I've a problem with image display. My clients are not getting images in the mail. Sometimes they get a mail with all the images, But if they forward the same email to someone else, they can’t get the images in forwarded mail. I really don’t know what’s happening with the approach., most of the cases the 2nd time forwarded mail is not showing the images properly. For example, consider I send a mail to client A, Here, Client A will get a mail with Images. Further, If Client A forward the same message to Person B then Person B is not getting Images in the Forwarded email. I’m using the following Approach to Embed an image in the mail template: StringBuilder sb = new StringBuilder(" <some html content> <img src=\"cid:main.png\" alt=\"\" border=\"0\" usemap=\"#Map\"> </html content ends here>"); Attachment imgMain = new Attachment(Server.MapPath("main.png")); imgMain.ContentId = "main.png"; MailMessageObject.Attachments.Add(imgMain); Instead of attachment, I tried bypassing the Image path from server directly. Something like as follows: StringBuilder sb = new StringBuilder(" <some html content> <img src=\"www.mydomain.com/images/main.png\" alt=\"\" border=\"0\" usemap=\"#Map\"> </html content ends here>"); But, result is same, Please help to resolve this problem

    Read the article

  • Write to PDF using PHP from android device

    - by Brent Mitchell
    I am trying to write to a pdf file on php server. I have sent variables to the server, create the pdf document, then have my phone download the document to view on device. The variables seem not to write on the php file. I have my code below public void postData() { try { Calculate calc = new Calculate(); HttpClient mClient = new DefaultHttpClient(); StringBuilder sb=new StringBuilder("myurl.com/pdf.php"); HttpPost mpost = new HttpPost(sb.toString()); String value = "1234"; List nameValuepairs = new ArrayList(1); nameValuepairs.add(new BasicNameValuePair("id",value)); mpost.setEntity(new UrlEncodedFormEntity(nameValuepairs)); } catch (UnsupportedEncodingException e) { Log.w(" error ", e.toString()); } catch (Exception e) { Log.w(" error ", e.toString()); } } And my php code to write the variable "value" onto the pdf document: //code to reverse the string if($_POST[] != null) { $reversed = strrev($_POST["value"]); $this->SetFont('Arial','u',50); $this->Text(52,68,$reversed); } I am just trying to write the variable in a random spot, but the variable the if statement is always null and I do not know why. Thanks. Sorry if it is a little sloppy.

    Read the article

  • Trying to login to site with PHP & cURL?

    - by motionman95
    I've never done something like this before...I'm trying to log into swagbucks.com and get retrieve some information, but it's not working. Can someone tell me what's wrong with my script? <?php $pages = array('home' => 'http://swagbucks.com/?cmd=home', 'login' => 'http://swagbucks.com/?cmd=sb-login&from=/?cmd=home', 'schedule' => 'http://swagbucks.com/?cmd=sb-acct-account&display=2'); $ch = curl_init(); //Set options for curl session $options = array(CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; `rv:1.9.2) Gecko/20100115 Firefox/3.6',` CURLOPT_HEADER => TRUE, //CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_COOKIEFILE => 'cookie.txt', CURLOPT_COOKIEJAR => 'cookies.txt'); //Hit home page for session cookie $options[CURLOPT_URL] = $pages['home']; curl_setopt_array($ch, $options); curl_exec($ch); //Login $options[CURLOPT_URL] = $pages['login']; $options[CURLOPT_POST] = TRUE; $options[CURLOPT_POSTFIELDS] = '[email protected]&pswd=jblake&persist=on'; $options[CURLOPT_FOLLOWLOCATION] = FALSE; curl_setopt_array($ch, $options); curl_exec($ch); //Hit schedule page $options[CURLOPT_URL] = $pages['schedule']; curl_setopt_array($ch, $options); $schedule = curl_exec($ch); //Output schedule echo $schedule; //Close curl session curl_close($ch); ?> But it still doesn't log me in. What's wrong?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17  | Next Page >