Search Results

Search found 189 results on 8 pages for 'exc'.

Page 8/8 | < Previous Page | 4 5 6 7 8 

  • Could not load type 'Default.DataMatch' in DataMatch.aspx file

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2008 website, but now I am getting the above error when I build it. I included the Default.aspx, Default.aspx.cs, DataMatch.aspx, and DataMatch.aspx.cs files below. What do I need to do to fix this? Default.aspx: <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> ... DataMatch.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataMatch.aspx.cs" Inherits="_Default.DataMatch" %> ... Default.aspx.cs: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using System.IO; using System.Drawing; using System.ComponentModel; using System.Data.SqlClient; using ADONET_namespace; using System.Security.Principal; //using System.Windows; public partial class _Default : System.Web.UI.Page //namespace AddFileToSQL { //protected System.Web.UI.HtmlControls.HtmlInputFile uploadFile; //protected System.Web.UI.HtmlControls.HtmlInputButton btnOWrite; //protected System.Web.UI.HtmlControls.HtmlInputButton btnAppend; protected System.Web.UI.WebControls.Label Label1; protected static string inputfile = ""; public static string targettable; public static string selection; // Number of controls added to view state protected int default_NumberOfControls { get { if (ViewState["default_NumberOfControls"] != null) { return (int)ViewState["default_NumberOfControls"]; } else { return 0; } } set { ViewState["default_NumberOfControls"] = value; } } protected void uploadFile_onclick(object sender, EventArgs e) { } protected void Load_GridData() { //GridView1.DataSource = ADONET_methods.DisplaySchemaTables(); //GridView1.DataBind(); } protected void btnOWrite_Click(object sender, EventArgs e) { if (uploadFile.PostedFile.ContentLength > 0) { feedbackLabel.Text = "You do not have sufficient access to overwrite table records."; } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void btnAppend_Click(object sender, EventArgs e) { string fullpath = Page.Request.PhysicalApplicationPath; string path = uploadFile.PostedFile.FileName; if (File.Exists(path)) { // Create a file to write to. try { StreamReader sr = new StreamReader(path); string s = ""; while (sr.Peek() > 0) s = sr.ReadLine(); sr.Close(); } catch (IOException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return; } } if (uploadFile.PostedFile.ContentLength > 0) { inputfile = System.IO.File.ReadAllText(path); Session["Message"] = inputfile; Response.Redirect("DataMatch.aspx"); } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { WelcomeBackMessage.Text = "Welcome back, " + User.Identity.Name + "!"; // Reference the CustomPrincipal / CustomIdentity CustomIdentity ident = User.Identity as CustomIdentity; if (ident != null) WelcomeBackMessage.Text += string.Format(" You are the {0} of {1}.", ident.Title, ident.CompanyName); AuthenticatedMessagePanel.Visible = true; AnonymousMessagePanel.Visible = false; if (!Page.IsPostBack) { Load_GridData(); } } else { AuthenticatedMessagePanel.Visible = false; AnonymousMessagePanel.Visible = true; } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; targettable = row.Cells[2].Text; } } DataMatch.aspx.cs: using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ADONET_namespace; //using MatrixApp; //namespace AddFileToSQL //{ public partial class DataMatch : AddFileToSQL._Default { protected System.Web.UI.WebControls.PlaceHolder phTextBoxes; protected System.Web.UI.WebControls.PlaceHolder phDropDownLists; protected System.Web.UI.WebControls.Button btnAnotherRequest; protected System.Web.UI.WebControls.Panel pnlCreateData; protected System.Web.UI.WebControls.Literal lTextData; protected System.Web.UI.WebControls.Panel pnlDisplayData; protected static string inputfile2; static string[] headers = null; static string[] data = null; static string[] data2 = null; static DataTable myInputFile = new DataTable("MyInputFile"); static string[] myUserSelections; static bool restart = false; private DropDownList[] newcol; int @temp = 0; string @tempS = ""; string @tempT = ""; // a Property that manages a counter stored in ViewState protected int NumberOfControls { get { return (int)ViewState["NumControls"]; } set { ViewState["NumControls"] = value; } } private Hashtable ddl_ht { get { return (Hashtable)ViewState["ddl_ht"]; } set { ViewState["ddl_ht"] = value; } } // Page Load private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { ddl_ht = new Hashtable(); this.NumberOfControls = 0; } } // This data comes from input file private void PopulateFileInputTable() { myInputFile.Columns.Clear(); string strInput, newrow; string[] oneRow; DataColumn myDataColumn; DataRow myDataRow; int result, numRows; //Read the input file strInput = Session["Message"].ToString(); data = strInput.Split('\r'); //Headers headers = data[0].Split('|'); //Data for (int i = 0; i < data.Length; i++) { newrow = data[i].TrimStart('\n'); data[i] = newrow; } result = String.Compare(data[data.Length - 1], ""); numRows = data.Length; if (result == 0) { numRows = numRows - 1; } data2 = new string[numRows]; for (int a = 0, b = 0; a < numRows; a++, b++) { data2[b] = data[a]; } // Create columns for (int col = 0; col < headers.Length; col++) { @temp = (col + 1); @tempS = @temp.ToString(); @tempT = "@col"+ @temp.ToString(); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = headers[col]; myInputFile.Columns.Add(myDataColumn); ddl_ht.Add(@tempT, headers[col]); } // Create new DataRow objects and add to DataTable. for (int r = 0; r < numRows - 1; r++) { oneRow = data2[r + 1].Split('|'); myDataRow = myInputFile.NewRow(); for (int c = 0; c < headers.Length; c++) { myDataRow[c] = oneRow[c]; } myInputFile.Rows.Add(myDataRow); } NumberOfControls = headers.Length; myUserSelections = new string[NumberOfControls]; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); btnSubmit.Style.Add("top", "200px"); btnSubmit.Style.Add("left", "400px"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } } //Recreate display panel private void RecreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); btnSubmit.Style.Add("top", "200px"); btnSubmit.Style.Add("left", "400px"); newcol = RecreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } } // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks dr2.Close(); ddl.Items.Add("IGNORE"); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } // Add TextBoxes Control to Placeholder private DropDownList[] RecreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = false; //Preserves View State info on Postbacks dr2.Close(); ddl.Items.Add("IGNORE"); dropDowns[counter] = ddl; } return dropDowns; } private void CreateLabels() { for (int counter = 0; counter < NumberOfControls; counter++) { Label lbl = new Label(); lbl.ID = "Label" + counter.ToString(); lbl.Text = headers[counter]; lbl.Style["position"] = "absolute"; lbl.Style["top"] = 60 * counter + 10 + "px"; lbl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(lbl); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); } } // Add TextBoxes Control to Placeholder private void RecreateLabels() { for (int counter = 0; counter < NumberOfControls; counter++) { Label lbl = new Label(); lbl.ID = "Label" + counter.ToString(); lbl.Text = headers[counter]; lbl.Style["position"] = "absolute"; lbl.Style["top"] = 60 * counter + 10 + "px"; lbl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(lbl); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); } } // Create TextBoxes and DropDownList data here on postback. protected override void CreateChildControls() { // create the child controls if the server control does not contains child controls this.EnsureChildControls(); // Creates a new ControlCollection. this.CreateControlCollection(); // Here we are recreating controls to persist the ViewState on every post back if (Page.IsPostBack) { RecreateDisplayPanel(); RecreateLabels(); } // Create these conrols when asp.net page is created else { PopulateFileInputTable(); CreateDisplayPanel(); CreateLabels(); } // Prevent dropdownlists and labels from being created again. if (restart == false) { this.ChildControlsCreated = true; } else if (restart == true) { this.ChildControlsCreated = false; } } private void AppendRecords() { switch (targettable) { case "ContactType": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataCT(myInputFile.Rows[r], ddl_ht); } break; case "Contact": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataC(myInputFile.Rows[r], ddl_ht); } break; case "AddressType": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataAT(myInputFile.Rows[r], ddl_ht); } break; default: resultLabel.Text = "You do not have access to modify this table. Please select a different target table and try again."; restart = true; break; //throw new ArgumentOutOfRangeException("targettable type", targettable); } } // Read all the data from TextBoxes and DropDownLists protected void btnSubmit_Click(object sender, System.EventArgs e) { //int cnt = FindOccurence("DropDownListID"); AppendRecords(); pnlDisplayData.Visible = false; btnSubmit.Visible = false; resultLabel.Attributes.Add("style", "align:center"); btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); int bSubmitPosition = NumberOfControls; btnSubmit.Style.Add("top", System.Convert.ToString(bSubmitPosition)+"px"); resultLabel.Visible = true; Instructions.Visible = false; if (restart == true) { CreateChildControls(); } } private int FindOccurence(string substr) { string reqstr = Request.Form.ToString(); return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion } //}

    Read the article

  • OperationalError "unable to open database file" processing query results with SQLAlchemy and SQLite3

    - by Peter
    I'm running into this little problem that I hope is just a dumb user error. It looks like some sort of a size limit with a query to a SQLite database. I managed to reproduce the issue with an in-memory DB and a simple script shown below. I can make it work by either reducing the number of records in the DB; or by reducing the size of each record; or by dropping the order_by() call. I am using Python 2.5.5 and SQLAlchemy 0.6.0 in a Cygwin environment. Thanks! #!/usr/bin/python from sqlalchemy.orm import sessionmaker import sqlalchemy import sqlalchemy.orm class Person(object): def __init__(self, name): self.name = name engine = sqlalchemy.create_engine('sqlite:///:memory:') Session = sessionmaker(bind=engine) metadata = sqlalchemy.schema.MetaData(bind=engine) person_table = sqlalchemy.Table('person', metadata, sqlalchemy.Column('id', sqlalchemy.types.Integer, primary_key=True), sqlalchemy.Column('name', sqlalchemy.types.String)) metadata.create_all(engine) sqlalchemy.orm.mapper(Person, person_table) session = Session() session.add_all([Person("012345678901234567890123456789012") for i in range(5000)]) session.commit() persons = session.query(Person).order_by(Person.name).all() print "count =", len(persons) session.close() The all() call to the query result fails with the OperationalError exception: Traceback (most recent call last): File "./stress.py", line 27, in <module> persons = session.query(Person).order_by(Person.name).all() File "/usr/lib/python2.5/site-packages/sqlalchemy/orm/query.py", line 1343, in all return list(self) File "/usr/lib/python2.5/site-packages/sqlalchemy/orm/query.py", line 1451, in __iter__ return self._execute_and_instances(context) File "/usr/lib/python2.5/site-packages/sqlalchemy/orm/query.py", line 1456, in _execute_and_instances mapper=self._mapper_zero_or_none()) File "/usr/lib/python2.5/site-packages/sqlalchemy/orm/session.py", line 737, in execute clause, params or {}) File "/usr/lib/python2.5/site-packages/sqlalchemy/engine/base.py", line 1109, in execute return Connection.executors[c](self, object, multiparams, params) File "/usr/lib/python2.5/site-packages/sqlalchemy/engine/base.py", line 1186, in _execute_clauseelement return self.__execute_context(context) File "/usr/lib/python2.5/site-packages/sqlalchemy/engine/base.py", line 1215, in __execute_context context.parameters[0], context=context) File "/usr/lib/python2.5/site-packages/sqlalchemy/engine/base.py", line 1284, in _cursor_execute self._handle_dbapi_exception(e, statement, parameters, cursor, context) File "/usr/lib/python2.5/site-packages/sqlalchemy/engine/base.py", line 1282, in _cursor_execute self.dialect.do_execute(cursor, statement, parameters, context=context) File "/usr/lib/python2.5/site-packages/sqlalchemy/engine/default.py", line 277, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.OperationalError: (OperationalError) unable to open database file u'SELECT person.id AS person_id, person.name AS person_name \nFROM person ORDER BY person.name' ()

    Read the article

  • DbgHelp.dll : Problem calling SymGetModuleInfo64 from C#

    - by Civa
    Hello everyone, I have quite strange behaviour calling SymGetModuleInfo64 from C# code.I always get ERROR_INVALID_PARAMETER (87) with Marshal.GetLastWin32Error().I have already read a lot of posts regarding problems with frequent updates of IMAGEHLP_MODULE64 struct and I just downloaded latest Debugging Tools For Windows (x86) , loaded dbghelp.dll from that location and I was quite sure it would work.Nevertheless I am getting the same error.Can anyone point me what is wrong here? IMAGEHLP_MODULE64 struct is defined in my code as follows : [StructLayout(LayoutKind.Sequential)] public struct IMAGEHELP_MODULE64 { //************************************************ public int SizeOfStruct; public long BaseOfImage; public int ImageSize; public int TimeDateStamp; public int CheckSum; public int NumSyms; public SymType SymType; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string ModuleName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string ImageName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string LoadedImageName; //************************************************ //new elements v2 //************************************************* [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string LoadedPdbName; public int CVSig; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 780)] public string CVData; public int PdbSig; public GUID PdbSig70; public int PdbAge; public bool PdbUnmatched; public bool DbgUnmatched; public bool LineNumbers; public bool GlobalSymbols; public bool TypeInfo; //************************************************ //new elements v3 //************************************************ public bool SourceIndexed; public bool Publics; //************************************************ //new elements v4 //************************************************ public int MachineType; public int Reserved; //************************************************ } the piece of code that actually calls SymGetModuleInfo64 is like this : public void GetSymbolInfo(IntPtr hProcess,long modBase64,out bool success) { success = false; DbgHelp.IMAGEHELP_MODULE64 moduleInfo = new DbgHelp.IMAGEHELP_MODULE64(); moduleInfo.SizeOfStruct = Marshal.SizeOf(moduleInfo); try { success = DbgHelp.SymGetModuleInfo64(hProcess, modBase64, out moduleInfo); if (success) { //Do the stuff here } } catch (Exception exc) { } } Im stuck here...always with error 87.Please someone points me to the right direction. By the way modBase64 is value previously populated by : modBase64 = DbgHelp.SymLoadModule64(_handle, IntPtr.Zero, fileName, null, baseAddress, size); where _handle is process handle of process being debugged,fileName is path of current loaded module, baseAddress is address base of currently loaded module and size is of course the size of current loaded module.I call this code when I get LOAD_DLL_DEBUG_EVENT. Edit : Sorry, I forgot to mention that SymGetModuleInfo64 signature is like this : [DllImport("dbghelp.dll", SetLastError = true)] public static extern bool SymGetModuleInfo64(IntPtr hProcess, long ModuleBase64, out IMAGEHELP_MODULE64 imgHelpModule); Best regards, Civa

    Read the article

  • Why does Celery work in Python shell, but not in my Django views? (import problem)

    - by TIMEX
    I installed Celery (latest stable version.) I have a directory called /home/myuser/fable/jobs. Inside this directory, I have a file called tasks.py: from celery.decorators import task from celery.task import Task class Submitter(Task): def run(self, post, **kwargs): return "Yes, it works!!!!!!" Inside this directory, I also have a file called celeryconfig.py: BROKER_HOST = "localhost" BROKER_PORT = 5672 BROKER_USER = "abc" BROKER_PASSWORD = "xyz" BROKER_VHOST = "fablemq" CELERY_RESULT_BACKEND = "amqp" CELERY_IMPORTS = ("tasks", ) In my /etc/profile, I have these set as my PYTHONPATH: PYTHONPATH=/home/myuser/fable:/home/myuser/fable/jobs So I run my Celery worker using the console ($ celeryd --loglevel=INFO), and I try it out. I open the Python console and import the tasks. Then, I run the Submitter. >>> import fable.jobs.tasks as tasks >>> s = tasks.Submitter() >>> s.delay("abc") <AsyncResult: d70d9732-fb07-4cca-82be-d7912124a987> Everything works, as you can see in my console [2011-01-09 17:30:05,766: INFO/MainProcess] Task tasks.Submitter[d70d9732-fb07-4cca-82be-d7912124a987] succeeded in 0.0398268699646s: But when I go into my Django's views.py and run the exact 3 lines of code as above, I get this: [2011-01-09 17:25:20,298: ERROR/MainProcess] Unknown task ignored: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported.": {'retries': 0, 'task': 'fable.jobs.tasks.Submitter', 'args': ('abc',), 'expires': None, 'eta': None, 'kwargs': {}, 'id': 'eb5c65b4-f352-45c6-96f1-05d3a5329d53'} Traceback (most recent call last): File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/listener.py", line 321, in receive_message eventer=self.event_dispatcher) File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 299, in from_message eta=eta, expires=expires) File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 243, in __init__ self.task = tasks[self.task_name] File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/registry.py", line 63, in __getitem__ raise self.NotRegistered(str(exc)) NotRegistered: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported." It's weird, because the celeryd client does show that it's registered, when I launch it. [2011-01-09 17:38:27,446: WARNING/MainProcess] Configuration -> . broker -> amqp://GOGOme@localhost:5672/fablemq . queues -> . celery -> exchange:celery (direct) binding:celery . concurrency -> 1 . loader -> celery.loaders.default.Loader . logfile -> [stderr]@INFO . events -> OFF . beat -> OFF . tasks -> . tasks.Decayer . tasks.Submitter Can someone help?

    Read the article

  • How can arguments to variadic functions be passed by reference in PHP?

    - by outis
    Assuming it's possible, how would one pass arguments by reference to a variadic function without generating a warning in PHP? We can no longer use the '&' operator in a function call, otherwise I'd accept that (even though it would be error prone, should a coder forget it). What inspired this is are old MySQLi wrapper classes that I unearthed (these days, I'd just use PDO). The only difference between the wrappers and the MySQLi classes is the wrappers throw exceptions rather than returning FALSE. class DBException extends RuntimeException {} ... class MySQLi_throwing extends mysqli { ... function prepare($query) { $stmt = parent::prepare($query); if (!$stmt) { throw new DBException($this->error, $this->errno); } return new MySQLi_stmt_throwing($this, $query, $stmt); } } // I don't remember why I switched from extension to composition, but // it shouldn't matter for this question. class MySQLi_stmt_throwing /* extends MySQLi_stmt */ { protected $_link, $_query, $_delegate; public function __construct($link, $query, $prepared) { //parent::__construct($link, $query); $this->_link = $link; $this->_query = $query; $this->_delegate = $prepared; } function bind_param($name, &$var) { return $this->_delegate->bind_param($name, $var); } function __call($name, $args) { //$rslt = call_user_func_array(array($this, 'parent::' . $name), $args); $rslt = call_user_func_array(array($this->_delegate, $name), $args); if (False === $rslt) { throw new DBException($this->_link->error, $this->errno); } return $rslt; } } The difficulty lies in calling methods such as bind_result on the wrapper. Constant-arity functions (e.g. bind_param) can be explicitly defined, allowing for pass-by-reference. bind_result, however, needs all arguments to be pass-by-reference. If you call bind_result on an instance of MySQLi_stmt_throwing as-is, the arguments are passed by value and the binding won't take. try { $id = Null; $stmt = $db->prepare('SELECT id FROM tbl WHERE ...'); $stmt->execute() $stmt->bind_result($id); // $id is still null at this point ... } catch (DBException $exc) { ... } Since the above classes are no longer in use, this question is merely a matter of curiosity. Alternate approaches to the wrapper classes are not relevant. Defining a method with a bunch of arguments taking Null default values is not correct (what if you define 20 arguments, but the function is called with 21?). Answers don't even need to be written in terms of MySQL_stmt_throwing; it exists simply to provide a concrete example.

    Read the article

  • controlling threads flow

    - by owca
    I had a task to write simple game simulating two players picking up 1-3 matches one after another until the pile is gone. I managed to do it for computer choosing random value of matches but now I'd like to go further and allow humans to play the game. Here's what I already have : http://paste.pocoo.org/show/201761/ Class Player is a computer player, and PlayerMan should be human being. Problem is, that thread of PlayerMan should wait until proper value of matches is given but I cannot make it work this way. Logic is as follows: thread runs until matches equals to zero. If player number is correct at the moment function pickMatches() is called. After decreasing number of matches on table, thread should wait and another thread should be notified. I know I must use wait() and notify() but I can't place them right. Class Shared keeps the value of current player, and also amount of matches. public void suspendThread() { suspended = true; } public void resumeThread() { suspended = false; } @Override public void run(){ int matches=1; int which = 0; int tmp=0; Shared data = this.selectData(); String name = this.returnName(); int number = this.getNumber(); while(data.getMatches() != 0){ while(!suspended){ try{ which = data.getCurrent(); if(number == which){ matches = pickMatches(); tmp = data.getMatches() - matches; data.setMatches(tmp, number); if(data.getMatches() == 0){ System.out.println(" "+ name+" takes "+matches+" matches."); System.out.println("Winner is player: "+name); stop(); } System.out.println(" "+ name+" takes "+matches+" matches."); if(number != 0){ data.setCurrent(0); } else{ data.setCurrent(1); } } this.suspendThread(); notifyAll(); wait(); }catch(InterruptedException exc) {} } } } @Override synchronized public int pickMatches(){ Scanner scanner = new Scanner(System.in); int n = 0; Shared data = this.selectData(); System.out.println("Choose amount of matches (from 1 to 3): "); if(data.getMatches() == 1){ System.out.println("There's only 1 match left !"); while(n != 1){ n = scanner.nextInt(); } } else{ do{ n = scanner.nextInt(); } while(n <= 1 && n >= 3); } return n; } }

    Read the article

  • Some more multitasking java issues

    - by owca
    I had a task to write simple game simulating two players picking up 1-3 matches one after another until the pile is gone. I managed to do it for computer choosing random value of matches but now I'd like to go further and allow humans to play the game. Here's what I already have : http://paste.pocoo.org/show/200660/ Class Player is a computer player, and PlayerMan should be human being. Problem is, that thread of PlayerMan should wait until proper value of matches is given but I cannot make it work this way. When I type the values it sometimes catches them and decrease amount of matches but that's not exactly what I was up to :) Logics is : I check the value of current player. If it corresponds to this of the thread currently active I use scanner to catch the amount of matches. Else I wait one second (I know it's kinda harsh solution, but I have no other idea how to do it). Class Shared keeps the value of current player, and also amount of matches. By the way, is there any way I can make Player and Shared attributes private instead of public and still make the code work ? CONSOLE and INPUT-DIALOG is just for choosing way of inserting values. class PlayerMan extends Player{ static final int CONSOLE=0; static final int INPUT_DIALOG=1; private int input; public PlayerMan(String name, Shared data, int c){ super(name, data); input = c; } @Override public void run(){ Scanner scanner = new Scanner(System.in); int n = 0; System.out.println("Matches on table: "+data.matchesAmount); System.out.println("which: "+data.which); System.out.println("number: "+number); while(data.matchesAmount != 0){ if(number == data.which){ System.out.println("Choose amount of matches (from 1 to 3): "); n = scanner.nextInt(); if(data.matchesAmount == 1){ System.out.println("There's only 1 match left !"); while(n != 1){ n = scanner.nextInt(); } } else{ do{ n = scanner.nextInt(); } while(n <= 1 && n >= 3); } data.matchesAmount = data.matchesAmount - n; System.out.println(" "+ name+" takes "+n+" matches."); if(number != 0){ data.which = 0; } else{ data.which = 1; } } else{ try { Thread.sleep(1000); } catch(InterruptedException exc) { System.out.println("End of thread."); return; } } System.out.println("Matches on table: "+data.matchesAmount); } if(data.matchesAmount == 0){ System.out.println("Winner is player: "+name); stop(); } } }

    Read the article

  • Where i am doing wrong in this?

    - by kumar
    <script type="text/javascript"> $(document).ready(function() { $('#PbtnSubmit').attr('disabled', 'disabled'); $('#PbtnCancel').attr('disabled', 'disabled'); $('#PbtnSelectAll').click(function() { $('#PricingEditExceptions input[type=checkbox]').attr('checked', 'checked'); $('#PbtnSubmit').removeAttr('disabled'); $('#PbtnCancel').removeAttr('disabled'); $('fieldset').find("input,select,textarea").removeAttr('disabled'); }); $('#PbtnCancel').click(function() { $('#PricingEditExceptions input[name=PMchk]').attr('checked', false); $('#PbtnSubmit').attr('disabled', 'disabled'); $('#PbtnCancel').attr('disabled', 'disabled'); $('fieldset').find("input:not(:checkbox),select,textarea").attr('disabled', 'disabled'); $('#genericfieldset').find("input,select,textarea").removeAttr('disabled'); }); $('#PbtnSubmit').click(function() { $('#PricingEditExceptions input[name=PMchk]').each(function() { if ($("#PricingEditExceptions input:checkbox:checked").length > 0) { var checked = $('#PricingEditExceptions input[type=checkbox]:checked'); var PMstrIDs = checked.map(function() { return $(this).val(); }).get().join(','); $('#1_exceptiontypes').attr('value', exceptiontypes) $('#1_PMstrIDs').attr('value', PMstrIDs); } else { alert("Please select atleast one exception"); return false; } }); }); function validate_excpt(formData, jqForm, options) { var form = jqForm[0]; } // post-submit callback function showResponse(responseText, statusText, xhr, $form) { if (responseText[0].substring(0, 16) != "System.Exception") { $('#error-msg-ID span:last').html('<strong>Update successful.</strong>'); } else { $('#error-msg-ID span:last').html('<strong>Update failed.</strong> ' + responseText[0].substring(0, 48)); } $('#error-msg-ID').removeClass('hide'); } $('#exc-').ajaxForm({ target: '#error-msg-ID', beforeSubmit: validate_excpt, success: showResponse, dataType: 'json' }); $('.button').button(); }); </script> This is my button.. at very first when page load I am trying Make Disabled PbtnSubmit and PbtnCancel and when we click PbtnSelectAll I am enabling back again.. but its not doing with this code. is that something I am doing worng in this? thanks

    Read the article

  • SQLAlchemy unsupported type error - and table design issues?

    - by Az
    Hi there, back again with some more SQLAlchemy shenanigans. Let me step through this. My table is now set up as so: engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('preferences', Integer), Column('allocated_rank', Integer), Column('allocated_project', Integer) ) metadata.create_all(engine) mapper(Student, students_table) Fairly simple, and for the most part I've been enjoying the ability to query almost any bit of information I want provided I avoid the error cases below. The class it is mapped from is: class Student(object): def __init__(self, sid, name): self.sid = sid self.name = name self.preferences = collections.defaultdict(set) self.allocated_project = None self.allocated_rank = 0 def __repr__(self): return str(self) def __str__(self): return "%s %s" %(self.sid, self.name) Explanation: preferences is basically a set of all the projects the student would prefer to be assigned. When the allocation algorithm kicks in, a student's allocated_project emerges from this preference set. Now if I try to do this: for student in students.itervalues(): session.add(student) session.commit() It throws two errors, one for the allocated_project column (seen below) and a similar error for the preferences column: sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding parameter 4 - probably unsupported type. u'INSERT INTO studs (sid, name, allocated_rank, allocated_project) VALUES (?, ?, ?, ?, ?, ?, ?)' [1101, 'Muffett,M.', 1, 888 Human-spider relationships (Supervisor id: 123)] If I go back into my code I find that, when I'm copying the preferences from the given text files, it actually refers to the Project class which is mapped to a dictionary, using the unique project id's (pid) as keys. Thus, as I iterate through each student via their rank and to the preferences set, it adds not a project id, but the reference to the project id from the projects dictionary. students[sid].preferences[int(rank)].add(projects[int(pid)]) Now this is very useful to me since I can find out all I want to about a student's preferred projects without having to run another check to pull up information about the project id. The form you see in the error has the object print information passed as: return "%s %s (Supervisor id: %s)" %(self.proj_id, self.proj_name, self.proj_sup) My questions are: I'm trying to store an object in a database field aren't I? Would the correct way then, be copying the project information (project id, name, etc) into its own table, referenced by the unique project id? That way I can just have the project id field for one of the student tables just be an integer id and when I need more information, just join the tables? So and so forth for other tables? If the above makes sense, then how does one maintain the relationship with a column of information in one table which is a key index on another table? Does this boil down into a database design problem? Are there any other elegant ways of accomplishing this? Apologies if this is a very long-winded question. It's rather crucial for me to solve this, so I've tried to explain as much as I can, whilst attempting to show that I'm trying (key word here sadly) to understand what could be going wrong.

    Read the article

  • Few doubts regarding Bitmaps , Images & `using` blocks

    - by imageWorker
    I caught up in this problem. http://stackoverflow.com/questions/2559826/garbage-collector-not-doing-its-job-memory-consumption-1-5gb-outofmemory-exc I feel that there is something wrong in my understanding. Please clarify these things. Destructor & IDisposable.Dispose are two methods for freeing resources that are not not under the control of .NET. Which means, everything except memory. right? using blocks are just better way of calling IDisposable.Dispose() method of an object. This is the main code I'm referring to. class someclass { static someMethod(Bitmap img) { Bitmap bmp = new Bitmap(img); //statement1 // some code here and return } } here is class I'm using for testing: class someotherClass { public static voide Main() { foreach (string imagePath in imagePathsArray) { using (Bitmap img1 = new Bitmap(imagePath)) { someclass.someMethod(img1); // does some more processing on `img1` } } } } Is there any memory leak with statement1? Question1: If each image size is say 10MB. Then does this bmp object occupy atleast 10MB? What I mean is, will it make completely new copy of entire image? or just refer to it? Question2:should I or should I not put the statement1 in using block? My Argument: We should not. Because using is not for freeing memory but for freeing the resources (file handle in this case). If I use it in using block. It closes file handle here encapsulated by this bmp object. It means we are also closing filehandle for the caller's img1 object. Which is not correct? As of the memory leak. No there is no scope of memory leak here. Because reference bmp is destroyed when this method is returned. Which leaves memory it refered without any pointer. So, its garbage collected. Am I right? Edit: class someclass { static Bitmap someMethod(Bitmap img) { Bitmap bmp = new Bitmap(img); //can I use `using` block on this enclosing `return bmp`; ??? // do some processing on bmp here return bmp; } }

    Read the article

  • How can i make a gallery with web images from my website?

    - by ronhdoge
    I currently have two codes that i am trying to figure out how to mix or write a new code to have a gallery with image doing fill_parent but i can slide sideways to see the other url linked images from my site. here are both parts of code i have: package com.mandarich.gallerygrid; import java.io.InputStream; import java.net.URL; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.ImageView; public class Gallery extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView =(ImageView)findViewById(R.id.ImageView01); Drawable drawable = LoadImageFromWebOperations("http://www.mandarichmodels.com/hot-pics/"); imgView.setImageDrawable(drawable); } private Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src name"); return d; }catch (Exception e) { System.out.println("Exc="+e); return null; } } } and here is my gallery code package com.mandarich.Grid; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class gridfinal extends Activity { private Gallery gallery; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); gallery.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("unchecked") public void onItemClick(AdapterView parent, View v, int position, long id) { // Displaying the position when the gallery item in clicked Toast.makeText(gridfinal.this, "Position=" + position, Toast.LENGTH_SHORT).show(); } }); } public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; // Adding images. private Integer[] Imgid = { R.drawable.cindy, R.drawable.clinton, R.drawable.colin, R.drawable.cybil, R.drawable.david, R.drawable.demi, R.drawable.drew }; public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); } public int getCount() { return Imgid.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); imgView.setImageResource(Imgid[position]); // Fixing width & height for image to display imgView.setLayoutParams(new Gallery.LayoutParams(430, 370)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg); return imgView; } } }

    Read the article

  • Error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException [migrated]

    - by user134212
    I'm new here. I'm learning how to program on java and I have a problem with my code. I really have no clue why my code is not working. I think my mistake may be here, but I'm not quite sure. m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); My Complete code import java.awt.*; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class Practica2 { private int opcion,ren2,col2; private JFrame ventana,ventanaPrintMatriz; private JPanel panel,panel2; private Border borderRed2,borderBlue2,borderGreen2,borderGreen4; private Color red,green,blue,white,black; private Font Verdana14,ArialBlack18; private JLabel labelTitulo; public JButton btSalir,btSumar,btRestar,btMultiplica,btTranspuesta,btCrear; private ImageIcon suma,resta,multi,crear,salir,trans; private boolean ventanaAbierta = false; private static ValidacionesMatrices valida; private static Operaciones operacion; private static Matriz m1,m2,m3; private static ImprimirMatriz printMat; public Practica2() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Operaciones con Matrices"); ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Sale del programa System.exit(0); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(150,150,300,380); //ventana.setBounds(0,0,650,650); } public void inicializarComponentes() { panel2 = new JPanel(); panel2.setLayout(null); labelTitulo = new JLabel("Practica #2"); suma = new ImageIcon("suma1.png"); resta = new ImageIcon("resta1.png"); multi = new ImageIcon("multi1.png"); trans = new ImageIcon("trans2.png"); crear = new ImageIcon("crear1.png"); salir = new ImageIcon("salir1.png"); btTranspuesta = new JButton("Transpuesta",trans); btMultiplica = new JButton("Multiplica",multi); btRestar = new JButton("Restar",resta); btSumar = new JButton("Sumar",suma); btCrear = new JButton("Crear",crear); btSalir = new JButton("Salir",salir); //Tipo de letra ArialBlack18 = new Font("Arial Black",Font.BOLD,18); //Color green = new Color(0,255,0); //Formato labelTitulo labelTitulo.setBounds(80,-60,200,150); labelTitulo.setFont(ArialBlack18); labelTitulo.setForeground(blue); labelTitulo.setVisible(true); //Formato de CrearMatriz btCrear.setBounds(80,50,130,30); btCrear.setToolTipText("Crea una matriz"); //Formato de Muliplica btMultiplica.setBounds(80,100,130,30); btMultiplica.setToolTipText("Mat[A] * Mat[B]"); //Formato de botonRestar btRestar.setBounds(80,150,130,30); btRestar.setToolTipText("Mat[A] - Mat[B]"); //Formato del botonSumar btSumar.setBounds(80,200,130,30); btSumar.setToolTipText("Mat[A] + Mat[B]"); //Formato de Transpuesta btTranspuesta.setBounds(80,250,130,30); btTranspuesta.setToolTipText("Mat[A]^-1"); //Formato del botonSalir btSalir.setBounds(80,300,130,30); //Agregando componentes al panel1 panel2.add(labelTitulo); panel2.add(btMultiplica); panel2.add(btCrear); panel2.add(btRestar); panel2.add(btSumar); panel2.add(btSalir); panel2.add(btTranspuesta); //Formato panel2 panel2.setBackground(green); panel2.setVisible(true); panel2.setBounds(0,0,300,380); //Argregamos componentes al panelPrincipal= panel.add(panel2); //BotonCrear btCrear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) //throws IOException { if(ventanaAbierta==false) { ventanaAbierta=true; new CrearMatriz(); } else { JOptionPane.showMessageDialog(null,"Ya se crearon las Matrices"); } } }); m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); //BotonSalir btSalir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); panel.setVisible(true); panel.setBounds(0,0,350,380); } class VentanaMatriz { private JFrame ventana; private JPanel panel; private JTextArea textArea1,textArea2; private JLabel mat1,mat2; private JTextField textField1; public VentanaMatriz() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Creacion de Matrices"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { ventana.dispose(); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(200,100,850,420); } public void inicializarComponentes() { //Colores black = new Color(0,0,0); white = new Color(255,255,255); blue = new Color(0,0,255); green = new Color(0,255,0); red = new Color(255,0,0); //Tipo de letra Verdana14 = new Font("Verdana",Font.BOLD,14); //Tipos de borde borderRed2 = BorderFactory.createLineBorder(red,2); borderBlue2 = BorderFactory.createLineBorder(blue,2); borderGreen2 = BorderFactory.createLineBorder(green,2); borderGreen4 = BorderFactory.createLineBorder(green,4); //Agregando componentes al panel1 panel.add(mat1); panel.add(textArea1); panel.add(mat2); panel.add(textArea2); //Formato panel2 panel.setBackground(blue); panel.setVisible(true); panel.setBounds(0,0,850,420); } } class CrearMatriz { public int col1,re1,ren2,col2; public Matriz m1,m2,m3; public CrearMatriz() { int col1,ren1,ren2,col2; ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz A: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz A: ")); final Matriz m1= new Matriz(ren2,col2); ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz B: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz B: ")); final Matriz m2= new Matriz(ren2,col2); m3 = new Matriz(ren2,col2); m1.llenarMatriz(); m2.llenarMatriz(); m1.printMat(); m2.printMat(); } public void SUMA(Matriz m1,Matriz m2) { Matriz m3; if(ventanaAbierta==false) { m3 = new Matriz(ren2,col2); if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } } } public void RESTA() { } //btSumar = new JButton("Sumar",suma); //BotonSumar //Mostrar matriz 1 y 2 // System.out.println("\n\n\nMatriz 1="); // m1.imprimeMatriz(); // System.out.println("\nMatriz 2="); //Poner en botones /* if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } if(valida.validaSumayResta(m1,m2)) { m3=operacion.restaMat(m1,m2); JOptionPane.showMessageDialog(null,"La resta es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la resta"); } if(valida.validaMultiplicacion(m1,m2)){ m3=operacion.multiplicaMat(m1,m2); JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la multiplicacion"); } JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m1=operacion.transpuesta(m1); m2=operacion.transpuesta(m2); */ } class Matriz { public JTextField matriz; //public JTextArea texto; private JFrame ventanaPrintMatriz; private JPanel panel2; int ren; int col; int pos[][]; public Matriz(int ren1, int col1) { ren = ren1; col = col1; pos = new int [ren][col];/*una matriz de enteros de renglon por columan*/ } public void llenarMatriz() { for(int i=0;i<ren;i++) for(int j=0;j<col;j++) pos[i][j]=(int) (Math.random()*10);/*la posicion i y j crea un entero random*/ } /*vuelve a recorrer los espacio de i y j*/ } //Esta clase era un metodo de CrearMatriz class ImprimirMatriz { public void ImprimirMatriz() { panel2 = new JPanel(); panel2.setLayout(null); ventanaPrintMatriz = new JFrame("Matriz"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Practica2.ventanaAbierta=false; ventana.dispose(); } }); int i,j; int x=0,y=0; borderRed2 = BorderFactory.createLineBorder(red,2); white = new Color(255,255,255); red = new Color(255,0,0); black = new Color(0,0,0); blue = new Color(0,0,255); for(i=0;i<ren;i++) { for(j=0;j<col;j++) { matriz = new JTextField(" "+pos[i][j]); matriz.setBorder(borderRed2); matriz.setForeground(white); matriz.setBounds(x+25,y+25,25,25); matriz.setBackground(black); matriz.setEditable(false); matriz.setVisible(true); //Se incrementa la coordenada en X //para el siguiente Textfield no se encime x=x+35; //Agregamos el textField al panel panel2.add(matriz); } //Regreso las cordenadas de X a 0 para que el //siguiente renglon empieze en donde mismo x=0; //Incremento las coordenada Y para que se brinque //de linea y=y+35; } //Formato panel2 panel2.setBounds(150,150,350,380); panel2.setBackground(blue); //panel2.setEditable(false); panel2.setVisible(true); //Formato de Ventana ventanaPrintMatriz.setContentPane(panel2); ventanaPrintMatriz.setBounds(150,150,350,380); ventanaPrintMatriz.setResizable(false); ventanaPrintMatriz.setVisible(true); } } class Operaciones { public Matriz sumaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]+m2.pos[i][j]; return m3; } public Matriz restaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]-m2.pos[i][j]; return m3; } public Matriz multiplicaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m2.col); for(int i=0;i<m1.ren;i++) for(int j=0;j<m2.col;j++) { m3.pos[i][j]=0; for(int k=0;k<m1.col;k++) m3.pos[i][j]+=(m1.pos[i][k]*m2.pos[k][j]); } return m3; } public Matriz transpuesta(Matriz m1) { Matriz m3=new Matriz(m1.col,m1.ren); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[j][i]; return m3; } } class ValidacionesMatrices { public boolean validaSumayResta(Matriz m1, Matriz m2) { if((m1.ren==m2.ren) && (m1.col==m2.col)) return true; else return false; } public boolean validaMultiplicacion(Matriz m1, Matriz m2) { if(((m1.ren==m2.ren) && (m1.col==m2.col)) || (m1.col==m2.ren)) return true; else return false; } } public static void main(String[] args) { Practica2 practica2 = new Practica2(); practica2.inicializarComponentes(); } } Exc

    Read the article

  • running multi threads in Java

    - by owca
    My task is to simulate activity of couple of persons. Each of them has few activities to perform in some random time: fast (0-5s), medium(5-10s), slow(10-20s) and very slow(20-30s). Each person performs its task independently in the same time. At the beginning of new task I should print it's random time, start the task and then after time passes show next task's time and start it. I've written run() function that counts time, but now it looks like threads are done one after another and not in the same time or maybe they're just printed in this way. public class People{ public static void main(String[] args){ Task tasksA[]={new Task("washing","fast"), new Task("reading","slow"), new Task("shopping","medium")}; Task tasksM[]={new Task("sleeping zzzzzzzzzz","very slow"), new Task("learning","slow"), new Task(" :** ","slow"), new Task("passing an exam","slow") }; Task tasksJ[]={new Task("listening music","medium"), new Task("doing nothing","slow"), new Task("walking","medium") }; BusyPerson friends[]={ new BusyPerson("Alice",tasksA), new BusyPerson("Mark",tasksM), new BusyPerson("John",tasksJ)}; System.out.println("STARTING....................."); for(BusyPerson f: friends) (new Thread(f)).start(); System.out.println("DONE........................."); } } class Task { private String task; private int time; private Task[]tasks; public Task(String t, String s){ task = t; Speed speed = new Speed(); time = speed.getSpeed(s); } public Task(Task[]tab){ Task[]table=new Task[tab.length]; for(int i=0; i < tab.length; i++){ table[i] = tab[i]; } this.tasks = table; } } class Speed { private static String[]hows = {"fast","medium","slow","very slow"}; private static int[]maxs = {5000, 10000, 20000, 30000}; public Speed(){ } public static int getSpeed( String speedString){ String s = speedString; int up_limit=0; int down_limit=0; int time=0; //get limits of time for(int i=0; i<hows.length; i++){ if(s.equals(hows[i])){ up_limit = maxs[i]; if(i>0){ down_limit = maxs[i-1]; } else{ down_limit = 0; } } } //get random time within the limits Random rand = new Random(); time = rand.nextInt(up_limit) + down_limit; return time; } } class BusyPerson implements Runnable { private String name; private Task[] person_tasks; private BusyPerson[]persons; public BusyPerson(String s, Task[]t){ name = s; person_tasks = t; } public BusyPerson(BusyPerson[]tab){ BusyPerson[]table=new BusyPerson[tab.length]; for(int i=0; i < tab.length; i++){ table[i] = tab[i]; } this.persons = table; } public void run() { int time = 0; double t1=0; for(Task t: person_tasks){ t1 = (double)t.time/1000; System.out.println(name+" is... "+t.task+" "+t.speed+ " ("+t1+" sec)"); while (time == t.time) { try { Thread.sleep(10); } catch(InterruptedException exc) { System.out.println("End of thread."); return; } time = time + 100; } } } } And my output : STARTING..................... DONE......................... Mark is... sleeping zzzzzzzzzz very slow (36.715 sec) Mark is... learning slow (10.117 sec) Mark is... :** slow (29.543 sec) Mark is... passing an exam slow (23.429 sec) Alice is... washing fast (1.209 sec) Alice is... reading slow (23.21 sec) Alice is... shopping medium (11.237 sec) John is... listening music medium (8.263 sec) John is... doing nothing slow (13.576 sec) John is... walking medium (11.322 sec) Whilst it should be like this : STARTING..................... DONE......................... John is... listening music medium (7.05 sec) Alice is... washing fast (3.268 sec) Mark is... sleeping zzzzzzzzzz very slow (23.71 sec) Alice is... reading slow (15.516 sec) John is... doing nothing slow (13.692 sec) Alice is... shopping medium (8.371 sec) Mark is... learning slow (13.904 sec) John is... walking medium (5.172 sec) Mark is... :** slow (12.322 sec) Mark is... passing an exam very slow (27.1 sec)

    Read the article

  • Intent and OnActivityResult causing Activity to get restart Actuomatically : Require to solve this issues

    - by Parth Dani
    i am having 20 imageview and i am having 20 button for them when i click any 1 button it gives me option to select image from gallery or camera when i select any option for example galley it will take me to the gallery and let me select image from their and let me display those images on my imageview for respective button now the problem is sometimes when i do the whole above process my activity is getting restart actuomatically and all the image which were first selected get vanished from their imageview For Refernce my code is as follow: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_upload); // **************Code to get Road worthy number and VIN number value in // Shared Preference starts here************************ SharedPreferences myPrefs1 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); roadworthynumber = myPrefs1.getString(MY_ROADWORTHY, "Road Worthy Number"); vinnumber = myPrefs1.getString(MY_VIN, "VIN Number"); // **************Code to get Road worthy number and VIN number value in // Shared Preference ends here************************ // **************Code to create Directory AUSRWC starts // here************************ if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "AUSRWC" + File.separator); cacheDir.mkdirs(); } // **************Code to Create Directory AUSRWC ends // here************************ // *****************Assigning Button variable their Id declare in XML // file starts here***************** new_select1 = (Button) findViewById(R.id.new_select1); new_select2 = (Button) findViewById(R.id.new_select2); new_select3 = (Button) findViewById(R.id.new_select3); new_select4 = (Button) findViewById(R.id.new_select4); new_select5 = (Button) findViewById(R.id.new_select5); new_select6 = (Button) findViewById(R.id.new_select6); new_select7 = (Button) findViewById(R.id.new_select7); new_select8 = (Button) findViewById(R.id.new_select8); new_select9 = (Button) findViewById(R.id.new_select9); new_select10 = (Button) findViewById(R.id.new_select10); new_select11 = (Button) findViewById(R.id.new_select11); new_select12 = (Button) findViewById(R.id.new_select12); new_select13 = (Button) findViewById(R.id.new_select13); new_select14 = (Button) findViewById(R.id.new_select14); new_select15 = (Button) findViewById(R.id.new_select15); new_select16 = (Button) findViewById(R.id.new_select16); new_select17 = (Button) findViewById(R.id.new_select17); new_select18 = (Button) findViewById(R.id.new_select18); new_select19 = (Button) findViewById(R.id.new_select19); new_select20 = (Button) findViewById(R.id.new_select20); // *****************Assigning Button variable their Id declare in XML // file ends here***************** // *****************Assigning Image variable their Id declare in XML // file starts here***************** new_selectimage1 = (ImageView) findViewById(R.id.new_selectImage1); new_selectimage2 = (ImageView) findViewById(R.id.new_selectImage2); new_selectimage3 = (ImageView) findViewById(R.id.new_selectImage3); new_selectimage4 = (ImageView) findViewById(R.id.new_selectImage4); new_selectimage5 = (ImageView) findViewById(R.id.new_selectImage5); new_selectimage6 = (ImageView) findViewById(R.id.new_selectImage6); new_selectimage7 = (ImageView) findViewById(R.id.new_selectImage7); new_selectimage8 = (ImageView) findViewById(R.id.new_selectImage8); new_selectimage9 = (ImageView) findViewById(R.id.new_selectImage9); new_selectimage10 = (ImageView) findViewById(R.id.new_selectImage10); new_selectimage11 = (ImageView) findViewById(R.id.new_selectImage11); new_selectimage12 = (ImageView) findViewById(R.id.new_selectImage12); new_selectimage13 = (ImageView) findViewById(R.id.new_selectImage13); new_selectimage14 = (ImageView) findViewById(R.id.new_selectImage14); new_selectimage15 = (ImageView) findViewById(R.id.new_selectImage15); new_selectimage16 = (ImageView) findViewById(R.id.new_selectImage16); new_selectimage17 = (ImageView) findViewById(R.id.new_selectImage17); new_selectimage18 = (ImageView) findViewById(R.id.new_selectImage18); new_selectimage19 = (ImageView) findViewById(R.id.new_selectImage19); new_selectimage20 = (ImageView) findViewById(R.id.new_selectImage20); // ****Assigning Image variable their Id declare in XML file ends // here***************** // **************Creating Dialog to give option to user to new_select // image from gallery or from camera starts here**************** final String[] items = new String[] { "From Camera", "From Gallery" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("select Image"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { if (android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED)) { Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Environment .getExternalStorageDirectory(), "/AUSRWC/picture" + ".jpg"); mImageCaptureUri = Uri.fromFile(file); try { Toast.makeText(getBaseContext(), "Click Image", Toast.LENGTH_SHORT).show(); intent.putExtra( android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); intent.putExtra("return-data", true); startActivityForResult(intent, PICK_FROM_CAMERA); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } dialog.cancel(); } else { Intent intent = new Intent(); Toast.makeText(getBaseContext(), "Select Image", Toast.LENGTH_SHORT).show(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE); } } }); dialog = builder.create(); // **************Creating Dialog to give option to user to new_select // image from gallery or from camera ends here**************** final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha); // Animation Code for displaying Button // Clicked. // ********************Image 1 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 1; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 1 button code ends // here******************************* // ********************Image 2 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 2; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 2 button code ends // here******************************* // ********************Image 3 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 3; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 3 button code ends // here******************************* // ********************Image 4 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 4; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 4 button code ends // here******************************* // ********************Image 5 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select5.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 5; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 5 button code ends // here******************************* // ********************Image 6 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select6.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 6; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 6 button code ends // here******************************* // ********************Image 7 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select7.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 7; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 7 button code ends // here******************************* // ********************Image 8 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select8.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 8; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 8 button code ends // here******************************* // ********************Image 9 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select9.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 9; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 9 button code ends // here******************************* // ********************Image 10 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select10.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 10; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 10 button code ends // here******************************* // ********************Image 11 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select11.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 11; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 11 button code ends // here******************************* // ********************Image 12 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select12.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 12; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 12 button code ends // here******************************* // ********************Image 13 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select13.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 13; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 13 button code ends // here******************************* // ********************Image 14 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select14.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 14; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 14 button code ends // here******************************* // ********************Image 15 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select15.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 15; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 15 button code ends // here******************************* // ********************Image 16 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select16.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 16; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 16 button code ends // here******************************* // ********************Image 17 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select17.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 17; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 17 button code ends // here******************************* // ********************Image 18 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select18.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 18; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 18 button code ends // here******************************* // ********************Image 19 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select19.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 19; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 19 button code ends // here******************************* // ********************Image 20 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select20.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 20; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 20 button code ends // here******************************* } // *************************When Back Button is Pressed code begins // here************************************* @Override public void onBackPressed() { Toast.makeText(new_upload.this, "Sorry You are not allowed to go back", Toast.LENGTH_SHORT).show(); return; } // *************************When Back Button is Pressed code ends // here************************************* // ***********************To get Path of new_selected Image code starts // here************************************ public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); if (cursor == null) return null; int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } // ***********************To get Path of new_selected Image code ends // here************************************ // **********************Picture obtained from the camera or from gallery // code starts here************** @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //path = ""; Log.e("","requestCode="+requestCode); switch (requestCode){ case PICK_FROM_FILE: if (resultCode == Activity.RESULT_OK) { mImageCaptureUri = data.getData(); path = getRealPathFromURI(mImageCaptureUri); // from Gallery Log.e("", "Imagepath from gallery=" + path); if (path == null) path = mImageCaptureUri.getPath(); // from File Manager if (path != null) { dialog1 = ProgressDialog.show(new_upload.this, "", "Processing Please wait...", true); new ImageDisplayTask().execute(); } } break; case PICK_FROM_CAMERA: if (resultCode == Activity.RESULT_OK) { try { path = mImageCaptureUri.getPath(); Log.e("", "Imagepath from Camera =" + path); // bitmap = BitmapFactory.decodeFile(path); } catch (Exception e) { e.printStackTrace(); } if (path != null) { dialog1 = ProgressDialog.show(new_upload.this, "", "Processing Please wait...", true); //new ImageDisplayTask1().execute(); new ImageDisplayTask().execute(); } } break; default: } } // ********************Picture obtained from the camera or from gallery code // ends here********************************************* // ******************Image Display on Button when new_selected from gallery // Ashynch Code starts here******************************** class ImageDisplayTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... unsued) { Bitmap src = BitmapFactory.decodeFile(path); Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); //Bitmap dest = Bitmap.createScaledBitmap(src, src.getWidth(),src.getHeight(), true); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local `` String timestamp = dateTime + " " + roadworthynumber; SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String dateTime1 = sdf1.format(Calendar.getInstance().getTime()); Imagename = dateTime1.toString().trim().replaceAll(":", "") .replaceAll("-", "").replaceAll(" ", "") + roadworthynumber + ".jpg"; Canvas cs = new Canvas(dest); Paint tPaint = new Paint(); tPaint.setTextSize(100); tPaint.setTypeface(Typeface.SERIF); tPaint.setColor(Color.RED); tPaint.setStyle(Style.FILL); cs.drawBitmap(src, 0f, 0f, null); float height = tPaint.measureText("yY"); cs.drawText(timestamp, 5f, src.getHeight() - height + 5f, tPaint); try { dest.compress(Bitmap.CompressFormat.JPEG, 70, new FileOutputStream(new File(cacheDir, Imagename))); dest.recycle(); src.recycle(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Void... unsued) { } @Override protected void onPostExecute(String serverresponse) { String error = "noerror"; Display currentDisplay = getWindowManager().getDefaultDisplay(); int dw = currentDisplay.getWidth(); int dh = currentDisplay.getHeight() - 100; Log.e("", "width= " + dw + " Height= " + dh); try { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/AUSRWC/" + Imagename, bmpFactoryOptions); int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh); int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw); if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { bmpFactoryOptions.inSampleSize = heightRatio; } else { bmpFactoryOptions.inSampleSize = widthRatio; } } bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/AUSRWC/" + Imagename, bmpFactoryOptions); if (buttonpressed == 1) { new_selectimage1.setImageBitmap(bmp); //Image set on ImageView } else if (buttonpressed == 2) { new_selectimage2.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 3) { new_selectimage3.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 4) { new_selectimage4.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 5) { new_selectimage5.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 6) { new_selectimage6.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 7) { new_selectimage7.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 8) { new_selectimage8.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 9) { new_selectimage9.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 10) { new_selectimage10.setImageBitmap(bmp); } else if (buttonpressed == 11) { new_selectimage11.setImageBitmap(bmp); } else if (buttonpressed == 12) { new_selectimage12.setImageBitmap(bmp); } else if (buttonpressed == 13) { new_selectimage13.setImageBitmap(bmp); } else if (buttonpressed == 14) { new_selectimage14.setImageBitmap(bmp); } else if (buttonpressed == 15) { new_selectimage15.setImageBitmap(bmp); } else if (buttonpressed == 16) { new_selectimage16.setImageBitmap(bmp); } else if (buttonpressed == 17) { new_selectimage17.setImageBitmap(bmp); } else if (buttonpressed == 18) { new_selectimage18.setImageBitmap(bmp); } else if (buttonpressed == 19) { new_selectimage19.setImageBitmap(bmp); } else if (buttonpressed == 20) { new_selectimage20.setImageBitmap(bmp); } } catch (Exc

    Read the article

< Previous Page | 4 5 6 7 8