Search Results

Search found 1130 results on 46 pages for 'encode'.

Page 39/46 | < Previous Page | 35 36 37 38 39 40 41 42 43 44 45 46  | Next Page >

  • App-Engine Parse a UrlFetch UTF-8 encoded stream

    - by Davidrd91
    I am trying to parse an XML from a URL using the xml.sax parser. I know there are other libraries to use but coming from Java this is the one I am most familiar with and seems the least complicated to me. The code I'm using to parse is as follows: parser = xml.sax.make_parser() handler = MangaHandler() parser.setContentHandler(handler) url = urlfetch.Fetch('http://www.mangapanda.com/alphabetical', allow_truncated = False, follow_redirects = False, deadline = False) xml.sax.parseString(url.content, handler) This returns a SaxException (invalid token) once the parser reaches the first & sign: SAXParseException: <unknown>:582:34: not well-formed (invalid token) Because urlfetch returns a string and not a stream I cannot use the parse() (which only works with streams) and am left to use parseString() instead. To see if parsing as a stream would fix this I tried: parser.parse(io.StringIO(url.content).encode('utf-8')) but this returns: TypeError: initial_value must be unicode or None, not str I have also tried to use the urllib2 libraries which do return a stream instead of urlfetch but the file is too large and is automatically truncated, leaving me with missing data. Any Sort of work-around for this would be greatly appreciated as I've spent days getting around one obstacle just to be stopped by another.

    Read the article

  • Creating C++ client app for some abstract windows server - how to manage TCP connection to server speed?

    - by Kabumbus
    So we have some server with some address port and ip. we are developing that server so we can implement on it what ever we need for help. What are standard/best practices for data transfer speed management between C++ windows client app and server (C++)? My main point is in how to get how much data can be uploaded/downloaded from/to client via his low speed network to my relatively super fast server. (I need it for set up of his live stream Audio/Video bit rate) My try on explaining number 3. We do not care how fast is our server. It is always faster than needed. We care about client tyring to stream out to our server his media. he streams encoded (via ffmpeg) live video data to our server. But he has say ADSL with 500kb/s of outgoing traffic. Also he uses some ICQ or what so ever so he has less than 500 kb/s per second. And he wants to stream live video! So we need to set up our ffmpeg to encode video with respect to the bit rate user can provide. We develop server side and client side. We need a way of finding out how much user can upload per second currently (so value can change dynamically over time)

    Read the article

  • Optimization of Function with Dictionary and Zip()

    - by eWizardII
    Hello, I have the following function: def filetxt(): word_freq = {} lvl1 = [] lvl2 = [] total_t = 0 users = 0 text = [] for l in range(0,500): # Open File if os.path.exists("C:/Twitter/json/user_" + str(l) + ".json") == True: with open("C:/Twitter/json/user_" + str(l) + ".json", "r") as f: text_f = json.load(f) users = users + 1 for i in range(len(text_f)): text.append(text_f[str(i)]['text']) total_t = total_t + 1 else: pass # Filter occ = 0 import string for i in range(len(text)): s = text[i] # Sample string a = re.findall(r'(RT)',s) b = re.findall(r'(@)',s) occ = len(a) + len(b) + occ s = s.encode('utf-8') out = s.translate(string.maketrans("",""), string.punctuation) # Create Wordlist/Dictionary word_list = text[i].lower().split(None) for word in word_list: word_freq[word] = word_freq.get(word, 0) + 1 keys = word_freq.keys() numbo = range(1,len(keys)+1) WList = ', '.join(keys) NList = str(numbo).strip('[]') WList = WList.split(", ") NList = NList.split(", ") W2N = dict(zip(WList, NList)) for k in range (0,len(word_list)): word_list[k] = W2N[word_list[k]] for i in range (0,len(word_list)-1): lvl1.append(word_list[i]) lvl2.append(word_list[i+1]) I have used the profiler to find that it seems the greatest CPU time is spent on the zip() function and the join and split parts of the code, I'm looking to see if there is any way I have overlooked that I could potentially clean up the code to make it more optimized, since the greatest lag seems to be in how I am working with the dictionaries and the zip() function. Any help would be appreciated thanks!

    Read the article

  • How to connect to a third party website in classic asp using javascript for password encryption and yet not giving in the password.

    - by Abbi
    Hi I have to make changes to classic asp website where once a button is clicked it autologins to a third party website with a intermediate page that warns that you are logging in to a third party website. The thirdparty is providing us with a username and password and gave us an examle javascript to encode the password to send to them. Now where do I store the userid and password. I cannot execute the javascript on the serverside. It has to go to the client. If the asp page which has the encryption javascript goes to the client side then the source can be viewed and the username and password is given out. Is there a way that I can have hidden asp page whose only job is to encrypt the password and create a new url and auto redirect it to that new url. So when the user clicks ok on the intermediate warning page I redirect it to this hidden asp page which does the encryption and a creates a url for get method and redirects to that page. I am a novice as far as java script and classic asp is concerned. Any ideas/ advice will be appreciated. Thanks, --Abbi

    Read the article

  • To implement a remote desktop sharing solution

    - by Cameigons
    Hi, I'm on planning/modeling phase to develop a remote desktop sharing solution, which must be web browser based. In other words: an user will be able to see and interact with someone's remote desktop using his web-browser. Everything the user who wants to share his desktop will need, besides his browser, is installing an add-in, which he's going to be prompted about when necessary. The add-in is required since (afaik) no browser technology allows desktop control from an app running within the browser alone. The add-in installation process must be as simple and transparent as possible to the user (similar to AdobeConnectNow, in case anyone's acquainted with it). The user can share his desktop with lots of people at the same time, but concede desktop control to only one of them at a time(makes no sense being otherwise). Project requirements: All technology employed must be open-source license compatible Both front ends are going to be in flash (browser) Must work on Linux, Windows XP(and later) and MacOSX. Must work at least with IE7(and later) and Firefox3.0(and later). At the very least, once the sharer's stream hits the server from where it'll be broadcast, hereon it must be broadcasted in flv (so I'm thinking whether to do the encoding at the client's machine (the one sharing the desktop) or send it in some other format to the server and encode it there). Performance and scalability are important: It must be able to handle hundreds of dozens of users(one desktop sharer, the rest viewers) We'll definitely be using red5. My doubts concern mostly implementing the desktop publisher side (add-in and streamer): 1) Are you aware of other projects that I could look into for ideas? (I'm aware of bigbluebutton.org and code.google.com/p/openmeetings) 2) Should I base myself on VNC ? 3) Bearing in mind the need to have it working cross-platform, what language should I go with? (My team is very used with java and I have some knowledge of C/C++, but anything goes really). 4) Any other advices are appreciated.

    Read the article

  • how to set Content-Type automatically when i download the data that i uploaded.

    - by zjm1126
    this is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_args=None): if not template_args: template_args = {} path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_args)) class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file.encode('utf8')) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.out.write(o) application = webapp.WSGIApplication( [ ('/?', upload), ('/download',download), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() my index.html is : <form action="/" method="post"> <input type="file" name="file" /> <input type="submit" /> </form> and it show : <__main__.MyModel object at 0x02506830> but ,i don't want to see this , i want to download it , how to change my code to run, thanks updated it is ok now : class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().order('-').get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.headers['Content-Type'] = "image/png" self.response.out.write(o.blob) and new question is : if you upload a 'png' file ,it will show successful , but ,when i upload a rar file ,i will run error , so how to set Content-Type automatically , and what is the Content-Type of the 'rar' file thanks

    Read the article

  • Php JSON Response Array

    - by Nick Kl
    I have this php code. As you can see i query a mysql database through a function showallevents. I return a the $result to the $event variable. I try to return all rows of the data that i take with the msql_fetch_assoc. I don't get response even when i encode the $response variable. It returns null to all fields. Can anyone help me on what i am doing wrong. I had a valid code but it was returning only 1 row of data so i tried to make an associative array but seems i am failing. if ($tag == 'showallevents') { // Request type is show all events // show all events $event = $db->showallevents(); if ($event != false) { $data = array(); while($row = mysql_fetch_assoc($event)) { $data[] = array( $response["success"] = 1, $response["uid"] = $event["uid"], $response["event"]["date"] = $event["date"], $response["event"]["hours"] = $event["hours"], $response["event"]["store_name"] = $event["store_name"], $response["event"]["event_information"] = $event["event_information"], $response["event"]["event_type"] = $event["event_type"], $response["event"]["Phone"] = $event["Phone"], $response["event"]["address"] = $event["address"], $response["event"]["created_at"] = $event["created_at"], $response["event"]["updated_at"] = $event["updated_at"]); } echo json_encode($data); } else { // event not found // echo json with error = 1 $response["error"] = 1; $response["error_msg"] = "Events not found"; echo json_encode($response); } } else { echo "Access Denied"; } } ?>

    Read the article

  • Fast (de)serialization on iPhone

    - by Jacob Kuypers
    I'm developing a game/engine for iPhone OS. It's the first time I'm using Objective-C. I made my own binary format for geometry data and for textures I'm focusing on PVRTC. That should be the optimal approach as far as speed and space are concerned. I really want to keep loading time to a minimum and - if possible - be able to save very fast as well. So now I'm trying to make my "Entity" stuff persistent without sacrificing performance. First I wanted to use NSKeyedArchiver. From what I've heard, it's not very fast. Also, what I want to serialize is mostly structs made of floats with some ints and strings, so there isn't really a need for all that "object graph" overhead. NSArchiver would have been more appropriate, but they kicked that off the iphone for some reason. So now I'm thinking about making my own serialization scheme again. Am I wrong in thinking that NSKeyedArchiver is slow (I only read that, haven't tested it myself)? If so, what's the best way to encode/decode structs (with no pointers, mostly floats) without sacrificing speed?

    Read the article

  • Consume a JSON webservice and process data in Android

    - by user1783391
    I am trying to consume a the webservice below http://62.253.195.179/disaster/webservices/login.php?message=[{"email":"[email protected]","password":"welcome"}] This returns a JSON array [{"companyuserId":"2","name":"ben stein","superiorname":"Leon","departmentId":"26","departmentname":"Development","companyId":"23","UDID":"12345","isActive":"1","devicetoken":"12345","email":"[email protected]","phone":"5456465465654","userrole":"1","chngpwdStatus":"1"}] My code is below try{ String weblink = URLEncoder.encode("http://62.253.195.179/disaster/webservices/login.php?message=[{\"email\":\"[email protected]\",\"password\":\"welcome\"}]"); HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 7500; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 7500; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(); URI link = new URI(weblink); request.setURI(link); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); result = rd.readLine(); JSONObject myData = new JSONObject(result); JSONArray jArray = myData.getJSONArray(""); JSONObject steps = jArray.getJSONObject(0); String name = steps.getString("name"); } catch (JSONException e) { e.printStackTrace(); } But its not working and I am not 100% sure this is the best way to do it. 11-10 10:49:55.489: E/AndroidRuntime(392): java.lang.IllegalStateException: Target host must not be null, or set in parameters.

    Read the article

  • Why does Python sometimes upgrade a string to unicode and sometimes not?

    - by samtregar
    I'm confused. Consider this code working the way I expect: >>> foo = u'Émilie and Juañ are turncoats.' >>> bar = "foo is %s" % foo >>> bar u'foo is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' And this code not at all working the way I expect: >>> try: ... raise Exception(foo) ... except Exception as e: ... foo2 = e ... >>> bar = "foo2 is %s" % foo2 ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) Can someone explain what's going on here? Why does it matter whether the unicode data is in a plain unicode string or stored in an Exception object? And why does this fix it: >>> bar = u"foo2 is %s" % foo2 >>> bar u'foo2 is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' I am quite confused! Thanks for the help! UPDATE: My coding buddy Randall has added to my confusion in an attempt to help me! Send in the reinforcements to explain how this is supposed to make sense: >>> class A: ... def __str__(self): return "string" ... def __unicode__(self): return "unicode" ... >>> "%s %s" % (u'niño', A()) u'ni\xc3\xb1o unicode' >>> "%s %s" % (A(), u'niño') u'string ni\xc3\xb1o' Note that the order of the arguments here determines which method is called!

    Read the article

  • Generating authentication header from azure table through objective-c

    - by user923370
    I'm fetching data from iCloud and for that I need to generate a header (azure table storage). I used the code below for that and it is generating the headers. But when I use these headers in my project it is showing "make sure that the value of authorization header is formed correctly including the signature." I googled a lot and tried many codes but in vain. Can anyone kindly please help me with where I'm going wrong in this code. -(id)generat{ NSString *messageToSign = [NSString stringWithFormat:@"%@/%@/%@", dateString,AZURE_ACCOUNT_NAME, tableName]; NSString *key = @"asasasasasasasasasasasasasasasasasasasasas=="; const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding]; const char *cData = [messageToSign cStringUsingEncoding:NSUTF8StringEncoding]; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; NSString *hash = [Base64 encode:HMAC]; NSLog(@"Encoded hash: %@", hash); NSURL *url=[NSURL URLWithString: @"http://my url"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request addValue:[NSString stringWithFormat:@"SharedKeyLite %@:%@",AZURE_ACCOUNT_NAME, hash] forHTTPHeaderField:@"Authorization"]; [request addValue:dateString forHTTPHeaderField:@"x-ms-date"]; [request addValue:@"application/atom+xml, application/xml"forHTTPHeaderField:@"Accept"]; [request addValue:@"UTF-8" forHTTPHeaderField:@"Accept-Charset"]; NSLog(@"Headers: %@", [request allHTTPHeaderFields]); NSLog(@"URL: %@", [[request URL] absoluteString]); return request; } -(NSString*)rfc1123String:(NSDate *)date { static NSDateFormatter *df = nil; if(df == nil) { df = [[NSDateFormatter alloc] init]; df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]; df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"; } return [df stringFromDate:date]; }

    Read the article

  • Use CSS3 nth-child to alternate the float of images within DIV tags...

    - by Aaron Rodgers
    Basically, what I'm trying to create is a page of div tags, each has an image inside them and I'm trying to use CSS3's nth-child to alternate the float of that specific image. But for the life of me, I can't get the nth-child to locate those images. Here is my code so far... CSS .featureBlock img:nth-of-type(even) { float: left; } .featureBlock img:nth-of-type(odd) { float: right; } This is the HTML of one of those div tags.... <div class="featureBlock"> <h1>Multisize Players</h1> <div class="featureHelpBlock"><a href="#">More help with this</a></div> <img src="http://office2.vzaar.com/images/features/ft_multisize_players.png"> <span class="featureContent"><p>A variety of player sizes is important as we recognise the fact that no two videos or websites are ever the same and you will want something that suits your site&#8217;s look. So if you record your video in 4x3 (not widescreen) or 16x9 (widescreen) we have the range of player sizes to suit your exact needs.</p> <p>We encode the video at the time of uploading in the size that you choose so that the picture and sound quality is retained throughout. Users can choose from the following sizes:</p></span> <br style="clear:both"> </div> Hope this makes sense...

    Read the article

  • using Python reduce over a list of pairs

    - by user248237
    I'm trying to pair together a bunch of elements in a list to create a final object, in a way that's analogous to making a sum of objects. I'm trying to use a simple variation on reduce where you consider a list of pairs rather than a flat list to do this. I want to do something along the lines of: nums = [1, 2, 3] reduce(lambda x, y: x + y, nums) except I'd like to add additional information to the sum that is specific to each element in the list of numbers nums. For example for each pair (a,b) in the list, run the sum as (a+b): nums = [(1, 0), (2, 5), (3, 10)] reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) This does not work: >>> reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> TypeError: 'int' object is unsubscriptable Why does it not work? I know I can encode nums as a flat list - that is not the point - I just want to be able to create a reduce operation that can iterate over a list of pairs, or over two lists of the same length simultaneously and pool information from both lists. thanks.

    Read the article

  • json parser empty result

    - by graybow
    I'm new in gwt and new in using firebug.I have valid json result from tesdb3.php {"item": [{"kode":"002","nama":"bambang gentolet"}, {"kode":"012","nama":"Algiz"}]} I add the xml with inherits name='com.google.gwt.json.JSON'/ inherits name="com.google.gwt.http.HTTP" / then i try to show it in the gwt with this code. public class Tesdb3 implements EntryPoint { String url= "http://localhost/phpmyadmin/tesdb3/datauser.php"; public void LoadData() throws RequestException{ RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); builder.sendRequest(null, new RequestCallback(){ @Override public void onError(Request request, Throwable exception) { Window.alert("error " + exception); } public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { Window.alert("ok -" + response.getText() + "-" + response.getStatusCode()); } else { Window.alert("error2 -" + response.getText()+ response.getStatusText() + "-" + response.getStatusCode()); } } }); } public void onModuleLoad() { try { LoadData(); } catch (RequestException e) { e.printStackTrace(); } } } I run it in development mode. not hosted mode. My code didn't show any error. But the result in window alert is "error2 --OK-0". result Net from firebug is 7 request: get Tesdb3.html?gwt.codeserv = 200ok get Tesdb3.css = 200ok get tesdb3.nocache.js = 200ok get hosted.html?tesdb3 = aborted get standard.css = 304 not modified get hosted.html?tesdb3 = 403 not modified get datauser.php = 200ok my question is: Why the response status code is 0, and the response status text is 'OK'? there was no eror in json or java code. why response.getText is empty? Why i can't get any json result even a single character?

    Read the article

  • Security considerations processing emails

    - by Timmy O' Tool
    I have process that will be reading emails from an account. The objective of the process is saving to a database those emails with image(s) as attachments. I will be saving sender, subject body and image path (the image will be saved on the process). I will be showing this information on a page so I would like to know all (or most of them :) ) security aspects to cover. I plan to sanitize the subject and body of the email. I can remove most of the tags, probably it would be enough keeping the <p> tag. I'm not sure if I can trust just in a sanitizer. I would like to HTML encode everything except for the <p> tag after sanitize, just in case. Any suggestion? I'm only accepting images as attachment as I said above, any security risk I have to take into account in relation to the attachment? Thanks!

    Read the article

  • Java RSA Encrypt using .NET XML Key File - need help

    - by badMonkey
    In .net I have generated the following public key file: <RSAKeyValue> <Modulus>xTSiS4+I/x9awUXcF66Ffw7tracsQfGCn6g6k/hGkLquHYMFTCYk4mOB5NwLwqczwvl8HkQfDShGcvrm47XHKUzA8iadWdA5n4toBECzRxiCWCHm1KEg59LUD3fxTG5ogGiNxDj9wSguCIzFdUxBYq5ot2J4iLgGu0qShml5vwk=</Modulus> <Exponent>AQAB</Exponent> .NET is happy to encrypt using it's normal methods. I am trying to use this key to encode a string in Java and am running into an Arithmetic problem (exception) when I attempt to encrypt the string. The following is the code I am using to encrypt: byte[] modulusBytes = Base64.decode(this.getString(R.string.public_key_modulus)); byte[] exponentBytes = Base64.decode(this.getString(R.string.public_key_exponent)); BigInteger modulus = new BigInteger( modulusBytes ); BigInteger exponent = new BigInteger( exponentBytes); RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey pubKey = fact.generatePublic(rsaPubKey); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherData = cipher.doFinal( new String("big kitty dancing").getBytes() ); It is the final line in the code block that fails. I have looked at numerous examples and this is the best I could come up with. If it is not obvious, the R.string.public_key_modulus is a copy/paste of the text in the Modulus element, same applies for exponent.

    Read the article

  • how to download data which upload to gae ,

    - by zjm1126
    this is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_args=None): if not template_args: template_args = {} path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_args)) class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file.encode('utf8')) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.out.write(o) application = webapp.WSGIApplication( [ ('/?', upload), ('/download',download), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() my index.html is : <form action="/" method="post"> <input type="file" name="file" /> <input type="submit" /> </form> and it show : <__main__.MyModel object at 0x02506830> but ,i don't want to see this , i want to download it , how to change my code to run, thanks

    Read the article

  • Striped table rows in ASP.NET MVC (without using jQuery or equivalent)

    - by Richard Ev
    When using an ASP.NET WebForms ListView control to display data in an HTML table I use the following technique in to "stripe" the table rows: <ItemTemplate> <tr class="<%# Container.DisplayIndex % 2 == 0 ? "" : "alternate" %>"> <!-- table cells in here --> </tr> </ItemTemplate> With the following CSS: tr.alternate { background-color: #EFF5FB; } I have just gone through the ASP.NET MVC Movie Database Application tutorial and learnt that in MVC-land table rows can be (must be?) constructed as follows: <% foreach (var item in Model) { %> <tr> <td> <%= Html.Encode(item.Title) %> </td> <!-- and so on for the rest of the table cells... --> </tr> <% } %> What can I add to this code to stripe the rows of my table? Note: I know that this can be done using jQuery, I want to know if it can be done another way. Edit If jQuery (or equivalent) is in your opinion the best or most appropriate post, I'd be interested in knowing why.

    Read the article

  • Obfuscating ids in Rails app

    - by fphilipe
    I'm trying to obfuscate all the ids that leave the server, i.e., ids appearing in URLs and in the HTML output. I've written a simple Base62 lib that has the methods encode and decode. Defining—or better—overwriting the id method of an ActiveRecord to return the encoded version of the id and adjusting the controller to load the resource with the decoded params[:id] gives me the desired result. The ids now are base62 encoded in the urls and the response displays the correct resource. Now I started to notice that subresources defined through has_many relationships aren't loading. e.g. I have a record called User that has_many Posts. Now User.find(1).posts is empty although there are posts with user_id = 1. My explanation is that ActiveRecord must be comparing the user_id of Post with the method id of User—which I've overwritten—instead of comparing with self[:id]. So basically this renders my approach useless. What I would like to have is something like defining obfuscates_id in the model and that the rest would be taken care of, i.e., doing all the encoding/decoding at the appropriate locations and preventing ids to be returned by the server. Is there any gem available or does somebody have a hint how to accomplish this? I bet I'm not the first trying this.

    Read the article

  • Problems with Getting Remote Contents using Google App Engine

    - by dade
    Here is the client side code. It is running insdide a Google Gadgets var params = {}; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON; var url = "http://invplatformtest.appspot.com/getrecent/"; gadgets.io.makeRequest(url, response, params); The response function is: function response(obj) { var r = obj.data; alert(r['name']); } while on the server end, the python code sending the JSON is: class GetRecent(webapp.RequestHandler): def get(self): self.response.out.write({'name':'geocities'}) #i know this is where the problem is so how do i encode json in GAE? which is just supposed to send back a Json encoded string but when i run this, the javascript throws the following error: r is null alert(r['name']); If i were recieving just TEXT contents and my server send TEXT everything works fine. I only get this problem when am trying to send JSON. Where exactly is the problem? Am i encoding the JSON the wrong way on AppEngine? I tried using the JSON library but it looks as if this is not supported. Where is the problem exactly? :(

    Read the article

  • Please help me optimize my Python code

    - by Haidon
    Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem. I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programming perspective I doubt it works well. How would I best go about optimizing the actions made upon the 'outtext' variable? At the moment it's basically doing a very similar thing four times over... import binascii import re import struct import sys infile = sys.argv[1] charenc = sys.argv[2] outFile=infile+'.tex' findreplace = [ ('TERM1', 'TERM2'), ('TERM3', 'TERM4'), ('TERM5', 'TERM6'), ] inF = open(infile,'rb') s=unicode(inF.read(),charenc) inF.close() # THIS IS VERY MESSY. for couple in findreplace: outtext=s.replace(couple[0],couple[1]) s=outtext for couple in findreplace: outtext=re.compile('Title: (.*)', re.I).sub(r'\\title'+ r'{\1}', s) s=outtext for couple in findreplace: outtext=re.compile('Author: (.*)', re.I).sub(r'\\author'+ r'{\1}', s) s=outtext for couple in findreplace: outtext=re.compile('Date: (.*)', re.I).sub(r'\\date'+ r'{\1}', s) s=outtext # END MESSY SECTION. outF = open(outFile,'wb') outF.write(outtext.encode('utf-8')) outF.close()

    Read the article

  • Audio Streaming Latency

    - by killianmcc
    I'm writing a UDP local area network video chat system and have got the video and audio streams working. However I'm experiencing a little latency (about half a second) in the audio and was wondering what codecs would provide the least latency. I'm using NAudio (http://naudio.codeplex.com/) which provides me access to the following codecs for streaming; Speex Narrow Band (VBR) Speex Wide Band (16kHz)(VBR) Speex Ultra Wide Band (32kHz)(VBR) DSP Group TrueSpeech (8.5kbps) GSM 6.10 (13kbps) Microsoft ADPCM (32.8kbps) G.711 a-law (64kbps) G.722 16kHz (64kbps) G.711 mu-law (64kbps) PCM 8kHz 16 bit uncompressed (128kbps) I've tried them out and I'm not noticing much difference. Is there any others that I should download and try to reduce latency? I'm only going to be sending voice over the connection but I'm not really worried about quality or background noises too much. UPDATE I'm sending the audio in blocks like so; waveIn = new WaveIn(); waveIn.BufferMilliseconds = 50; waveIn.DeviceNumber = inputDeviceNumber; waveIn.WaveFormat = codec.RecordFormat; waveIn.DataAvailable += waveIn_DataAvailable; void waveIn_DataAvailable(object sender, WaveInEventArgs e) { if (connected) { byte[] encoded = codec.Encode(e.Buffer, 0, e.BytesRecorded); udpSender.Send(encoded, encoded.Length); } }

    Read the article

  • How to check the correct radio button.

    - by MrW
    I have a Table containing some information that I need. All these rows also contains a column with a radio button in it so that the user is suppose to be able to check one of the rows as default. When I'm bringing the data back from the DB and want to select the one that's currentlly the default one. <% foreach (var item in (IEnumerable<Locale>) ViewData["Locales"]) { %> <tr> <td> <%= Html.Encode(item.Language.Name) %> </td> <td> <input type="radio" id="defaultLocale" name="defaultLocele" value="on" checked="<%= item.Default == false ? "false" : "true" %>" /> </td> I've also tried to do this: <input type="radio" id="defaultLocale" name="defaultLocele" value="on" checked="<%=item.Default == false ? "" : "checked" %>" /> but nothing seems to do the right thing. I always end up with having the last row in checked, which it isn't for sure.

    Read the article

  • Do you use cParseCSV source on iphone?

    - by Beomseok
    link! I'm using cParseCSV. I'm want to encode text of NSUTF8StringEncoding. But It does not work. 2010-04-05 08:53:16.616 test[12086:207] Fine thanks. 2010-04-05 08:53:16.617 test[12086:207] ????, ????. 2010-04-05 08:53:16.617 test[12086:207] Thank you. 2010-04-05 08:53:16.618 test[12086:207] ?????. 2010-04-05 08:53:16.618 test[12086:207] I'm all right. 2010-04-05 08:53:16.619 test[12086:207] ?? ????. 2010-04-05 08:53:16.620 test[12086:207] Oh, pretty good. 2010-04-05 08:53:16.620 test[12086:207] ?, ?? ???? 2010-04-05 08:53:16.621 test[12086:207] Alive and kicking. 2010-04-05 08:53:16.621 test[12086:207] ???????. 2010-04-05 08:53:16.622 test[12086:207] So so. 2010-04-05 08:53:16.623 test[12086:207] ?? ???. 2010-04-05 08:53:16.623 test[12086:207] Not too bad. 2010-04-05 08:53:16.624 test[12086:207] (null) 2010-04-05 08:53:16.625 test[12086:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPlaceholderString initWithString:]: nil argument' I don't know Why it happen...Please advice for me.

    Read the article

  • How to serialize each item in IEnumerable for ajax post

    - by bflemi3
    I have a PartialView that displays IEnumerable<Movie>. _MoviePartial.cshtml @foreach(var movie in Model) { <div class="content"> <span class="image"><img src="@movie.Posters.Profile" alt="@movie.Title"/></span> <span class="title">@movie.Title</span> <div class="score`"> <span class="critics-score">@movie.Ratings.CriticsScore</span> <span class="audience-score">@movie.Ratings.AudienceScore</span> </div> @Html.ActionLink("Add Movie", "Add", "MyMovies") </div> } When the user clicks the "Add Movie" ActionLink I am going to do an ajax post to add the selected movie to the users collection. My problem is that I would like to send the entire selected Movie class to the "Add" action but not sure how to serialize each movie since the entire Movie class is not rendered in the PartialView, just a few properties. I know I can serialize something like this... <script type="text/javascript"> var obj = @Html.Raw(Json.Encode(movie)); </script> But I'm not sure how that would work inside a foreach loop that renders html, especially inside a PartialView. So, just to be clear, when a user clicks the "Add Movie" ActionLink I would like to send the serialized Movie class for that respective movie to my controller via ajax. My questions is... Is there a better way to serialize each movie and append it to it's respective anchor? I know there's the data- html5 attribute but I thought they only allow string values, not json objects. I also know I could use jQuery's .data() function but I'm struggling to think through how to get that to run from a PartialView, especially since the html rendered by _MoviePartial.cshtml may be returned from a controller via ajax.

    Read the article

< Previous Page | 35 36 37 38 39 40 41 42 43 44 45 46  | Next Page >