Search Results

Search found 34141 results on 1366 pages for 'even mien'.

Page 15/1366 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Laravel4: Checking many-to-many relationship attribute even when it does not exist

    - by Simo A.
    This is my first time with Laravel and also Stackoverflow... I am developing a simple course management system. The main objects are User and Course, with a many-to-many relationship between them. The pivot table has an additional attribute, participant_role, which defines whether the user is a student or an instructor within that particular course. class Course extends Eloquent { public function users() { return $this->belongsToMany('User')->withPivot('participant_role')->withTimestamps(); } } However, there is an additional role, system admin, which can be defined on the User object. And this brings me mucho headache. In my blade view I have the following: @if ($course->pivot->participant_role == 'instructor') { // do something here... } This works fine when the user has been assigned to that particular $course and there is an entry for this user-course combination in the pivot table. However, the problem is the system administrator, who also should be able to access course details. The if-clause above gives Trying to get property of non-object error, apparently because there is no entry in the pivot table for system administrator (as the role is defined within the User object). I could probably solve the problem by using some off-the-shelf bundle for handling role-based permissions. Or I could (but don't want to) do something like this with two internal if-clauses: if (!empty($course->pivot)) { if ($course->pivot->participant_role == 'instructor') { // do something... } } Other options (suggested in partially similar entries in Stackoverflow) would include 1) reading all the pivot table entries to an array, and use in_array to check if a role exists, or even 2) SQL left join to do this on database level. However, ultimately I am looking for a compact one-line solution? Can I do anything similar to this, which unfortunately does not seem to work? if (! empty ($course->pivot->participant_role == 'instructor') ) { // do something... } The shorter the answer, the better :-). Thanks a lot!

    Read the article

  • Why is this ajax call being made even though it shouldn't be

    - by user2921557
    i have this validation script im working on but cant see why im having an issue. You can see that i have a check = false / true, check before it runs the ajax call. However, even if a field is empty and check is set to false, it is still running the call. so: // JavaScript - Update Password AJAX $(document).ready(function () { // When the form is submitted $('.updatepasswordform').submit(function () { var check = true; // Get the values var password1 = $("input[name=password1]").val(); var password2 = $("input[name=password2]").val(); var newpassword = $("input[name=newpassword]").val(); /* Password Validation */ // If fields are empty if (password1 === '') { check = false; $("input[name=password1]").css('border', 'solid 2px red'); } // If fields are empty if (password2 === '') { check = false; $("input[name=password2]").css('border', 'solid 2px red'); } // If fields are empty if (newpassword === '') { check = false; $("input[name=newpassword]").css('border', 'solid 2px red'); } if (check = true) { $.ajax({ type: "POST", url: "process/updatepassword.php", data: $(".updatepasswordform").serialize(), dataType: "json", success: function (response) { /* Checks for database validation, removed for space saving */ } }); } return false; }); });

    Read the article

  • Infinite loop using Spring Security - Login page is protected even though it should allow anonymous

    - by Tai Squared
    I have a Spring application (Spring version 2.5.6.SEC01, Spring Security version 2.0.5) with the following setup: web.xml <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> The index.jsp page is in the WebContent directory and simply contains a redirect: <c:redirect url="/login.htm"/> In the appname-servlet.xml, there is a view resolver to point to the jsp pages in WEB-INF/jsp <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> In the security-config.xml file, I have the following configuration: <http> <!-- Restrict URLs based on role --> <intercept-url pattern="/WEB-INF/jsp/login.jsp*" access="ROLE_ANONYMOUS" /> <intercept-url pattern="/WEB-INF/jsp/header.jsp*" access="ROLE_ANONYMOUS" /> <intercept-url pattern="/WEB-INF/jsp/footer.jsp*" access="ROLE_ANONYMOUS" /> <intercept-url pattern="/login*" access="ROLE_ANONYMOUS" /> <intercept-url pattern="/index.jsp" access="ROLE_ANONYMOUS" /> <intercept-url pattern="/logoutSuccess*" access="ROLE_ANONYMOUS" /> <intercept-url pattern="/css/**" filters="none" /> <intercept-url pattern="/images/**" filters="none" /> <intercept-url pattern="/**" access="ROLE_ANONYMOUS" /> <form-login login-page="/login.jsp"/> </http> <authentication-provider> <jdbc-user-service data-source-ref="dataSource" /> </authentication-provider> However, I can't even navigate to the login page and get the following error in the log: WARNING: The login page is being protected by the filter chain, but you don't appear to have anonymous authentication enabled. This is almost certainly an error. I've tried changing the ROLE_ANONYMOUS to IS_AUTHENTICATED_ANONYMOUSLY, changing the login-page to index.jsp, login.htm, and adding different intercept-url values, but I can't get it so the login page is accesible and security applies to the other pages. What do I have to change to avoid this loop?

    Read the article

  • ArrayAdapter need to be clear even i am creating a new one

    - by Roi
    Hello I'm having problems understanding how the ArrayAdapter works. My code is working but I dont know how.(http://amy-mac.com/images/2013/code_meme.jpg) I have my activity, inside it i have 2 private classes.: public class MainActivity extends Activity { ... private void SomePrivateMethod(){ autoCompleteTextView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>(Arrays.asList("")))); autoCompleteTextView.addTextChangedListener(new MyTextWatcher()); } ... private class MyTextWatcher implements TextWatcher { ... } private class SearchAddressTask extends AsyncTask<String, Void, String[]> { ... } } Now inside my textwatcher class i call the search address task: @Override public void afterTextChanged(Editable s) { new SearchAddressTask().execute(s.toString()); } So far so good. In my SearchAddressTask I do some stuff on doInBackground() that returns the right array. On the onPostExecute() method i try to just modify the AutoCompleteTextView adapter to add the values from the array obtained in doInBackground() but the adapter cannot be modified: NOT WORKING CODE: protected void onPostExecute(String[] addressArray) { ArrayAdapter<String> adapter = (ArrayAdapter<String>) autoCompleteDestination.getAdapter(); adapter.clear(); adapter.addAll(new ArrayList<String>(Arrays.asList(addressArray))); adapter.notifyDataSetChanged(); Log.d("SearchAddressTask", "adapter isEmpty : " + adapter.isEmpty()); // Returns true!!??! } I dont get why this is not working. Even if i run it on UI Thread... I kept investigating, if i recreate the arrayAdapter, is working in the UI (Showing the suggestions), but i still need to clear the old adapter: WORKING CODE: protected void onPostExecute(String[] addressArray) { ArrayAdapter<String> adapter = (ArrayAdapter<String>) autoCompleteDestination.getAdapter(); adapter.clear(); autoCompleteDestination.setAdapter(new ArrayAdapter<String>(NewDestinationActivity.this,android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>(Arrays.asList(addressArray)))); //adapter.notifyDataSetChanged(); // no needed Log.d("SearchAddressTask", "adapter isEmpty : " + adapter.isEmpty()); // keeps returning true!!??! } So my question is, what is really happening with this ArrayAdapter? why I cannot modify it in my onPostExecute()? Why is working in the UI if i am recreating the adapter? and why i need to clear the old adapter then? I dont know there are so many questions that I need some help in here!! Thanks!!

    Read the article

  • Cached ObjectDataSource not firing Select Event even Cache Dependecy Removed

    - by John Polvora
    I have the following scenario. A Page with a DetailsView binded to an ObjectDatasource with cache-enabled. The SelectMethod is assigned at Page_Load event, depending on my User Level Logic. After assigned the selectMethod and Parameters for the ODS, if Cache not exists, then ODS will be cached the first time. The next time, the cache will be applied to the ODS and the select event don't need to be fired since the dataresult is cached. The problem is, the ODS Cache works fine, but I have a Refresh button to clear the cache and rebind the DetailsView. Am I doing correctly ? Below is my code. <asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="ObjectDataSource_Summary" EnableModelValidation="True" EnableViewState="False" ForeColor="#333333" GridLines="None"> </asp:DetailsView> <asp:ObjectDataSource ID="ObjectDataSource_Summary" runat="server" SelectMethod="" TypeName="BL.BusinessLogic" EnableCaching="true"> <SelectParameters> <asp:Parameter Name="idCompany" Type="String" /> <SelectParameters> </asp:ObjectDataSource> <asp:ImageButton ID="ImageButton_Refresh" runat="server" OnClick="RefreshClick" ImageUrl="~/img/refresh.png" /> And here is the code behind public partial class Index : Page { protected void Page_Load(object sender, EventArgs e) { ObjectDataSource_Summary.SelectMethod = ""; ObjectDataSource_Summary.SelectParameters[0].DefaultValue = ""; switch (this._loginData.UserLevel) //this is a struct I use for control permissions e pages behaviour { case OperNivel.SysAdmin: case OperNivel.SysOperator: { ObjectDataSource_Summary.SelectMethod = "SystemSummary"; ObjectDataSource_Summary.SelectParameters[0].DefaultValue = "0"; break; } case OperNivel.CompanyAdmin: case OperNivel.CompanyOperator: { ObjectDataSource_Summary.SelectMethod = "CompanySummary"; ObjectDataSource_Summary.SelectParameters[0].DefaultValue = this._loginData.UserLevel.ToString(); break; } default: break; } } protected void Page_LoadComplete(object sender, EventArgs e) { if (Cache[ObjectDataSource_Summary.CacheKeyDependency] == null) { this._loginData.LoginDatetime = DateTime.Now; Session["loginData"] = _loginData; Cache[ObjectDataSource_Summary.CacheKeyDependency] = _loginData; DetailsView1.DataBind(); } } protected void RefreshClick(object sender, ImageClickEventArgs e) { Cache.Remove(ObjectDataSource_Summary.CacheKeyDependency); } } Can anyone help me? The Select() Event of the ObjectDasource is not firing even I Remove the CacheKey Dependency

    Read the article

  • JLabel not displaying all the characters even after dynamically changing font size

    - by wniroshan
    Hi all, I am trying to fit a sentence that changes often, in to a few jlabels. Widths of my 3 jlabels stay unchanged all the time. What I am doing is changing the font size so all the characters can fit with out non being out of the display range of the labels. What I do is call below code snippet when ever sentence is changed. Here is my code String sentence = "Some long sentence"; int SentenceLength = sentence.length(); int FontSize = 0; // sum of widths of the three labels int TotalLblLength=lbl_0ValueInWords.getWidth()+lbl_1ValueInWords.getWidth()+lbl_1ValueInWords.getWidth(); /*decide the font size so that all the characters can be displayed with out exceeding the display renge(horizontal) of the 3 labels Inconsolata -> monopace font font size == width of the font*2 (something I observed, not sure if this is true always) */ FontSize=(TotalLblLength/SentenceLength)*2; // max font size is 20 - based on label height FontSize=(FontSize>20)?20:FontSize; lbl_0ValueInWords.setFont(new java.awt.Font("Inconsolata", 0,FontSize)); lbl_1ValueInWords.setFont(new java.awt.Font("Inconsolata", 0,FontSize)); lbl_2ValueInWords.setFont(new java.awt.Font("Inconsolata", 0,FontSize)); int CharCount_lbl0 = width_lbl0 / (FontSize / 2); int CharCount_lbl1 = width_lbl1 / (FontSize / 2); int CharsCount_lbl2 = width_lbl2 / (FontSize / 2); /*Set texts of each label if sentence has more than the number of characters that can fit in the 1st label, excessive characters are moved to the 2nd label. same goes for the 2nd and 3rd labels*/ if (SentenceLength > CharCount_lbl0) { lbl_0ValueInWords.setText(sentence.substring(0, CharCount_lbl0)); if (SentenceLength > CharCount_lbl0 + CharCount_lbl1) { lbl_1ValueInWords.setText(sentence.substring(CharCount_lbl0, CharCount_lbl0 + CharCount_lbl1)); lbl_2ValueInWords.setText(sentence.substring(CharCount_lbl0 + CharCount_lbl1, SentenceLength)); } else { lbl_1ValueInWords.setText(sentence.substring(CharCount_lbl0, SentenceLength)); } } else { lbl_0ValueInWords.setText(sentence); } But even after resetting font size sometimes the last character goes out of the display range. I have removed margines from the jlabels that may cause this. This happens for random length sentences. I can solve the problem for the application by reducing label width used for the calculations(hopefully) Can anyone explain me the reason? Could be because of some defect in the fonts symmetry?

    Read the article

  • JS regex isn't matching, even thought it works with a regex tester

    - by Tom O
    I'm writing a piece of client-side javascript code that takes a function and finds the derivative of it, however, the regex that's supposed to match with the power rule fails to work in the context of the javascript program, even though it sucessfully matches when it's used with an independent regex tester. The browser I'm executing this on is Midori, and the operating system is Ubuntu 10.04 (Lucid Lynx). Here's the HTML page being used as the interface in addition to the code: Page: <html> <head> <title> Derivative Calculator </title> <script type="text/javascript" src="derivative.js"> </script> <body> <form action="" name=form> <input type=text name=f /> with respects to <input type=text name=vr size=7 /> <input type=button value="Derive!" onClick="main(this.form)" /> <br /> <input type=text name=result value="" /> </form> </body> </html> derivative.js: function main(form) { form.result.value = derive(form.f.value, form.vr.value); } function derive(f, v) { var atom = []; atom["sin(" + v + ")"] = "cos(" + v + ")"; atom["cos(" + v + ")"] = "-sin(" + v + ")"; atom["tan(" + v + ")"] = "sec^(2)(" + v + ")"; atom["sec(" + v + ")"] = "sec(" + v + ")*tan(" + v + ")"; atom["1/(cos(" + v + "))"] = "sec(" + v + ")*tan(" + v + ")"; atom["csc(" + v + ")"] = "-csc(" + v + ")*cot(" + v + ")"; atom["1/(sin(" + v + "))"] = "-csc(" + v + ")*cot(" + v + ")"; atom["cot(" + v + ")"] = "-csc^(2)(" + v + ")"; atom["1/(tan(" + v + "))"] = "-csc^(2)(" + v + ")"; atom["sin^(-1)(" + v + ")"] = "1/sqrt(1 - " + v + "^(2))"; atom["arcsin(" + v + ")"] = "1/sqrt(1 - " + v + "^(2))"; atom["cos^(-1)(" + v + ")"] = "-1/sqrt(1 - " + v + "^(2))"; atom["arccos(" + v + ")"] = "-1/sqrt(1 - " + v + "^(2))"; atom["tan^(-1)(" + v + ")"] = "1/(1 + " + v + "^(2))"; atom["arctan(" + v + ")"] = "1/(1 + " + v + "^(2))"; atom["sec^(-1)(" + v + ")"] = "1/(|" + v + "|*sqrt(" + v + "^(2) - 1))"; atom["arcsec(" + v + ")"] = "1/(|" + v + "|*sqrt(" + v + "^(2) - 1))"; atom["csc^(-1)(" + v + ")"] = "-1/(|" + v + "|*sqrt(" + v + "^(2) - 1))"; atom["arccsc(" + v + ")"] = "-1/(|" + v + "|*sqrt(" + v + "^(2) - 1))"; atom["cot^(-1)(" + v + ")"] = "-1/(1 + " + v + "^(2))"; atom["arccot(" + v + ")"] = "-1/(1 + " + v + "^(2))"; atom["ln(" + v + ")"] = "1/(" + v + ")"; atom["e^(" + v + ")"] = "e^(" + v + ")"; atom["ln(|" + v + "|)"] = "1/(" + v + ")"; atom[v] = "1"; var match = ""; if (new Boolean(atom[f]) == true) { return atom[f]; } else if (f.match(/^[0-9]+$/)) { return ""; } else if (f.match(/([\S]+)([\s]+)\+([\s]+)([\S]+)/)) { match = /([\S]+)([\s]+)\+([\s]+)([\S]+)/.exec(f); return derive(match[1], v) + " + " + derive(match[4], v); } else if (f.match(new RegExp("^([0-9]+)(" + v + ")$"))) { match = new RegExp("^([0-9]+)(" + v + ")$").exec(f); return match[1]; } else if (f.match(new RegExp("^([0-9]+)(" + v + ")\^([0-9]+)$"))) { match = new RegExp("^([0-9]+)(" + v + ")\^([0-9]+)$").exec(f); return String((match[1] * (match[3] - 1))) + v + "^" + String(match[3] - 1); } else { return "?"; } }

    Read the article

  • Visual Studio reports that not all code path return a value, even though they do

    - by chris12892
    I have an API in NETMF C# that I am writing that includes a function to send an HTTP request. For those who are familiar with NETMF, this is a heavily modified version of the "webClient" example, which a simple application that demonstrates how to submit an HTTP request, and recive a response. In the sample, it simply prints the response and returns void,. In my version, however, I need it to return the HTTP response. For some reason, Visual Studio reports that not all code paths return a value, even though, as far as I can tell, they do. Here is my code... /// <summary> /// This is a modified webClient /// </summary> /// <param name="url"></param> private string httpRequest(string url) { // Create an HTTP Web request. HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; // Set request.KeepAlive to use a persistent connection. request.KeepAlive = true; // Get a response from the server. WebResponse resp = request.GetResponse(); // Get the network response stream to read the page data. if (resp != null) { Stream respStream = resp.GetResponseStream(); string page = ""; byte[] byteData = new byte[4096]; char[] charData = new char[4096]; int bytesRead = 0; Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder(); int totalBytes = 0; // allow 5 seconds for reading the stream respStream.ReadTimeout = 5000; // If we know the content length, read exactly that amount of // data; otherwise, read until there is nothing left to read. if (resp.ContentLength != -1) { for (int dataRem = (int)resp.ContentLength; dataRem > 0; ) { Thread.Sleep(500); bytesRead = respStream.Read(byteData, 0, byteData.Length); if (bytesRead == 0) throw new Exception("Data laes than expected"); dataRem -= bytesRead; // Convert from bytes to chars, and add to the page // string. int byteUsed, charUsed; bool completed = false; totalBytes += bytesRead; UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0, bytesRead, true, out byteUsed, out charUsed, out completed); page = page + new String(charData, 0, charUsed); } page = new String(System.Text.Encoding.UTF8.GetChars(byteData)); } else throw new Exception("No content-Length reported"); // Close the response stream. For Keep-Alive streams, the // stream will remain open and will be pushed into the unused // stream list. resp.Close(); return page; } } Any ideas? Thanks...

    Read the article

  • Cannot connect to one of my WCF services, not even with telnet

    - by Ecyrb
    I have six wcf services that I'm hosting in a windows service. Everything works great on my machine (Windows 7) but when I try it in production (Windows Server 2003) I cannot connect to one of my six services, ReportsService. I figured I must have a typo, but everything looks right. I've even rewritten that section of the config file just to be sure. I've turned on WCF tracing, but it never shows the call to my service; nothing helpful in there. I tried connecting to the port (9005) with telnet, but it failed. I can connect to all other services (ports 9001-4 and 9006) just fine. I thought that maybe there was a problem with port 9005, so I changed it to 9007 and still couldn't connect. I had one of my working services host on 9005 and it actually worked fine. So I'm pretty sure there's nothing wrong with the port or any firewall settings. Whatever port I tell ReportsService to use fails. Now I'm out of ideas. It seems like it's not hosting that one service, but I cannot get any information about why or what's wrong. Any ideas on what I could try to get that information? Or what might be wrong? The unhandled System.ServiceModel.EndpointNotFoundException I get when running my client is: Could not connect to net.tcp://localhost:9005/ReportsService. The connection attempt lasted for a time span of 00:00:01.0937430. TCP error code 10061: No connection could be made because the target machine actively refused it 172.0.0.1:9005. . My host's config file contains: <!-- Snipped other services to simplify for you. --> <endpoint binding="netTcpBinding" bindingConfiguration="customTcpBinding" contract="ServiceContracts.IReportsService" /> <endpoint binding="netTcpBinding" bindingConfiguration="customTcpBinding" contract="ServiceContracts.IUpdateData" /> IReportService is the one I'm having trouble with. I get a proxy to IReportsService with the following code, where Server is the name of the hosting machine: return new ChannelFactory<IReportsService>("").CreateChannel(new EndpointAddress(string.Format("net.tcp://{0}:9005/ReportsService", Server))); My client config file contains: <system.serviceModel> <bindings> <netTcpBinding> <binding name="customTcpBinding" maxReceivedMessageSize="2147483647"> <readerQuotas maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/> <security mode="None"/> </binding> </netTcpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> <serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="30" maxConcurrentSessions="1000" /> </behavior> </serviceBehaviors> </behaviors> <services> <!-- Snipped other services to simplify for you. --> <service behaviorConfiguration="ServiceBehavior" name="WcfService.ReportsService"> <endpoint address="ReportsService" binding="netTcpBinding" bindingConfiguration="customTcpBinding" contract="ServiceContracts.IReportsService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:9005" /> </baseAddresses> </host> </service> <service behaviorConfiguration="ServiceBehavior" name="WcfService.UpdateData"> <endpoint address="UpdateData" binding="netTcpBinding" bindingConfiguration="customTcpBinding" contract="ServiceContracts.IUpdateData" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:9006" /> </baseAddresses> </host> </service> </services> </system.serviceModel> I've tried to keep things simple with the code snippets above, but if you would like to see more just ask and I'd be happy to provide anything that'll help.

    Read the article

  • php - upload script mkdir saying file already exists when same directory even though different filename

    - by neeko
    my upload script says my file already exists when i try upload even though different filename <?php // Start a session for error reporting session_start(); ?> <?php // Check, if username session is NOT set then this page will jump to login page if (!isset($_SESSION['username'])) { header('Location: index.html'); } // Call our connection file include('config.php'); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/JPG", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // Grab the User ID we sent from our form $user_id = $_SESSION['username']; $category = $_POST['category']; // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "img/users/$category/$user_id/"; mkdir($TARGET_PATH, 0755, true); // Get our POSTed variables $fname = $_POST['fname']; $lname = $_POST['lname']; $contact = $_POST['contact']; $price = $_POST['price']; $image = $_FILES['image']; // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $fname == "" || $lname == "" || $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: error.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: error.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: error.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $imagename = $image['name']; $sql = "insert into people (price, contact, category, username, fname, lname, expire, filename) values (:price, :contact, :category, :user_id, :fname, :lname, now() + INTERVAL 1 MONTH, :imagename)"; $q = $conn->prepare($sql) or die("failed!"); $q->bindParam(':price', $price, PDO::PARAM_STR); $q->bindParam(':contact', $contact, PDO::PARAM_STR); $q->bindParam(':category', $category, PDO::PARAM_STR); $q->bindParam(':user_id', $user_id, PDO::PARAM_STR); $q->bindParam(':fname', $fname, PDO::PARAM_STR); $q->bindParam(':lname', $lname, PDO::PARAM_STR); $q->bindParam(':imagename', $imagename, PDO::PARAM_STR); $q->execute(); $sql1 = "UPDATE people SET firstname = (SELECT firstname FROM user WHERE username=:user_id1) WHERE username=:user_id2"; $q = $conn->prepare($sql1) or die("failed!"); $q->bindParam(':user_id1', $user_id, PDO::PARAM_STR); $q->bindParam(':user_id2', $user_id, PDO::PARAM_STR); $q->execute(); $sql2 = "UPDATE people SET surname = (SELECT surname FROM user WHERE username=:user_id1) WHERE username=:user_id2"; $q = $conn->prepare($sql2) or die("failed!"); $q->bindParam(':user_id1', $user_id, PDO::PARAM_STR); $q->bindParam(':user_id2', $user_id, PDO::PARAM_STR); $q->execute(); header("Location: search.php"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: error.php"); exit; } ?>

    Read the article

  • Slowdowns when reading from an urlconnection's inputstream (even with byte[] and buffers)

    - by user342677
    Ok so after spending two days trying to figure out the problem, and reading about dizillion articles, i finally decided to man up and ask to for some advice(my first time here). Now to the issue at hand - I am writing a program which will parse api data from a game, namely battle logs. There will be A LOT of entries in the database(20+ million) and so the parsing speed for each battle log page matters quite a bit. The pages to be parsed look like this: http://api.erepublik.com/v1/feeds/battle_logs/10000/0. (see source code if using chrome, it doesnt display the page right). It has 1000 hit entries, followed by a little battle info(lastpage will have <1000 obviously). On average, a page contains 175000 characters, UTF-8 encoding, xml format(v 1.0). Program will run locally on a good PC, memory is virtually unlimited(so that creating byte[250000] is quite ok). The format never changes, which is quite convenient. Now, I started off as usual: //global vars,class declaration skipped public WebObject(String url_string, int connection_timeout, int read_timeout, boolean redirects_allowed, String user_agent) throws java.net.MalformedURLException, java.io.IOException { // Open a URL connection java.net.URL url = new java.net.URL(url_string); java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) { throw new java.lang.IllegalArgumentException("URL protocol must be HTTP"); } conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(connection_timeout); conn.setReadTimeout(read_timeout); conn.setInstanceFollowRedirects(redirects_allowed); conn.setRequestProperty("User-agent", user_agent); } public void executeConnection() throws IOException { try { is = conn.getInputStream(); //global var l = conn.getContentLength(); //global var } catch (Exception e) { //handling code skipped } } //getContentStream and getLength methods which just return'is' and 'l' are skipped Here is where the fun part began. I ran some profiling (using System.currentTimeMillis()) to find out what takes long ,and what doesnt. The call to this method takes only 200ms on avg public InputStream getWebPageAsStream(int battle_id, int page) throws Exception { String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page; WebObject wobj = new WebObject(url, 10000, 10000, true, "Mozilla/5.0 " + "(Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)"); wobj.executeConnection(); l = wobj.getContentLength(); // global variable return wobj.getContentStream(); //returns 'is' stream } 200ms is quite expected from a network operation, and i am fine with it. BUT when i parse the inputStream in any way(read it into string/use java XML parser/read it into another ByteArrayStream) the process takes over 1000ms! for example, this code takes 1000ms IF i pass the stream i got('is') above from getContentStream() directly to this method: public static Document convertToXML(InputStream is) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); doc.getDocumentElement().normalize(); return doc; } this code too, takes around 920ms IF the initial InputStream 'is' is passed in(dont read into the code itself - it just extracts the data i need by directly counting the characters, which can be done thanks to the rigid api feed format): public static parsedBattlePage convertBattleToXMLWithoutDOM(InputStream is) throws IOException { // Point A BufferedReader br = new BufferedReader(new InputStreamReader(is)); LinkedList ll = new LinkedList(); String str = br.readLine(); while (str != null) { ll.add(str); str = br.readLine(); } if (((String) ll.get(1)).indexOf("error") != -1) { return new parsedBattlePage(null, null, true, -1); } //Point B Iterator it = ll.iterator(); it.next(); it.next(); it.next(); it.next(); String[][] hits_arr = new String[1000][4]; String t_str = (String) it.next(); String tmp = null; int j = 0; for (int i = 0; t_str.indexOf("time") != -1; i++) { hits_arr[i][0] = t_str.substring(12, t_str.length() - 11); tmp = (String) it.next(); hits_arr[i][1] = tmp.substring(14, tmp.length() - 9); tmp = (String) it.next(); hits_arr[i][2] = tmp.substring(15, tmp.length() - 10); tmp = (String) it.next(); hits_arr[i][3] = tmp.substring(18, tmp.length() - 13); it.next(); it.next(); t_str = (String) it.next(); j++; } String[] b_info_arr = new String[9]; int[] space_nums = {13, 10, 13, 11, 11, 12, 5, 10, 13}; for (int i = 0; i < space_nums.length; i++) { tmp = (String) it.next(); b_info_arr[i] = tmp.substring(space_nums[i] + 4, tmp.length() - space_nums[i] - 1); } //Point C return new parsedBattlePage(hits_arr, b_info_arr, false, j); } I have tried replacing the default BufferedReader with BufferedReader br = new BufferedReader(new InputStreamReader(is), 250000); This didnt change much. My second try was to replace the code between A and B with: Iterator it = IOUtils.lineIterator(is, "UTF-8"); Same result, except this time A-B was 0ms, and B-C was 1000ms, so then every call to it.next() must have been consuming some significant time.(IOUtils is from apache-commons-io library). And here is the culprit - the time taken to parse the stream to string, be it by an iterator or BufferedReader in ALL cases was about 1000ms, while the rest of the code took 0ms(e.g. irrelevant). This means that parsing the stream to LinkedList, or iterating over it, for some reason was eating up a lot of my system resources. question was - why? Is it just the way java is made...no...thats just stupid, so I did another experiment. In my main method I added after the getWebPageAsStream(): //Point A ba = new byte[l]; // 'l' comes from wobj.getContentLength above bytesRead = is.read(ba); //'is' is our URLConnection original InputStream offset = bytesRead; while (bytesRead != -1) { bytesRead = is.read(ba, offset - 1, l - offset); offset += bytesRead; } //Point B InputStream is2 = new ByteArrayInputStream(ba); //Now just working with 'is2' - the "copied" stream The InputStream-byte[] conversion took again 1000ms - this is the way many ppl suggested to read an InputStream, and stil it is slow. And guess what - the 2 parser methods above (convertToXML() and convertBattlePagetoXMLWithoutDOM(), when passed 'is2' instead of 'is' took, in all 4 cases, under 50ms to complete. I read a suggestion that the stream waits for connection to close before unblocking, so i tried using HttpComponentsClient 4.0 (http://hc.apache.org/httpcomponents-client/index.html) instead, but the initial InputStream took just as long to parse. e.g. this code: public InputStream getWebPageAsStream2(int battle_id, int page) throws Exception { String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpParams p = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(p, 250000); HttpConnectionParams.setStaleCheckingEnabled(p, false); HttpConnectionParams.setConnectionTimeout(p, 5000); httpget.setParams(p); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); l = (int) entity.getContentLength(); return entity.getContent(); } took even longer to process(50ms more for just the network) and the stream parsing times remained the same. Obviously it can be instantiated so as to not create HttpClient and properties every time(faster network time), but the stream issue wont be affected by that. So we come to the center problem - why does the initial URLConnection InputStream(or HttpClient InputStream) take so long to process, while any stream of same size and content created locally is orders of magnitude faster? I mean, the initial response is already somewhere in RAM, and I cant see any good reasong why it is processed so slowly compared to when a same stream is just created from a byte[]. Considering I have to parse million of entries and thousands of pages like that, a total processing time of almost 1.5s/page seems WAY WAY too long. Any ideas? P.S. Please ask in any more code is required - the only thing I do after parsing is make a PreparedStatement and put the entries into JavaDB in packs of 1000+, and the perfomance is ok ~ 200ms/1000entries, prb could be optimized with more cache but I didnt look into it much.

    Read the article

  • web.xml not reloading in tomcat even after stop/start

    - by ajay
    This is in relation to:- http://stackoverflow.com/questions/2576514/basic-tomcat-servlet-error I changed my web.xml file, did ant compile , all, /etc/init.d/tomcat stop , start Even then my web.xml file in tomcat deployment is still unchanged. This is build.properties file:- app.name=hello catalina.home=/usr/local/tomcat manager.username=admin manager.password=admin This is my build.xml file. Is there something wrong with this:- <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- General purpose build script for web applications and web services, including enhanced support for deploying directly to a Tomcat 6 based server. This build script assumes that the source code of your web application is organized into the following subdirectories underneath the source code directory from which you execute the build script: docs Static documentation files to be copied to the "docs" subdirectory of your distribution. src Java source code (and associated resource files) to be compiled to the "WEB-INF/classes" subdirectory of your web applicaiton. web Static HTML, JSP, and other content (such as image files), including the WEB-INF subdirectory and its configuration file contents. $Id: build.xml.txt 562814 2007-08-05 03:52:04Z markt $ --> <!-- A "project" describes a set of targets that may be requested when Ant is executed. The "default" attribute defines the target which is executed if no specific target is requested, and the "basedir" attribute defines the current working directory from which Ant executes the requested task. This is normally set to the current working directory. --> <project name="My Project" default="compile" basedir="."> <!-- ===================== Property Definitions =========================== --> <!-- Each of the following properties are used in the build script. Values for these properties are set by the first place they are defined, from the following list: * Definitions on the "ant" command line (ant -Dfoo=bar compile). * Definitions from a "build.properties" file in the top level source directory of this application. * Definitions from a "build.properties" file in the developer's home directory. * Default definitions in this build.xml file. You will note below that property values can be composed based on the contents of previously defined properties. This is a powerful technique that helps you minimize the number of changes required when your development environment is modified. Note that property composition is allowed within "build.properties" files as well as in the "build.xml" script. --> <property file="build.properties"/> <property file="${user.home}/build.properties"/> <!-- ==================== File and Directory Names ======================== --> <!-- These properties generally define file and directory names (or paths) that affect where the build process stores its outputs. app.name Base name of this application, used to construct filenames and directories. Defaults to "myapp". app.path Context path to which this application should be deployed (defaults to "/" plus the value of the "app.name" property). app.version Version number of this iteration of the application. build.home The directory into which the "prepare" and "compile" targets will generate their output. Defaults to "build". catalina.home The directory in which you have installed a binary distribution of Tomcat 6. This will be used by the "deploy" target. dist.home The name of the base directory in which distribution files are created. Defaults to "dist". manager.password The login password of a user that is assigned the "manager" role (so that he or she can execute commands via the "/manager" web application) manager.url The URL of the "/manager" web application on the Tomcat installation to which we will deploy web applications and web services. manager.username The login username of a user that is assigned the "manager" role (so that he or she can execute commands via the "/manager" web application) --> <property name="app.name" value="myapp"/> <property name="app.path" value="/${app.name}"/> <property name="app.version" value="0.1-dev"/> <property name="build.home" value="${basedir}/build"/> <property name="catalina.home" value="../../../.."/> <!-- UPDATE THIS! --> <property name="dist.home" value="${basedir}/dist"/> <property name="docs.home" value="${basedir}/docs"/> <property name="manager.url" value="http://localhost:8080/manager"/> <property name="src.home" value="${basedir}/src"/> <property name="web.home" value="${basedir}/web"/> <!-- ==================== External Dependencies =========================== --> <!-- Use property values to define the locations of external JAR files on which your application will depend. In general, these values will be used for two purposes: * Inclusion on the classpath that is passed to the Javac compiler * Being copied into the "/WEB-INF/lib" directory during execution of the "deploy" target. Because we will automatically include all of the Java classes that Tomcat 6 exposes to web applications, we will not need to explicitly list any of those dependencies. You only need to worry about external dependencies for JAR files that you are going to include inside your "/WEB-INF/lib" directory. --> <!-- Dummy external dependency --> <!-- <property name="foo.jar" value="/path/to/foo.jar"/> --> <!-- ==================== Compilation Classpath =========================== --> <!-- Rather than relying on the CLASSPATH environment variable, Ant includes features that makes it easy to dynamically construct the classpath you need for each compilation. The example below constructs the compile classpath to include the servlet.jar file, as well as the other components that Tomcat makes available to web applications automatically, plus anything that you explicitly added. --> <path id="compile.classpath"> <!-- Include all JAR files that will be included in /WEB-INF/lib --> <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** --> <!-- <pathelement location="${foo.jar}"/> --> <!-- Include all elements that Tomcat exposes to applications --> <fileset dir="${catalina.home}/bin"> <include name="*.jar"/> </fileset> <pathelement location="${catalina.home}/lib"/> <fileset dir="${catalina.home}/lib"> <include name="*.jar"/> </fileset> </path> <!-- ================== Custom Ant Task Definitions ======================= --> <!-- These properties define custom tasks for the Ant build tool that interact with the "/manager" web application installed with Tomcat 6. Before they can be successfully utilized, you must perform the following steps: - Copy the file "lib/catalina-ant.jar" from your Tomcat 6 installation into the "lib" directory of your Ant installation. - Create a "build.properties" file in your application's top-level source directory (or your user login home directory) that defines appropriate values for the "manager.password", "manager.url", and "manager.username" properties described above. For more information about the Manager web application, and the functionality of these tasks, see <http://localhost:8080/tomcat-docs/manager-howto.html>. --> <taskdef resource="org/apache/catalina/ant/catalina.tasks" classpathref="compile.classpath"/> <!-- ==================== Compilation Control Options ==================== --> <!-- These properties control option settings on the Javac compiler when it is invoked using the <javac> task. compile.debug Should compilation include the debug option? compile.deprecation Should compilation include the deprecation option? compile.optimize Should compilation include the optimize option? --> <property name="compile.debug" value="true"/> <property name="compile.deprecation" value="false"/> <property name="compile.optimize" value="true"/> <!-- ==================== All Target ====================================== --> <!-- The "all" target is a shortcut for running the "clean" target followed by the "compile" target, to force a complete recompile. --> <target name="all" depends="clean,compile" description="Clean build and dist directories, then compile"/> <!-- ==================== Clean Target ==================================== --> <!-- The "clean" target deletes any previous "build" and "dist" directory, so that you can be ensured the application can be built from scratch. --> <target name="clean" description="Delete old build and dist directories"> <delete dir="${build.home}"/> <delete dir="${dist.home}"/> </target> <!-- ==================== Compile Target ================================== --> <!-- The "compile" target transforms source files (from your "src" directory) into object files in the appropriate location in the build directory. This example assumes that you will be including your classes in an unpacked directory hierarchy under "/WEB-INF/classes". --> <target name="compile" depends="prepare" description="Compile Java sources"> <!-- Compile Java classes as necessary --> <mkdir dir="${build.home}/WEB-INF/classes"/> <javac srcdir="${src.home}" destdir="${build.home}/WEB-INF/classes" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}"> <classpath refid="compile.classpath"/> </javac> <!-- Copy application resources --> <copy todir="${build.home}/WEB-INF/classes"> <fileset dir="${src.home}" excludes="**/*.java"/> </copy> </target> <!-- ==================== Dist Target ===================================== --> <!-- The "dist" target creates a binary distribution of your application in a directory structure ready to be archived in a tar.gz or zip file. Note that this target depends on two others: * "compile" so that the entire web application (including external dependencies) will have been assembled * "javadoc" so that the application Javadocs will have been created --> <target name="dist" depends="compile,javadoc" description="Create binary distribution"> <!-- Copy documentation subdirectories --> <mkdir dir="${dist.home}/docs"/> <copy todir="${dist.home}/docs"> <fileset dir="${docs.home}"/> </copy> <!-- Create application JAR file --> <jar jarfile="${dist.home}/${app.name}-${app.version}.war" basedir="${build.home}"/> <!-- Copy additional files to ${dist.home} as necessary --> </target> <!-- ==================== Install Target ================================== --> <!-- The "install" target tells the specified Tomcat 6 installation to dynamically install this web application and make it available for execution. It does *not* cause the existence of this web application to be remembered across Tomcat restarts; if you restart the server, you will need to re-install all this web application. If you have already installed this application, and simply want Tomcat to recognize that you have updated Java classes (or the web.xml file), use the "reload" target instead. NOTE: This target will only succeed if it is run from the same server that Tomcat is running on. NOTE: This is the logical opposite of the "remove" target. --> <target name="install" depends="compile" description="Install application to servlet container"> <deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="file://${build.home}"/> </target> <!-- ==================== Javadoc Target ================================== --> <!-- The "javadoc" target creates Javadoc API documentation for the Java classes included in your application. Normally, this is only required when preparing a distribution release, but is available as a separate target in case the developer wants to create Javadocs independently. --> <target name="javadoc" depends="compile" description="Create Javadoc API documentation"> <mkdir dir="${dist.home}/docs/api"/> <javadoc sourcepath="${src.home}" destdir="${dist.home}/docs/api" packagenames="*"> <classpath refid="compile.classpath"/> </javadoc> </target> <!-- ====================== List Target =================================== --> <!-- The "list" target asks the specified Tomcat 6 installation to list the currently running web applications, either loaded at startup time or installed dynamically. It is useful to determine whether or not the application you are currently developing has been installed. --> <target name="list" description="List installed applications on servlet container"> <list url="${manager.url}" username="${manager.username}" password="${manager.password}"/> </target> <!-- ==================== Prepare Target ================================== --> <!-- The "prepare" target is used to create the "build" destination directory, and copy the static contents of your web application to it. If you need to copy static files from external dependencies, you can customize the contents of this task. Normally, this task is executed indirectly when needed. --> <target name="prepare"> <!-- Create build directories as needed --> <mkdir dir="${build.home}"/> <mkdir dir="${build.home}/WEB-INF"/> <mkdir dir="${build.home}/WEB-INF/classes"/> <!-- Copy static content of this web application --> <copy todir="${build.home}"> <fileset dir="${web.home}"/> </copy> <!-- Copy external dependencies as required --> <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** --> <mkdir dir="${build.home}/WEB-INF/lib"/> <!-- <copy todir="${build.home}/WEB-INF/lib" file="${foo.jar}"/> --> <!-- Copy static files from external dependencies as needed --> <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** --> </target> <!-- ==================== Reload Target =================================== --> <!-- The "reload" signals the specified application Tomcat 6 to shut itself down and reload. This can be useful when the web application context is not reloadable and you have updated classes or property files in the /WEB-INF/classes directory or when you have added or updated jar files in the /WEB-INF/lib directory. NOTE: The /WEB-INF/web.xml web application configuration file is not reread on a reload. If you have made changes to your web.xml file you must stop then start the web application. --> <target name="reload" depends="compile" description="Reload application on servlet container"> <reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target> <!-- ==================== Remove Target =================================== --> <!-- The "remove" target tells the specified Tomcat 6 installation to dynamically remove this web application from service. NOTE: This is the logical opposite of the "install" target. --> <target name="remove" description="Remove application on servlet container"> <undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target> </project>

    Read the article

  • Django cannot find my templatetags, even though it's in INSTALLED_APPS and has a __init__.py

    - by Vivian Short
    I just installed django-compress (http://code.google.com/p/django-compress) into /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/compress. I added 'compress' to INSTALLED_APPS. In my template file, I wrote {% load compressed %}. I got the error: 'compressed' is not a valid tag library: Could not load template library from django.templatetags.compressed, No module named compressed I verified that there is an init.py in compress, as well as in compress/templatetags/. I tried putting the compress directory into PYTHONPATH. I ran python and wrote "import compress" and that worked. Your suggestions would be very appreciated! What else can I try?

    Read the article

  • Team Build: The path 'Path' is already mapped in workspace 'workspace' error even after deleting all

    - by Glenn Slaven
    I have this problem when I queue a build. The build dies with the error The path C:\[Path]\Sources is already mapped in workspace [Server Name]. the same as this question. but I've removed all the workspaces on the build agent by running this command: tf workspaces /remove:* and also by deleting the TFS cache folder. I've also restarted the server, but the error keeps happening on each build.

    Read the article

  • Why jquery have problem with onbeforeprint even?

    - by Cesar Lopez
    Hi all, I have the following function. $(function() { $(".sectionHeader:gt(0)").click(function() { $(this).next(".fieldset").slideToggle("fast"); }); $("img[alt='minimize']").click(function(e) { $(this).closest("table").next(".fieldset").slideUp("fast"); e.stopPropagation(); return false; }); $("img[alt='maximize']").click(function(e) { $(this).closest("table").next(".fieldset").slideDown("fast"); e.stopPropagation(); return false; }); }); <script type="text/javascript"> window.onbeforeprint = expandAll; function expandAll(){ $(".fieldset:gt(0)").slideDown("fast"); } </script> For this html <table class="sectionHeader" ><tr ><td>Heading 1</td></tr></table> <div style="display:none;" class="fieldset">Content 1</div> <table class="sectionHeader" ><tr ><td>Heading 2</td></tr></table> <div style="display:none;" class="fieldset">Content 2</div> I have several div class="fieldset" over the page, but when I do print preview or print, I can see all divs sliding down before opening the print preview or printing but on the actual print preview or print out they are all collapse. I would appreciate if anyone comes with a solution for this. Anyone have any idea why is this or how to fix it? Thanks. PS:Using a does not work either ( I assume because jquery using toggle) and its not the kind of question I am looking for.

    Read the article

  • Coloring even heighten columns

    - by verror
    I try to set different a background colors for left and right columns and to maintain the same height. So I set a background color for outer wrapper ("container" div) so it will set a color to rightBar. But this didn't work. Online Demo I want it to work on all browsers. Markup: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Test</title> </head> <body> <div class="contentcontainer"> <div class="container"> <div class="mainBar"> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text </p> </div> <div class="rightBar"> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> <p>BAR Text BAR Text BAR Text</p> </div> </div> </div> </body> </html> CSS: body { font-family: Verdana,Tahoma,Arial, "Trebuchet MS" ,Sans-Serif,Georgia,Courier, "Times New Roman" ,Serif; margin: 0px; padding: 0px; background: repeat-x scroll center bottom #C4DAE9; text-align:center; } .contentcontainer { } .container { margin-left: auto; margin-right: auto; margin-top:5px; width: 99%; text-align: left; background-color:Gray; clear:both; } .mainBar { width:70%; float:left; background-color:White; } .rightBar { width:30%; float:left; }

    Read the article

  • Video/audio streaming does not stop even if UIWebView is closed - iPad

    - by lostInTransit
    Hi I see this issue only on the iPad. The same things works as expected on the iPhone. I am opening the URL from my application in a UIWebView. If the URL is a normal web page, it works fine as expected. But if the URL is that of a remote video/audio file, the UIWebView opens the default player which is again good. Now when I dismiss the UIWebView (by clicking on the Done button on the player), the streaming doesn't stop and the audio/video keeps playing in the background (I cannot see it but it does keep playing in the background, can hear it). The UIViewController in which the webview was created is also dealloced (I put in a log statement in the dealloc method) but the streaming doesn't stop. Can someone please help me out on why this could be happening? And how can I stop the audio/video streaming when the UIWebView is closed? Thanks.

    Read the article

  • WCF sending the same exception even if the service endpoint address is valid

    - by ALexr111
    Hi, I'm running into a really strange problem with WCF. I need to implement some recovery behavior for WCF service if not reachable endpoint IP address received or service can not bind. The flow is simple if the application fail on exception on service creation it terminate it and request from user another IP address and perform another attempt to create the service. (The code snippet below). If the address is not valid I get "A TCP error (10049: The requested address is not valid in its context) occurred while listening on IP Endpoint=.121.10.11.11" exception, but for any reason if I try the second attempt with valid address I've got the same exception with wrong IP address from previous attempt. Here is a code: ServiceHost service = null; try { Uri[] uris = { new Uri(Constants.PROTOCOL + "://" + address + ":" + port) }; service = new ServiceHost(typeof(IRemoteService), uris); NetTcpBinding tcpBinding = WcfTcpRemoteServicesManager.LessLimitedNewNetTcpBinding(int.MaxValue, int.MaxValue, int.MaxValue); ServiceEndpoint ep = service.AddServiceEndpoint(implementedContract.FullName, tcpBinding, serviceName); var throttle = service.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior { MaxConcurrentCalls = Constants.MAX_CONCURRENT_CALLS, MaxConcurrentSessions = Constants.MAX_CONCURRENT_SESSIONS, MaxConcurrentInstances = Constants.MAX_CONCURRENT_INSTANCES }; service.Description.Behaviors.Add(throttle); } service.Open(); } catch (Exception e) { _debugLog.WriteLineMessage( "Failed to open or create service exception. Exception message:" + e.Message); if (service!=null) { try { service.Close(); } catch (Exception) { service.Abort(); service.Close(); throw e; } } } Thanks

    Read the article

  • log4net affecting other projects which don't even use it

    - by Graeme
    I'm seeing something really strange happening with some projects I'm working on. I used log4net in an MVC web site and this was working great. I then was working on a totally unrelated Console application which uses the SharePoint API and as soon as I include the following line (other lines don't cause the problem) SPLimitedWebPartManager spWebPartManager = web.GetLimitedWebPartManager("http://blah/blah.aspx?PageView=Shared", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); I get the following message in the console app log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and < configSections> elements. The configuration section should look like: <section n ame="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" / > log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and < configSections> elements. The configuration section should look like: <section n ame="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" / > I get this twice after a small delay. The delay is probably the request to get the web part manager from the page but I'm not sure why this log4net error is showing up in this project. I've gone through the code and bin folders etc. and found no trace of any log4net mentions. Any ideas why this might be happening?

    Read the article

  • DataGridView's SelectionChange event firing twice on DataBinding even after removing event binding

    - by Shantanu Gupta
    This Code triggers selection change event twice. how can I prevent it ? Currently i m using a flag or focused property to prevent this. But what is the actual way ? I am using it on winfoms EDIT My Mistake in writing Question, here is the correct code that i wanted to ask private void frmGuestInfo_Load(object sender, EventArgs e) { this.dgvGuestInfo.SelectionChanged -= new System.EventHandler(this.dgvGuestInfo_SelectionChanged); dgvGuestInfo.DataSource=dsFillControls.Tables["tblName"]; this.dgvGuestInfo.SelectionChanged += new System.EventHandler(this.dgvGuestInfo_SelectionChanged); } private void dgvGuestInfo_SelectionChanged(object sender, EventArgs e) { //this function is raised twice, i was expecting that this will not be raised }

    Read the article

  • Qt: Force QWebView to click on a web element, even one not visible on the window

    - by Pirate for Profit
    So let's say I'm trying to click a link in the QWebView, here is what I have: // extending QWebView void MyWebView::click(const QString &selectorQuery) { QWebElement el = this->page()->mainFrame()->findFirstElement(selectorQuery); if (!el) return; el.setFocus(); QMouseEvent pressEvent(QMouseEvent::MouseButtonPress, el.geometry().center(), Qt::MouseButton::LeftButton, Qt::LeftButton, Qt::NoModifier); QCoreApplication::sendEvent(this, &pressEvent); QMouseEvent releaseEvent(QMouseEvent::MouseButtonRelease, el.geometry().center(), Qt::MouseButton::LeftButton, Qt::LeftButton, Qt::NoModifier); QCoreApplication::sendEvent(this, &releaseEvent); } And you call it as so: myWebView->click("a[href]"); // will click first link on page myWebView->click("input[type=submit]"); // submits a form THE ONLY PROBLEM IS: if the element is not visible in the window, it is impossible to click. What I mean is if you have to scroll down to see it, you can't click it. I imagine this has to do with the geometry, since the element doesn't show up on the screen it can't do the math to click it right. Any ideas to get around this? Maybe some way to make the window behave like a billion x billion pixels but still look 200x200?

    Read the article

  • Can't find controls in FormView.InsertItemTemplate even on DataBound event

    - by abatishchev
    I have FormView in my page markup: <asp:FormView ruanat="server" ID="FormView1" OnDataBound="FormView1_DataBound" DataSourceID="SqlDataSource1"> <InsertItemTemplate> <uc:UserControl1 runat="server" ID="ucUserControl1" /> </InsertItemTemplate> </asp:FormView> <asp:SqlDataSource runat="server" ID="SqlDataSource1" SelectCommand="EXEC someSP" /> It's code-behind: protected void FormView1_DataBound (object sender, EventArgs e) { var c1 = ((FormView)sender).FindControl("ucUserControl1"); // returns null var c2 = FormView1.FindControl("ucUserControl1"); // also returns null } In theory, I'm able to find control on FormView after it being data bound. But I'm not. Why?

    Read the article

  • iPhone - phone goes to sleep even if idleTimerDisabled is YES

    - by lostInTransit
    Hi I am using this in my appdelegate's applicationDidFinishLaunching: method to make sure the iPhone doesn't go to sleep during the time the app is open [application setIdleTimerDisabled:YES]; It works great on all screens but on one of the screens the iPhone goes to sleep. I could not figure out how to reproduce this and it seems to happen at random times. Can someone please tell me how to handle this situation. Thanks

    Read the article

  • Problem with pre-beta sdk - even after reinstalling SDK 3.2

    - by Anders Brenna
    I'm trying to upload the binary for a new app, but always get this errormessage: "The binary you uploaded was invalid. A pre-release beta version of the SDK was used to build the application." I know several people have asked a similar question, but I've tried all suggestions from the answers there without success. I used the XCode 4.0 beta 3 during development, and I've tried using it to compile for earlier releases (3.0, 3.1.3, 3.2 etc...) I've also tried downgrading to SDK 3.2, as well as removing 4.0 beta 3 and then installing SDK 3.2 as a fresh install. It seems to me that there might be some parameter in the "Edit Project Settings" that is sticking from the use of 4.0 beta 3, but I've tried to identify them without success. My last option seem to be a complete reinstall of both OS and SDK. Is there something else I might try first?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >