Search Results

Search found 21563 results on 863 pages for 'context free grammar'.

Page 8/863 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Strange (Undefined?) Behavior of Free in C

    - by Chris Cirefice
    This is really strange... and I can't debug it (tried for about two hours, debugger starts going haywire after a while...). Anyway, I'm trying to do something really simple: Free an array of strings. The array is in the form: char **myStrings. The array elements are initialized as: myString[index] = malloc(strlen(word)); myString[index] = word; and I'm calling a function like this: free_memory(myStrings, size); where size is the length of the array (I know this is not the problem, I tested it extensively and everything except this function is working). free_memory looks like this: void free_memory(char **list, int size) { for (int i = 0; i < size; i ++) { free(list[i]); } free(list); } Now here comes the weird part. if (size> strlen(list[i])) then the program crashes. For example, imagine that I have a list of strings that looks something like this: myStrings[0] = "Some"; myStrings[1] = "random"; myStrings[2] = "strings"; And thus the length of this array is 3. If I pass this to my free_memory function, strlen(myStrings[0]) > 3 (4 3), and the program crashes. However, if I change myStrings[0] to be "So" instead, then strlen(myStrings[0]) < 3 (2 < 3) and the program does not crash. So it seems to me that free(list[i]) is actually going through the char[] that is at that location and trying to free each character, which I imagine is undefined behavior. The only reason I say this is because I can play around with the size of the first element of myStrings and make the program crash whenever I feel like it, so I'm assuming that this is the problem area. Note: I did try to debug this by stepping through the function that calls free_memory, noting any weird values and such, but the moment I step into the free_memory function, the debugger crashes, so I'm not really sure what is going on. Nothing is out of the ordinary until I enter the function, then the world explodes. Another note: I also posted the shortened version of the source for this program (not too long; Pastebin) here. I am compiling on MinGW with the c99 flag on. PS - I just thought of this. I am indeed passing numUniqueWords to the free function, and I know that this does not actually free the entire piece of memory that I allocated. I've called it both ways, that's not the issue. And I left it how I did because that is the way that I will be calling it after I get it to work in the first place, I need to revise some of my logic in that function. Source, as per request (on-site): #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include "words.h" int getNumUniqueWords(char text[], int size); int main(int argc, char* argv[]) { setvbuf(stdout, NULL, 4, _IONBF); // For Eclipse... stupid bug. --> does NOT affect the program, just the output to console! int nbr_words; char text[] = "Some - \"text, a stdin\". We'll have! also repeat? We'll also have a repeat!"; int length = sizeof(text); nbr_words = getNumUniqueWords(text, length); return 0; } void free_memory(char **list, int size) { for (int i = 0; i < size; i ++) { // You can see that printing the values is fine, as long as free is not called. // When free is called, the program will crash if (size > strlen(list[i])) //printf("Wanna free value %d w/len of %d: %s\n", i, strlen(list[i]), list[i]); free(list[i]); } free(list); } int getNumUniqueWords(char text[], int length) { int numTotalWords = 0; char *word; printf("Length: %d characters\n", length); char totalWords[length]; strcpy(totalWords, text); word = strtok(totalWords, " ,.-!?()\"0123456789"); while (word != NULL) { numTotalWords ++; printf("%s\n", word); word = strtok(NULL, " ,.-!?()\"0123456789"); } printf("Looks like we counted %d total words\n\n", numTotalWords); char *uniqueWords[numTotalWords]; char *tempWord; int wordAlreadyExists = 0; int numUniqueWords = 0; char totalWordsCopy[length]; strcpy(totalWordsCopy, text); for (int i = 0; i < numTotalWords; i++) { uniqueWords[i] = NULL; } // Tokenize until all the text is consumed. word = strtok(totalWordsCopy, " ,.-!?()\"0123456789"); while (word != NULL) { // Look through the word list for the current token. for (int j = 0; j < numTotalWords; j ++) { // Just for clarity, no real meaning. tempWord = uniqueWords[j]; // The word list is either empty or the current token is not in the list. if (tempWord == NULL) { break; } //printf("Comparing (%s) with (%s)\n", tempWord, word); // If the current token is the same as the current element in the word list, mark and break if (strcmp(tempWord, word) == 0) { printf("\nDuplicate: (%s)\n\n", word); wordAlreadyExists = 1; break; } } // Word does not exist, add it to the array. if (!wordAlreadyExists) { uniqueWords[numUniqueWords] = malloc(strlen(word)); uniqueWords[numUniqueWords] = word; numUniqueWords ++; printf("Unique: %s\n", word); } // Reset flags and continue. wordAlreadyExists = 0; word = strtok(NULL, " ,.-!?()\"0123456789"); } // Print out the array just for funsies - make sure it's working properly. for (int x = 0; x <numUniqueWords; x++) { printf("Unique list %d: %s\n", x, uniqueWords[x]); } printf("\nNumber of unique words: %d\n\n", numUniqueWords); // Right below is where things start to suck. free_memory(uniqueWords, numUniqueWords); return numUniqueWords; }

    Read the article

  • Set Context User Principal for Customized Authentication in SignalR

    - by Shaun
    Originally posted on: http://geekswithblogs.net/shaunxu/archive/2014/05/27/set-context-user-principal-for-customized-authentication-in-signalr.aspxCurrently I'm working on a single page application project which is built on AngularJS and ASP.NET WebAPI. When I need to implement some features that needs real-time communication and push notifications from server side I decided to use SignalR. SignalR is a project currently developed by Microsoft to build web-based, read-time communication application. You can find it here. With a lot of introductions and guides it's not a difficult task to use SignalR with ASP.NET WebAPI and AngularJS. I followed this and this even though it's based on SignalR 1. But when I tried to implement the authentication for my SignalR I was struggled 2 days and finally I got a solution by myself. This might not be the best one but it actually solved all my problem.   In many articles it's said that you don't need to worry about the authentication of SignalR since it uses the web application authentication. For example if your web application utilizes form authentication, SignalR will use the user principal your web application authentication module resolved, check if the principal exist and authenticated. But in my solution my ASP.NET WebAPI, which is hosting SignalR as well, utilizes OAuth Bearer authentication. So when the SignalR connection was established the context user principal was empty. So I need to authentication and pass the principal by myself.   Firstly I need to create a class which delivered from "AuthorizeAttribute", that will takes the responsible for authenticate when SignalR connection established and any method was invoked. 1: public class QueryStringBearerAuthorizeAttribute : AuthorizeAttribute 2: { 3: public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) 4: { 5: } 6:  7: public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod) 8: { 9: } 10: } The method "AuthorizeHubConnection" will be invoked when any SignalR connection was established. And here I'm going to retrieve the Bearer token from query string, try to decrypt and recover the login user's claims. 1: public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) 2: { 3: var dataProtectionProvider = new DpapiDataProtectionProvider(); 4: var secureDataFormat = new TicketDataFormat(dataProtectionProvider.Create()); 5: // authenticate by using bearer token in query string 6: var token = request.QueryString.Get(WebApiConfig.AuthenticationType); 7: var ticket = secureDataFormat.Unprotect(token); 8: if (ticket != null && ticket.Identity != null && ticket.Identity.IsAuthenticated) 9: { 10: // set the authenticated user principal into environment so that it can be used in the future 11: request.Environment["server.User"] = new ClaimsPrincipal(ticket.Identity); 12: return true; 13: } 14: else 15: { 16: return false; 17: } 18: } In the code above I created "TicketDataFormat" instance, which must be same as the one I used to generate the Bearer token when user logged in. Then I retrieve the token from request query string and unprotect it. If I got a valid ticket with identity and it's authenticated this means it's a valid token. Then I pass the user principal into request's environment property which can be used in nearly future. Since my website was built in AngularJS so the SignalR client was in pure JavaScript, and it's not support to set customized HTTP headers in SignalR JavaScript client, I have to pass the Bearer token through request query string. This is not a restriction of SignalR, but a restriction of WebSocket. For security reason WebSocket doesn't allow client to set customized HTTP headers from browser. Next, I need to implement the authentication logic in method "AuthorizeHubMethodInvocation" which will be invoked when any SignalR method was invoked. 1: public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod) 2: { 3: var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId; 4: // check the authenticated user principal from environment 5: var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment; 6: var principal = environment["server.User"] as ClaimsPrincipal; 7: if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated) 8: { 9: // create a new HubCallerContext instance with the principal generated from token 10: // and replace the current context so that in hubs we can retrieve current user identity 11: hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId); 12: return true; 13: } 14: else 15: { 16: return false; 17: } 18: } Since I had passed the user principal into request environment in previous method, I can simply check if it exists and valid. If so, what I need is to pass the principal into context so that SignalR hub can use. Since the "User" property is all read-only in "hubIncomingInvokerContext", I have to create a new "ServerRequest" instance with principal assigned, and set to "hubIncomingInvokerContext.Hub.Context". After that, we can retrieve the principal in my Hubs through "Context.User" as below. 1: public class DefaultHub : Hub 2: { 3: public object Initialize(string host, string service, JObject payload) 4: { 5: var connectionId = Context.ConnectionId; 6: ... ... 7: var domain = string.Empty; 8: var identity = Context.User.Identity as ClaimsIdentity; 9: if (identity != null) 10: { 11: var claim = identity.FindFirst("Domain"); 12: if (claim != null) 13: { 14: domain = claim.Value; 15: } 16: } 17: ... ... 18: } 19: } Finally I just need to add my "QueryStringBearerAuthorizeAttribute" into the SignalR pipeline. 1: app.Map("/signalr", map => 2: { 3: // Setup the CORS middleware to run before SignalR. 4: // By default this will allow all origins. You can 5: // configure the set of origins and/or http verbs by 6: // providing a cors options with a different policy. 7: map.UseCors(CorsOptions.AllowAll); 8: var hubConfiguration = new HubConfiguration 9: { 10: // You can enable JSONP by uncommenting line below. 11: // JSONP requests are insecure but some older browsers (and some 12: // versions of IE) require JSONP to work cross domain 13: // EnableJSONP = true 14: EnableJavaScriptProxies = false 15: }; 16: // Require authentication for all hubs 17: var authorizer = new QueryStringBearerAuthorizeAttribute(); 18: var module = new AuthorizeModule(authorizer, authorizer); 19: GlobalHost.HubPipeline.AddModule(module); 20: // Run the SignalR pipeline. We're not using MapSignalR 21: // since this branch already runs under the "/signalr" path. 22: map.RunSignalR(hubConfiguration); 23: }); On the client side should pass the Bearer token through query string before I started the connection as below. 1: self.connection = $.hubConnection(signalrEndpoint); 2: self.proxy = self.connection.createHubProxy(hubName); 3: self.proxy.on(notifyEventName, function (event, payload) { 4: options.handler(event, payload); 5: }); 6: // add the authentication token to query string 7: // we cannot use http headers since web socket protocol doesn't support 8: self.connection.qs = { Bearer: AuthService.getToken() }; 9: // connection to hub 10: self.connection.start(); Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • Is there a free alternate to MIrrorfolder backup

    - by Ali
    Hi guys is there a free alternate to Mirror folder for taking real time automated backups of files and folders. Something which I could setup once to backup certain files and folders to a location on my network and rely on it to take backups on its own periodically.

    Read the article

  • I need help translating this portion of the ECMAScript grammar?

    - by ChaosPandion
    I've been working on my own implementation of ECMAScript for quite some time now. I have basically done everything by hand to help gain a deep understanding of the process. Repeated attempts to analyze and understand this portion of the grammar have failed so I've been working on the run time instead. Now I am at a point were I will be working on object literals so I really need to polish my syntactic analyzer. Can anyone put this in terms a language parser novice could understand? My biggest source of confusion is the following: new MemberExpression Arguments This is supposed to be a member expression, but this seemingly conflicts with the following: NewExpression : MemberExpression new NewExpression Is a new expression a member expression or a left hand side expression? To be honest I am having trouble laying out the proper C# classes for the concrete grammar. MemberExpression : PrimaryExpression FunctionExpression MemberExpression [ Expression ] MemberExpression . IdentifierName new MemberExpression Arguments NewExpression : MemberExpression new NewExpression CallExpression : MemberExpression Arguments CallExpression Arguments CallExpression [ Expression ] CallExpression . IdentifierName LeftHandSideExpression : NewExpression CallExpression

    Read the article

  • Whay types of grammar files are usable for spoken voice recognition?

    - by user1413199
    I'm using the System.Speech library in C# and I would like to create a smaller file to house commands as opposed to the default grammar. I'm not totally sure what I need. I've been looking at several different things but I don't really have any idea what I'm doing. I've read up on some stuff in ANTLR and looked at NuGram from NuEcho. I understand what a grammar file is and roughly how to create one but I'm not sure how they're used specifically for deciphering spoken words.

    Read the article

  • Android change context for findViewById to super from inline class

    - by wuntee
    I am trying to get the value of a EditText in a dialog box. A the "*"'ed line in the following code, the safeNameEditText is null; i am assuming because the 'findVeiwById' is searching on the context of the 'AlertDialog.OnClickListener'; How can I get/change the context of that 'findViewById' call? protected Dialog onCreateDialog(int id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); switch(id){ case DIALOG_NEW_SAFE: builder.setTitle(R.string.news_safe); builder.setIcon(android.R.drawable.ic_menu_add); LayoutInflater factory = LayoutInflater.from(this); View newSafeView = factory.inflate(R.layout.newsafe, null); builder.setView(newSafeView); builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { * EditText safeNameEditText = (EditText) findViewById(R.id.new_safe_name); String safeName = safeNameEditText.getText().toString(); Log.i(LOG, safeName); setSafeDao(safeName); } }); builder.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return(builder.create()); default: return(null); } }

    Read the article

  • Free space not reclaimed after online resizing ext4 in Ubuntu 9.10

    - by TiansHUo
    My root partition was filling up, with only 500 mbs left, I wanted to resize my root partition from 20 Gb to 40Gb So I resized my partition by using these steps: Using Gparted to resize another partition to give space for the EXT4 Using fdisk, deleting the root partition (on /dev/sda2), and creating it again using the new size resize2fs /dev/sda2 Updating grub2 But now the problem is that although I can boot in my new partition and the new partition shows it is 40Gb, but the free size was still 500mb. So I booted from a LiveCD and checked with e2fsck -p /dev/sda2, it reported clean. So I added the -f flag (force check), still, the drive is full.

    Read the article

  • iPhone/iPad: Get Alerts When Paid Apps Go Free

    - by Gopinath
    iPhone users has thousands of cool applications to choose. These apps are either paid or absolutely free. Many of the paid applications goes free for either a limited time or forever depending on the mood of their developers. Will it not be cool to get alerts whenever a paid app goes free? Yeah, it will be great. Free App Alert is a handy website that checks iTunes store regularly and sends alerts to it’s subscribers about the apps that have gone from paid to free. You can receive the alerts by following them on twitter, facebook or subscribing to the traditional RSS feeds(yeah RSS is a traditional technology). The home page of this website shows the apps that have gone free today and you can browse through the previous day free apps listing with the help of links available at the bottom. Free App Alert is definitely a cool site to check out for iPhone/iPod/iPad users and certainly easier than scrolling through iTunes store and checking prices. Tip: Immediately download the app that have gone from paid to free as many apps are free for limited time. You can see many free apps going back to paid version if you go through the previous pages the website. Join us on Facebook to read all our stories right inside your Facebook news feed.

    Read the article

  • Is there any existing (old) game that released graphic as free or open source?

    - by Alexey Petrushin
    I'd like to (re)create an online version (html5/JS) of some old game, for example something like HoM&M 2. Maybe, some of old games were released as free or open source (I'm interested in the graphical assets only)? I heard something about Red Alert been released as free, but I'm not sure if it's permitted to reuse graphical assets in such manner. Do You know such games? Another question - can You please share Your thoughts, rough estimate - how much it will cost to pay an artist to create graphics similar to HoM&M 2?

    Read the article

  • Preffered lambda syntax?

    - by Roger Alsing
    I'm playing around a bit with my own C like DSL grammar and would like some oppinions. I've reserved the use of "(...)" for invocations. eg: foo(1,2); My grammar supports "trailing closures" , pretty much like Ruby's blocks that can be passed as the last argument of an invocation. Currently my grammar support trailing closures like this: foo(1,2) { //parameterless closure passed as the last argument to foo } or foo(1,2) [x] { //closure with one argument (x) passed as the last argument to foo print (x); } The reason why I use [args] instead of (args) is that (args) is ambigious: foo(1,2) (x) { } There is no way in this case to tell if foo expects 3 arguments (int,int,closure(x)) or if foo expects 2 arguments and returns a closure with one argument(int,int) - closure(x) So thats pretty much the reason why I use [] as for now. I could change this to something like: foo(1,2) : (x) { } or foo(1,2) (x) -> { } So the actual question is, what do you think looks best? [...] is somewhat wrist unfriendly. let x = [a,b] { } Ideas?

    Read the article

  • How well do free-to-open-source-projects policies work in practice?

    - by Steve314
    In comparison with an open source license and requesting donations, is a free-for-open-source-projects (or free for non-commercial developers) closed source and otherwise commercial project likely to get more license fees? Or just to alienate potential users? Assume the project has value to programmers - I'm looking for generalizations here, though specific examples comparing existing projects will be very interesting. What I have in mind involves code generating programming utilities. And one issue I can think of, either way, is a near total inability to enforce any license restrictions. After all, I can't go around the internet demanding that everyone show me their source code just in case!

    Read the article

  • Preferred lambda syntax?

    - by Roger Alsing
    I'm playing around a bit with my own C like DSL grammar and would like some oppinions. I've reserved the use of "(...)" for invocations. eg: foo(1,2); My grammar supports "trailing closures" , pretty much like Ruby's blocks that can be passed as the last argument of an invocation. Currently my grammar support trailing closures like this: foo(1,2) { //parameterless closure passed as the last argument to foo } or foo(1,2) [x] { //closure with one argument (x) passed as the last argument to foo print (x); } The reason why I use [args] instead of (args) is that (args) is ambigious: foo(1,2) (x) { } There is no way in this case to tell if foo expects 3 arguments (int,int,closure(x)) or if foo expects 2 arguments and returns a closure with one argument(int,int) - closure(x) So thats pretty much the reason why I use [] as for now. I could change this to something like: foo(1,2) : (x) { } or foo(1,2) (x) -> { } So the actual question is, what do you think looks best? [...] is somewhat wrist unfriendly. let x = [a,b] { } Ideas?

    Read the article

  • Best (physical) DRM free MP3 players [closed]

    - by alex
    I'm looking to purchase an MP3 player soon. It should: Be compatible with Windows Media Player Hold at least 40 GB Be completely DRM free Be reliable and well built. I don't want to repeat my iRiver experience. Be small enough to be comfortably carried in my pocket. I don't care about looks, this can be the ugliest beast ever. Knowing this, what should I buy? [I figured this is almost on topic for Super User, if not: vote to close it.]

    Read the article

  • Generating n statements from context-free grammars

    - by Dervin Thunk
    Hello, So not to reinvent the wheel, I would like to know what has already been done about generating random statements from a context-free language (like those produced by yacc, etc.). These grammars are primarily for parsing, but maybe someone has done some generation for testing the parsers? Thanks

    Read the article

  • jQuery Context Menu Plugin and Capturing Right-Click

    - by Ben Griswold
    I was thrilled to find Cory LaViska’s jQuery Context Menu Plugin a few months ago. In very little time, I was able to integrate the context menu with the jQuery Treeview.  I quickly had a really pretty user interface which took full advantage of limited real estate.  And guess what.  As promised, the plugin worked in Chrome, Safari 3, IE 6/7/8, Firefox 2/3 and Opera 9.5.  Everything was perfect and I shipped to the Integration Environment. One thing kept bugging though – right clicks aren’t the standard in a web environment. Sure, when one hovers over the treeview node, the mouse changed from an arrow to a pointer, but without help text most users will certainly left-click rather than right. As I was already doubting the design decision, we did some Mac testing.  The context menu worked in Firefox but not Safari.  Damn.  That’s when I started digging into the Madness of Javascript Mouse Events.  Don’t tell, but it’s complicated.  About as close as one can get to capture the right-click mouse event on all major browsers on Windows and Mac is this: if (event.which == null) /* IE case */ button= (event.button < 2) ? "LEFT" : ((event.button == 4) ? "MIDDLE" : "RIGHT"); else /* All others */ button= (event.which < 2) ? "LEFT" : ((event.which == 2) ? "MIDDLE" : "RIGHT"); Yikes.  The content menu code was simply checking if event.button == 2.  No problem.  Cory offers a jQuery Right Click Plugin which I’m sure works for windows but probably not the Mac either.  (Please note I haven’t verified this.) Anyway, I decided to address my UI design concern and the Safari Mac issue in one swoop.  I decided to make the context menu respond to any mouse click event.  This didn’t take much – especially after seeing how Bill Beckelman updated the library to recognize the left click. First, I added an AnyClick option to the library defaults: // Any click may trigger the dropdown and that's okay // See Javascript Madness: Mouse Events – http: //unixpapa.com/js/mouse.html if (o.anyClick == undefined) o.anyClick = false; And then I trigger the context menu dropdown based on the following conditional: if (evt.button == 2 || o.anyClick) { Nothing tricky about that, right?  Finally, I updated my menu setup to include the AnyClick value, if true: $('.member').contextMenu({ menu: 'memberContextMenu', anyClick: true },             function (action, el, pos) {                 … Now the context menu works in “all” environments if you left, right or even middle click.  Download jQuery Context Menu Plugin for Any Click *Opera 9.5 has an option to allow scripts to detect right-clicks, but it is disabled by default. Furthermore, Opera still doesn’t allow JavaScript to disable the browser’s default context menu which causes a usability conflict.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >