Search Results

Search found 2240 results on 90 pages for 'assert redirected to'.

Page 18/90 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Eclipse editor closing itself

    - by Rohit
    I have been facing this weird problem for some days ... When i try to open my eclipse editor it closes itself and just show some error message that is logged in my .log file .. I am pasting my log file content here .. help ! !ENTRY org.eclipse.jface 4 0 2012-09-23 01:45:17.443 !MESSAGE An error has occurred. See error log for more details. !STACK 0 org.eclipse.core.runtime.AssertionFailedException: assertion failed: The application has not been initialized. at org.eclipse.core.runtime.Assert.isTrue(Assert.java:110) at org.eclipse.core.internal.runtime.InternalPlatform.assertInitialized(InternalPlatform.java:148) at org.eclipse.core.internal.runtime.InternalPlatform.getAdapterManager(InternalPlatform.java:169) at org.eclipse.core.runtime.Platform.getAdapterManager(Platform.java:628) at org.eclipse.ui.part.IntroPart.getAdapter(IntroPart.java:143) at org.eclipse.ui.internal.ViewIntroAdapterPart.getAdapter(ViewIntroAdapterPart.java:117) at org.eclipse.ui.internal.util.Util.getAdapter(Util.java:109) at org.eclipse.ui.internal.services.WorkbenchSourceProvider.getShowInSource(WorkbenchSourceProvider.java:406) at org.eclipse.ui.internal.services.WorkbenchSourceProvider.getContext(WorkbenchSourceProvider.java:410) at org.eclipse.ui.internal.services.WorkbenchSourceProvider.updateActivePart(WorkbenchSourceProvider.java:478) at org.eclipse.ui.internal.services.WorkbenchSourceProvider.checkActivePart(WorkbenchSourceProvider.java:305) at org.eclipse.ui.internal.services.WorkbenchSourceProvider.checkActivePart(WorkbenchSourceProvider.java:300) at org.eclipse.ui.internal.services.WorkbenchSourceProvider$2.windowDeactivated(WorkbenchSourceProvider.java:270) at org.eclipse.ui.internal.Workbench$15.run(Workbench.java:1026) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.ui.internal.Workbench.fireWindowDeactivated(Workbench.java:1024) at org.eclipse.ui.internal.WorkbenchWindow$29.shellDeactivated(WorkbenchWindow.java:3169) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:111) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1282) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1263) at org.eclipse.swt.widgets.Shell.filterProc(Shell.java:748) at org.eclipse.swt.widgets.Display.filterProc(Display.java:1543)

    Read the article

  • ScrollViewer.EnsureVisible for Windows Phone

    - by Daniel Moth
    In my Translator By Moth app, on both the current and saved pivot pages the need arose to programmatically scroll to the bottom. In the former, case it is when a translation takes place (if the text is too long, I want to scroll to the bottom of the translation so the user can focus on that, and not their input text for translation). In the latter case it was when a new translation is saved (it is added to the bottom of the list, so scrolling is required to make it visible). On both pages a ScrollViewer is used. In my exploration of the APIs through intellisense and msdn I could not find a method that auto scrolled to the bottom. So I hacked together a solution where I added a blank textblock to the bottom of each page (within the ScrollViewer, but above the translated textblock and the saved list) and tried to make it scroll it into view from code. After searching the web I found a little algorithm that did most of what I wanted (sorry, I do not have the reference handy, but thank you whoever it was) that after minor tweaking I turned into an extension method for the ScrollViewer that is very easy to use: this.Scroller.EnsureVisible(this.BlankText); The method itself I share with you here: public static void EnsureVisible(this System.Windows.Controls.ScrollViewer scroller, System.Windows.UIElement uiElem) { System.Diagnostics.Debug.Assert(scroller != null); System.Diagnostics.Debug.Assert(uiElem != null); scroller.UpdateLayout(); double maxScrollPos = scroller.ExtentHeight - scroller.ViewportHeight; double scrollPos = scroller.VerticalOffset - scroller.TransformToVisual(uiElem).Transform(new System.Windows.Point(0, 0)).Y; if (scrollPos > maxScrollPos) scrollPos = maxScrollPos; else if (scrollPos < 0) scrollPos = 0; scroller.ScrollToVerticalOffset(scrollPos); } I am sure there are better ways, but this "worked for me" :-) Comments about this post by Daniel Moth welcome at the original blog.

    Read the article

  • Robots.txt practices with .htaccess redirections (inherits)

    - by Jayhal
    I have a question regarding how to write robots.txt files for many domains and subdomains with redirects in place. We have a hosting account that enacts primary and add-on domains. All of our domains and subdomains, including the primary domain, is redirected via htaccess 301s to their own subdirectories in the primary domain's root directory. I'm confused about how I would write the robots.txt for certain directories. First, I wanted to confirm I am right in understanding that for domains and subdomains, crawlers will look to the directory that acts as that urls root directory for the crawling rules(robots.txt). Also, that a directory will not be affected by a robots.txt present in their parent directory if the directory has its own domain/subdomain, and that url is the one being accessed by crawlers. (Am pretty sure, but I wanted to confirm I didnt have a fundamentally flawed understanding of robots.txt) In the original root directory on the account(where the primary domain was directed before htaccess was put in place) what should the robots.txt contain? When crawlers look to crawl our primary domain, will they look to the original root directory for the robots.txt or will they reference the file contained in the new subdirectory where all the primary domain's site files are located? If so, what should the root's robot.txt include if anything at all. Would I be right to include a simple 'disallow: /' for all agents, and then include more specific robots.txt files in each subdirectory with more specific instructions. Would that affect the crawling of the directory where the primary domain is now redirected? Any help is greatly appreciated, Thanks!

    Read the article

  • DNS - domain conflict?

    - by Stefanos.Ioannou
    I was given two domains: domain.com & domain.info (they are on GoDaddy). And I was also given two servers, 107.105.38.99 - Rails app and 107.107.90.17 - Wordpress platform, on Digital Ocean. At first, I was instructed to associate domain.com with the 107.107.38.99 (Rails app). Then I was instructed to de-associate this IP with domain.com and associated the 107.107.90.17 with the domain name domain.com. Then I was instructed to associated domain.info with the 107.107.38.99 (Rails app). Right now, when I go to domain.com the WordPress platform (107.107.90.17) loads fine and that is what is expected. But when I go to domain.info for the Rails app (107.107.38.99) I get redirected to domain.com. This is not expected and this is really weird for me. When I ping domain.info I get this: PING domain.info (107.107.38.99): 56 data bytes 64 bytes from 107.107.38.99: icmp_seq=0 ttl=50 time=74.601 ms Which is the expected result showing the correct IP but I don't understand why I get redirected to domain.com...(which when I ping is:) domain 64 bytes from 107.107.90.17: icmp_seq=0 ttl=50 time=75.057 ms The PTR Records on Digital Ocean are as follows: IP Address PTR Record 107.107.38.99 domain.info. 107.107.90.17 domain.com. and the DNS configurations on Digital Ocean are: domain.com A: @ 107.107.90.17 CNAME: * @ domain.info A: @ 107.107.38.99 CNAME: * @ I am not sure what the issue is, if you have any clue please let me know, I will be really grateful. If you need any other info let me know.

    Read the article

  • Overriding component behavior

    - by deft_code
    I was thinking of how to implement overriding of behaviors in a component based entity system. A concrete example, an entity has a heath component that can be damaged, healed, killed etc. The entity also has an armor component that limits the amount of damage a character receives. Has anyone implemented behaviors like this in a component based system before? How did you do it? If no one has ever done this before why do you think that is. Is there anything particularly wrong headed about overriding component behaviors? Below is rough sketch up of how I imagine it would work. Components in an entity are ordered. Those at the front get a chance to service an interface first. I don't detail how that is done, just assume it uses evil dynamic_casts (it doesn't but the end effect is the same without the need for RTTI). class IHealth { public: float get_health( void ) const = 0; void do_damage( float amount ) = 0; }; class Health : public Component, public IHealth { public: void do_damage( float amount ) { m_damage -= amount; } private: float m_health; }; class Armor : public Component, public IHealth { public: float get_health( void ) const { return next<IHealth>().get_health(); } void do_damage( float amount ) { next<IHealth>().do_damage( amount / 2 ); } }; entity.add( new Health( 100 ) ); entity.add( new Armor() ); assert( entity.get<IHealth>().get_health() == 100 ); entity.get<IHealth>().do_damage( 10 ); assert( entity.get<IHealth>().get_health() == 95 ); Is there anything particularly naive about the way I'm proposing to do this?

    Read the article

  • Facebook shared links not opening (Redirecting correctly) [on hold]

    - by Hammad
    I have been in a problem and after hours of searching find nothing useful to counter it. I have a website, and that website has RSS feed attached to facebook page. As I post the content to website it also appears on facebook page. But I have people complaining on my page that my posts don't open when they click the link to read the details. Since I am a Chrome user and didn't notice this happening for months. But as I checked it through firefox and Internet Explorer, I found the links shared actually don't open with these browswers. They only work in Chrome, means they are properly redirected in chrome browser and not in firefox and IE. Whenever I click on links of posts on my page through IE or firefox the url does not simply redirect to my website and I get to see nothing as if I am not connecting to Internet. When examining URL I see this: http://www.facebook.com/l.php?u=http%3A%2F%2Fbit.ly%2F112NVO9&h=EAQHDgTUv&s=1 Which shows that facebook is not redirecting the links properly. Moreover I also use link shortening service bit.ly to shorten my shared links. I have checked same problem exists even if I don't shorten my links. And I checked I am not alone, even the tech giant website mashable.com links also don't open in IE and FF from facebook, they only open in Chrome. From mobile phone the links don't open (redirected properly) even in chrome. Can anyone tell me what is the issue? Nothing much is written about it on Internet as no once has faced this problem. P.S: I have checked from different systems, the problem persists.

    Read the article

  • Why does 301 redirect work for http but not for https?

    - by Tom G
    Through my domain registrar I have set up a domain, essayme.co.uk, to automatically forward to https://google.com. If I go to http://essayme.co.uk it works as expected and redirects me to https://google.com. $curl -i http://essayme.co.uk HTTP/1.1 301 Moved Permanently Cache-Control: max-age=900 Content-Type: text/html Location: https://google.com Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sat, 07 Jun 2014 11:14:16 GMT Content-Length: 0 Age: 0 Connection: keep-alive However, if I go to https://essayme.co.uk it just freezes and times out. $curl -i https://essayme.co.uk curl: (7) Failed connect to essayme.co.uk:443; Operation timed out What is happening in the second case? (and, if possible, how can I get the redirect to work for https?) Problem background/clarification: I don't have an SSL certificate for the essayme.co.uk domain above, but I do for my live domain (let's call it mywebsite.com), and I was seeing the exact same problem on this domain (hence why I'm trying to debug the problem). Unfortunately I can't experiment with the live domain (as it's live) and I would like to avoid having to buy a second certificate for essayme.co.uk just for debugging (unless absolutely necessary). The problem I was seeing: my live domain, mywebsite.com (not its real name), has a valid SSL certificate. Visiting https://www.mywebsite.com displayed the webpage as expected. I had set up forwarding (like in the question above) from the naked domain (mywebsite.com) to https://www.mywebsite.com) Visiting http://mywebsite.com redirected to https://www.mywebsite.com as expected. However, visiting https://mywebsite.com would freeze and time out (as in the question above). I also tried forwarding it to http://www.otherwebsite.com as an experiment (i.e. forwarding to another site that does not use SSL), but the result was the same: Visiting http://mywebsite.com redirected to http://www.otherwebsite.com as expected. Visiting https://mywebsite.com would freeze and time out again. So I set up essayme.co.uk as an experiment to try and understand why it doesn't work.

    Read the article

  • Is this method of writing Unit Tests correct?

    - by aspdotnetuser
    I have created a small C# project to help me learn how to write good unit tests. I know that one important rule of unit testing is to test the smallest 'unit' of code possible so that if it fails you know exactly what part of the code needs to fixed. I need help with the following before I continue to implement more unit tests for the project: If I have a Car class, for example, that creates a new Car object which has various attributes that are calculated when its' constructor method is called, would the two following tests be considered as overkill? Should there be one test that tests all calculated attributes of the Car object instead? [Test] public void CarEngineCalculatedValue() { BusinessObjects.Car car= new BusinessObjects.Car(); Assert.GreaterOrEqual(car.Engine, 1); } [Test] public void CarNameCalculatedValue() { BusinessObjects.Car car= new BusinessObjects.Car(); Assert.IsNotNull(car.Name); } Should I have the above two test methods to test these things or should I have one test method that asserts the Car object has first been created and then test these things in the same test method?

    Read the article

  • How to handle new domain names?

    - by michael
    I have a new product which I'll call a pen ink reloader. I have a website using my products name, for example, www.inkywink.com which I want to have accessed by searches for keywords such as "pen ink", "pen out of ink" "ink for pens" etc. , since nobody knows that a pen ink reloader exists. I see that its quite difficult to get on front page for these keywords since they have lots of competition. However I notice that the exact phrases I want to rank highly for are available as domains. I purchase "www.penink.com" and "penoutofink.com" which for arguments sake are highly searched and the perfect keywords to get eyes on my money site www.inkywink.com . Two questions: 1. What is my best option to leverage those names so that they appear near top of searches so that I can get traffic to my money site? Do I just have them redirect 301 to inkywink.com or should I create small original content on each with links to my main site? 2. If I just have them redirected to inkywink.com, am I able to use keywords in metatag and headers for each site separately or do they all automatically obtain the same headers and tags as the site to which theyre redirected ? Thanks to anyone who can help as I'm a real newbie to all this.

    Read the article

  • Making WatiN Wait for JQuery document.Ready() Functions to Complete

    - by Steve Wilkes
    WatiN's DomContainer.WaitForComplete() method pauses test execution until the DOM has finished loading, but if your page has functions registered with JQuery's ready() function, you'll probably want to wait for those to finish executing before testing it. Here's a WatiN extension method which pauses test execution until that happens. JQuery (as far as I can see) doesn't provide an event or other way of being notified of when it's finished running your ready() functions, so you have to get around it another way. Luckily, because ready() executes the functions it's given in the order they're registered, you can simply register another one to add a 'marker' div to the page, and tell WatiN to wait for that div to exist. Here's the code; I added the extension method to Browser rather than DomContainer (Browser derives from DomContainer) because it's the sort of thing you only execute once for each of the pages your test loads, so Browser seemed like a good place to put it. public static void WaitForJQueryDocumentReadyFunctionsToComplete(this Browser browser) { // Don't try this is JQuery isn't defined on the page: if (bool.Parse(browser.Eval("typeof $ == 'function'"))) { const string jqueryCompleteId = "jquery-document-ready-functions-complete"; // Register a ready() function which adds a marker div to the body: browser.Eval( @"$(document).ready(function() { " + "$('body').append('<div id=""" + jqueryCompleteId + @""" />'); " + "});"); // Wait for the marker div to exist or make the test fail: browser.Div(Find.ById(jqueryCompleteId)) .WaitUntilExistsOrFail(10, "JQuery document ready functions did not complete."); } } The code uses the Eval() method to send JavaScript to the browser to be executed; first to check that JQuery actually exists on the page, then to add the new ready() method. WaitUntilExistsOrFail() is another WatiN extension method I've written (I've ended up writing really quite a lot of them) which waits for the element on which it is invoked to exist, and uses Assert.Fail() to fail the test with the given message if it doesn't exist within the specified number of seconds. Here it is: public static void WaitUntilExistsOrFail(this Element element, int timeoutInSeconds, string failureMessage) { try { element.WaitUntilExists(timeoutInSeconds); } catch (WatinTimeoutException) { Assert.Fail(failureMessage); } }

    Read the article

  • How best to construct our test subjects in unit tests?

    - by Liath
    Some of our business logic classes require quite a few dependencies (in our case 7-10). As such when we come to unit test these the creation become quite complex. In most tests these dependencies are often not required (only some dependencies are required for particular methods). As a result unit tests often require a significant number of lines of code to mock up these useless dependencies (which can't be null because of null checks). For example: [Test] public void TestMethodA() { var dependency5 = new Mock<IDependency1>(); dependency5.Setup(x => x. // some setup var sut = new Sut(new Mock<IDependency1>().Object, new Mock<IDependency2>().Object, new Mock<IDependency3>().Object, new Mock<IDependency4>().Object, dependency5); Assert.SomeAssert(sut.MethodA()); } In this example almost half the test is taken up creating dependencies which aren't used. I've investigated an approach where I have a helper method. [Test] public void TestMethodA() { var dependency5 = new Mock<IDependency1>(); dependency5.Setup(x => x. // some setup var sut = CreateSut(null, null, null, null, dependency5); Assert.SomeAssert(sut.MethodA()); } private Sut CreateSut(IDependency1 d1, IDependency2 d2...) { return new Sut(d1 ?? new Mock<IDependency1>().Object, d2 ?? new Mock<IDependency2>().Object, } But these often grow very complicated very quickly. What is the best way to create these BLL classes in test classes to reduce complexity and simplify tests?

    Read the article

  • Espeak SAPI/dll usage on Windows ?

    - by Quandary
    Question: I am trying to use the espeak text-to-speech engine. So for I got it working wounderfully on linux (code below). Now I wanted to port this basic program to windows, too, but it's nearly impossible... Part of the problem is that the windows dll only allows for AUDIO_OUTPUT_SYNCHRONOUS, which means it requires a callback, but I can't figure out how to play the audio from the callback... First it crashed, then I realized, I need a callback function, now I get the data in the callback function, but I don't know how to play it... as it is neither a wav file nor plays automatically as on Linux. The sourceforge site is rather useless, because it basically says use the SAPI version, but then there is no example on how to use the sapi espeak dll... Anyway, here's my code, can anybody help? #ifdef __cplusplus #include <cstdio> #include <cstdlib> #include <cstring> else #include <stdio.h> #include <stdlib.h> #include <string.h> endif include include //#include "speak_lib.h" include "espeak/speak_lib.h" // libespeak-dev: /usr/include/espeak/speak_lib.h // apt-get install libespeak-dev // apt-get install libportaudio-dev // g++ -o mine mine.cpp -lespeak // g++ -o mine mine.cpp -I/usr/include/espeak/ -lespeak // gcc -o mine mine.cpp -I/usr/include/espeak/ -lespeak char voicename[40]; int samplerate; int quiet = 0; static char genders[4] = {' ','M','F',' '}; //const char *data_path = "/usr/share/"; // /usr/share/espeak-data/ const char *data_path = NULL; // use default path for espeak-data int strrcmp(const char *s, const char *sub) { int slen = strlen(s); int sublen = strlen(sub); return memcmp(s + slen - sublen, sub, sublen); } char * strrcpy(char *dest, const char *source) { // Pre assertions assert(dest != NULL); assert(source != NULL); assert(dest != source); // tk: parentheses while((*dest++ = *source++)) ; return(--dest); } const char* GetLanguageVoiceName(const char* pszShortSign) { #define LANGUAGE_LENGTH 30 static char szReturnValue[LANGUAGE_LENGTH] ; memset(szReturnValue, 0, LANGUAGE_LENGTH); for (int i = 0; pszShortSign[i] != '\0'; ++i) szReturnValue[i] = (char) tolower(pszShortSign[i]); const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { if( !strrcmp( v->languages, szReturnValue) ) { strcpy(szReturnValue, v->name); return szReturnValue; } } // End for strcpy(szReturnValue, "default"); return szReturnValue; } // End function getvoicename void ListVoices() { const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { printf("Shortsign: %s\n", v->languages); printf("age: %d\n", v->age); printf("gender: %c\n", genders[v->gender]); printf("name: %s\n", v->name); printf("\n\n"); } // End for } // End function getvoicename int main() { printf("Hello World!\n"); const char* szVersionInfo = espeak_Info(NULL); printf("Espeak version: %s\n", szVersionInfo); samplerate = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK,0,data_path,0); strcpy(voicename, "default"); // espeak --voices strcpy(voicename, "german"); strcpy(voicename, GetLanguageVoiceName("DE")); if(espeak_SetVoiceByName(voicename) != EE_OK) { printf("Espeak setvoice error...\n"); } static char word[200] = "Hello World" ; strcpy(word, "TV-fäns aufgepasst, es ist 20 Uhr 15. Zeit für Rambo 3"); strcpy(word, "Unnamed Player wurde zum Opfer von GSG9"); int speed = 220; int volume = 500; // volume in range 0-100 0=silence int pitch = 50; // base pitch, range 0-100. 50=normal // espeak.cpp 625 espeak_SetParameter(espeakRATE, speed, 0); espeak_SetParameter(espeakVOLUME,volume,0); espeak_SetParameter(espeakPITCH,pitch,0); // espeakRANGE: pitch range, range 0-100. 0-monotone, 50=normal // espeakPUNCTUATION: which punctuation characters to announce: // value in espeak_PUNCT_TYPE (none, all, some), espeak_VOICE *voice_spec = espeak_GetCurrentVoice(); voice_spec->gender=2; // 0=none 1=male, 2=female, //voice_spec->age = age; espeak_SetVoiceByProperties(voice_spec); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); strcpy(voicename, GetLanguageVoiceName("EN")); espeak_SetVoiceByName(voicename); strcpy(word, "Geany was fragged by GSG9 Googlebot"); strcpy(word, "Googlebot"); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); espeak_Terminate(); printf("Espeak terminated\n"); return EXIT_SUCCESS; } /* if(espeak_SetVoiceByName(voicename) != EE_OK) { memset(&voice_select,0,sizeof(voice_select)); voice_select.languages = voicename; if(espeak_SetVoiceByProperties(&voice_select) != EE_OK) { fprintf(stderr,"%svoice '%s'\n",err_load,voicename); exit(2); } } */ The above code is for Linux. The below code is about as far as I got on Vista x64 (32 bit emu): #ifdef __cplusplus #include <cstdio> #include <cstdlib> #include <cstring> else #include <stdio.h> #include <stdlib.h> #include <string.h> endif include include include "speak_lib.h" //#include "espeak/speak_lib.h" // libespeak-dev: /usr/include/espeak/speak_lib.h // apt-get install libespeak-dev // apt-get install libportaudio-dev // g++ -o mine mine.cpp -lespeak // g++ -o mine mine.cpp -I/usr/include/espeak/ -lespeak // gcc -o mine mine.cpp -I/usr/include/espeak/ -lespeak char voicename[40]; int iSampleRate; int quiet = 0; static char genders[4] = {' ','M','F',' '}; //const char *data_path = "/usr/share/"; // /usr/share/espeak-data/ //const char *data_path = NULL; // use default path for espeak-data const char *data_path = "C:\Users\Username\Desktop\espeak-1.43-source\espeak-1.43-source\"; int strrcmp(const char *s, const char *sub) { int slen = strlen(s); int sublen = strlen(sub); return memcmp(s + slen - sublen, sub, sublen); } char * strrcpy(char *dest, const char *source) { // Pre assertions assert(dest != NULL); assert(source != NULL); assert(dest != source); // tk: parentheses while((*dest++ = *source++)) ; return(--dest); } const char* GetLanguageVoiceName(const char* pszShortSign) { #define LANGUAGE_LENGTH 30 static char szReturnValue[LANGUAGE_LENGTH] ; memset(szReturnValue, 0, LANGUAGE_LENGTH); for (int i = 0; pszShortSign[i] != '\0'; ++i) szReturnValue[i] = (char) tolower(pszShortSign[i]); const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { if( !strrcmp( v->languages, szReturnValue) ) { strcpy(szReturnValue, v->name); return szReturnValue; } } // End for strcpy(szReturnValue, "default"); return szReturnValue; } // End function getvoicename void ListVoices() { const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { printf("Shortsign: %s\n", v->languages); printf("age: %d\n", v->age); printf("gender: %c\n", genders[v->gender]); printf("name: %s\n", v->name); printf("\n\n"); } // End for } // End function getvoicename /* Callback from espeak. Directly speaks using AudioTrack. */ define LOGI(x) printf("%s\n", x) static int AndroidEspeakDirectSpeechCallback(short *wav, int numsamples, espeak_EVENT *events) { char buf[100]; sprintf(buf, "AndroidEspeakDirectSpeechCallback: %d samples", numsamples); LOGI(buf); if (wav == NULL) { LOGI("Null: speech has completed"); } if (numsamples > 0) { //audout->write(wav, sizeof(short) * numsamples); sprintf(buf, "AudioTrack wrote: %d bytes", sizeof(short) * numsamples); LOGI(buf); } return 0; // continue synthesis (1 is to abort) } static int AndroidEspeakSynthToFileCallback(short *wav, int numsamples,espeak_EVENT *events) { char buf[100]; sprintf(buf, "AndroidEspeakSynthToFileCallback: %d samples", numsamples); LOGI(buf); if (wav == NULL) { LOGI("Null: speech has completed"); } // The user data should contain the file pointer of the file to write to //void* user_data = events->user_data; FILE* user_data = fopen ( "myfile1.wav" , "ab" ); FILE* fp = static_cast<FILE *>(user_data); // Write all of the samples fwrite(wav, sizeof(short), numsamples, fp); return 0; // continue synthesis (1 is to abort) } int main() { printf("Hello World!\n"); const char* szVersionInfo = espeak_Info(NULL); printf("Espeak version: %s\n", szVersionInfo); iSampleRate = espeak_Initialize(AUDIO_OUTPUT_SYNCHRONOUS, 4096, data_path, 0); if (iSampleRate <= 0) { printf("Unable to initialize espeak"); return EXIT_FAILURE; } //samplerate = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK,0,data_path,0); //ListVoices(); strcpy(voicename, "default"); // espeak --voices //strcpy(voicename, "german"); //strcpy(voicename, GetLanguageVoiceName("DE")); if(espeak_SetVoiceByName(voicename) != EE_OK) { printf("Espeak setvoice error...\n"); } static char word[200] = "Hello World" ; strcpy(word, "TV-fäns aufgepasst, es ist 20 Uhr 15. Zeit für Rambo 3"); strcpy(word, "Unnamed Player wurde zum Opfer von GSG9"); int speed = 220; int volume = 500; // volume in range 0-100 0=silence int pitch = 50; // base pitch, range 0-100. 50=normal // espeak.cpp 625 espeak_SetParameter(espeakRATE, speed, 0); espeak_SetParameter(espeakVOLUME,volume,0); espeak_SetParameter(espeakPITCH,pitch,0); // espeakRANGE: pitch range, range 0-100. 0-monotone, 50=normal // espeakPUNCTUATION: which punctuation characters to announce: // value in espeak_PUNCT_TYPE (none, all, some), //espeak_VOICE *voice_spec = espeak_GetCurrentVoice(); //voice_spec->gender=2; // 0=none 1=male, 2=female, //voice_spec->age = age; //espeak_SetVoiceByProperties(voice_spec); //espeak_SetSynthCallback(AndroidEspeakDirectSpeechCallback); espeak_SetSynthCallback(AndroidEspeakSynthToFileCallback); unsigned int unique_identifier; espeak_ERROR err = espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, &unique_identifier, NULL); err = espeak_Synchronize(); /* strcpy(voicename, GetLanguageVoiceName("EN")); espeak_SetVoiceByName(voicename); strcpy(word, "Geany was fragged by GSG9 Googlebot"); strcpy(word, "Googlebot"); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); */ // espeak_Cancel(); espeak_Terminate(); printf("Espeak terminated\n"); system("pause"); return EXIT_SUCCESS; }

    Read the article

  • Where can these be posted besides the Python Cookbook?

    - by Noctis Skytower
    Whitespace Assembler #! /usr/bin/env python """Assembler.py Compiles a program from "Assembly" folder into "Program" folder. Can be executed directly by double-click or on the command line. Give name of *.WSA file without extension (example: stack_calc).""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 3 $' ################################################################################ import string from Interpreter import INS, MNEMONIC ################################################################################ def parse(code): program = [] process_virtual(program, code) process_control(program) return tuple(program) def process_virtual(program, code): for line, text in enumerate(code.split('\n')): if not text or text[0] == '#': continue if text.startswith('part '): parse_part(program, line, text[5:]) elif text.startswith(' '): parse_code(program, line, text[5:]) else: syntax_error(line) def syntax_error(line): raise SyntaxError('Line ' + str(line + 1)) ################################################################################ def process_control(program): parts = get_parts(program) names = dict(pair for pair in zip(parts, generate_index())) correct_control(program, names) def get_parts(program): parts = [] for ins in program: if isinstance(ins, tuple): ins, arg = ins if ins == INS.PART: if arg in parts: raise NameError('Part definition was found twice: ' + arg) parts.append(arg) return parts def generate_index(): index = 1 while True: yield index index *= -1 if index > 0: index += 1 def correct_control(program, names): for index, ins in enumerate(program): if isinstance(ins, tuple): ins, arg = ins if ins in HAS_LABEL: if arg not in names: raise NameError('Part definition was never found: ' + arg) program[index] = (ins, names[arg]) ################################################################################ def parse_part(program, line, text): if not valid_label(text): syntax_error(line) program.append((INS.PART, text)) def valid_label(text): if not between_quotes(text): return False label = text[1:-1] if not valid_name(label): return False return True def between_quotes(text): if len(text) < 3: return False if text.count('"') != 2: return False if text[0] != '"' or text[-1] != '"': return False return True def valid_name(label): valid_characters = string.ascii_letters + string.digits + '_' valid_set = frozenset(valid_characters) label_set = frozenset(label) if len(label_set - valid_set) != 0: return False return True ################################################################################ from Interpreter import HAS_LABEL, Program NO_ARGS = Program.NO_ARGS HAS_ARG = Program.HAS_ARG TWO_WAY = tuple(set(NO_ARGS) & set(HAS_ARG)) ################################################################################ def parse_code(program, line, text): for ins, word in enumerate(MNEMONIC): if text.startswith(word): check_code(program, line, text[len(word):], ins) break else: syntax_error(line) def check_code(program, line, text, ins): if ins in TWO_WAY: if text: number = parse_number(line, text) program.append((ins, number)) else: program.append(ins) elif ins in HAS_LABEL: text = parse_label(line, text) program.append((ins, text)) elif ins in HAS_ARG: number = parse_number(line, text) program.append((ins, number)) elif ins in NO_ARGS: if text: syntax_error(line) program.append(ins) else: syntax_error(line) def parse_label(line, text): if not text or text[0] != ' ': syntax_error(line) text = text[1:] if not valid_label(text): syntax_error(line) return text ################################################################################ def parse_number(line, text): if not valid_number(text): syntax_error(line) return int(text) def valid_number(text): if len(text) < 2: return False if text[0] != ' ': return False text = text[1:] if '+' in text and '-' in text: return False if '+' in text: if text.count('+') != 1: return False if text[0] != '+': return False text = text[1:] if not text: return False if '-' in text: if text.count('-') != 1: return False if text[0] != '-': return False text = text[1:] if not text: return False valid_set = frozenset(string.digits) value_set = frozenset(text) if len(value_set - valid_set) != 0: return False return True ################################################################################ ################################################################################ from Interpreter import partition_number VMC_2_TRI = { (INS.PUSH, True): (0, 0), (INS.COPY, False): (0, 2, 0), (INS.COPY, True): (0, 1, 0), (INS.SWAP, False): (0, 2, 1), (INS.AWAY, False): (0, 2, 2), (INS.AWAY, True): (0, 1, 2), (INS.ADD, False): (1, 0, 0, 0), (INS.SUB, False): (1, 0, 0, 1), (INS.MUL, False): (1, 0, 0, 2), (INS.DIV, False): (1, 0, 1, 0), (INS.MOD, False): (1, 0, 1, 1), (INS.SET, False): (1, 1, 0), (INS.GET, False): (1, 1, 1), (INS.PART, True): (2, 0, 0), (INS.CALL, True): (2, 0, 1), (INS.GOTO, True): (2, 0, 2), (INS.ZERO, True): (2, 1, 0), (INS.LESS, True): (2, 1, 1), (INS.BACK, False): (2, 1, 2), (INS.EXIT, False): (2, 2, 2), (INS.OCHR, False): (1, 2, 0, 0), (INS.OINT, False): (1, 2, 0, 1), (INS.ICHR, False): (1, 2, 1, 0), (INS.IINT, False): (1, 2, 1, 1) } ################################################################################ def to_trinary(program): trinary_code = [] for ins in program: if isinstance(ins, tuple): ins, arg = ins trinary_code.extend(VMC_2_TRI[(ins, True)]) trinary_code.extend(from_number(arg)) else: trinary_code.extend(VMC_2_TRI[(ins, False)]) return tuple(trinary_code) def from_number(arg): code = [int(arg < 0)] if arg: for bit in reversed(list(partition_number(abs(arg), 2))): code.append(bit) return code + [2] return code + [0, 2] to_ws = lambda trinary: ''.join(' \t\n'[index] for index in trinary) def compile_wsa(source): program = parse(source) trinary = to_trinary(program) ws_code = to_ws(trinary) return ws_code ################################################################################ ################################################################################ import os import sys import time import traceback def main(): name, source, command_line, error = get_source() if not error: start = time.clock() try: ws_code = compile_wsa(source) except: print('ERROR: File could not be compiled.\n') traceback.print_exc() error = True else: path = os.path.join('Programs', name + '.ws') try: open(path, 'w').write(ws_code) except IOError as err: print(err) error = True else: div, mod = divmod((time.clock() - start) * 1000, 1) args = int(div), '{:.3}'.format(mod)[1:] print('DONE: Comipled in {}{} ms'.format(*args)) handle_close(error, command_line) def get_source(): if len(sys.argv) > 1: command_line = True name = sys.argv[1] else: command_line = False try: name = input('Source File: ') except: return None, None, False, True print() path = os.path.join('Assembly', name + '.wsa') try: return name, open(path).read(), command_line, False except IOError as err: print(err) return None, None, command_line, True def handle_close(error, command_line): if error: usage = 'Usage: {} <assembly>'.format(os.path.basename(sys.argv[0])) print('\n{}\n{}'.format('-' * len(usage), usage)) if not command_line: time.sleep(10) ################################################################################ if __name__ == '__main__': main() Whitespace Helpers #! /usr/bin/env python """Helpers.py Includes a function to encode Python strings into my WSA format. Has a "PRINT_LINE" function that can be copied to a WSA program. Contains a "PRINT" function and documentation as an explanation.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 1 $' ################################################################################ def encode_string(string, addr): print(' push', addr) print(' push', len(string)) print(' set') addr += 1 for offset, character in enumerate(string): print(' push', addr + offset) print(' push', ord(character)) print(' set') ################################################################################ # Prints a string with newline. # push addr # call "PRINT_LINE" """ part "PRINT_LINE" call "PRINT" push 10 ochr back """ ################################################################################ # def print(array): # if len(array) <= 0: # return # offset = 1 # while len(array) - offset >= 0: # ptr = array.ptr + offset # putch(array[ptr]) # offset += 1 """ part "PRINT" # Line 1-2 copy get less "__PRINT_RET_1" copy get zero "__PRINT_RET_1" # Line 3 push 1 # Line 4 part "__PRINT_LOOP" copy copy 2 get swap sub less "__PRINT_RET_2" # Line 5 copy 1 copy 1 add # Line 6 get ochr # Line 7 push 1 add goto "__PRINT_LOOP" part "__PRINT_RET_2" away part "__PRINT_RET_1" away back """ Whitespace Interpreter #! /usr/bin/env python """Interpreter.py Runs programs in "Programs" and creates *.WSO files when needed. Can be executed directly by double-click or on the command line. If run on command line, add "ASM" flag to dump program assembly.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 4 $' ################################################################################ def test_file(path): disassemble(parse(trinary(load(path))), True) ################################################################################ load = lambda ws: ''.join(c for r in open(ws) for c in r if c in ' \t\n') trinary = lambda ws: tuple(' \t\n'.index(c) for c in ws) ################################################################################ def enum(names): names = names.replace(',', ' ').split() space = dict((reversed(pair) for pair in enumerate(names)), __slots__=()) return type('enum', (object,), space)() INS = enum('''\ PUSH, COPY, SWAP, AWAY, \ ADD, SUB, MUL, DIV, MOD, \ SET, GET, \ PART, CALL, GOTO, ZERO, LESS, BACK, EXIT, \ OCHR, OINT, ICHR, IINT''') ################################################################################ def parse(code): ins = iter(code).__next__ program = [] while True: try: imp = ins() except StopIteration: return tuple(program) if imp == 0: # [Space] parse_stack(ins, program) elif imp == 1: # [Tab] imp = ins() if imp == 0: # [Tab][Space] parse_math(ins, program) elif imp == 1: # [Tab][Tab] parse_heap(ins, program) else: # [Tab][Line] parse_io(ins, program) else: # [Line] parse_flow(ins, program) def parse_number(ins): sign = ins() if sign == 2: raise StopIteration() buffer = '' code = ins() if code == 2: raise StopIteration() while code != 2: buffer += str(code) code = ins() if sign == 1: return int(buffer, 2) * -1 return int(buffer, 2) ################################################################################ def parse_stack(ins, program): code = ins() if code == 0: # [Space] number = parse_number(ins) program.append((INS.PUSH, number)) elif code == 1: # [Tab] code = ins() number = parse_number(ins) if code == 0: # [Tab][Space] program.append((INS.COPY, number)) elif code == 1: # [Tab][Tab] raise StopIteration() else: # [Tab][Line] program.append((INS.AWAY, number)) else: # [Line] code = ins() if code == 0: # [Line][Space] program.append(INS.COPY) elif code == 1: # [Line][Tab] program.append(INS.SWAP) else: # [Line][Line] program.append(INS.AWAY) def parse_math(ins, program): code = ins() if code == 0: # [Space] code = ins() if code == 0: # [Space][Space] program.append(INS.ADD) elif code == 1: # [Space][Tab] program.append(INS.SUB) else: # [Space][Line] program.append(INS.MUL) elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] program.append(INS.DIV) elif code == 1: # [Tab][Tab] program.append(INS.MOD) else: # [Tab][Line] raise StopIteration() else: # [Line] raise StopIteration() def parse_heap(ins, program): code = ins() if code == 0: # [Space] program.append(INS.SET) elif code == 1: # [Tab] program.append(INS.GET) else: # [Line] raise StopIteration() def parse_io(ins, program): code = ins() if code == 0: # [Space] code = ins() if code == 0: # [Space][Space] program.append(INS.OCHR) elif code == 1: # [Space][Tab] program.append(INS.OINT) else: # [Space][Line] raise StopIteration() elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] program.append(INS.ICHR) elif code == 1: # [Tab][Tab] program.append(INS.IINT) else: # [Tab][Line] raise StopIteration() else: # [Line] raise StopIteration() def parse_flow(ins, program): code = ins() if code == 0: # [Space] code = ins() label = parse_number(ins) if code == 0: # [Space][Space] program.append((INS.PART, label)) elif code == 1: # [Space][Tab] program.append((INS.CALL, label)) else: # [Space][Line] program.append((INS.GOTO, label)) elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] label = parse_number(ins) program.append((INS.ZERO, label)) elif code == 1: # [Tab][Tab] label = parse_number(ins) program.append((INS.LESS, label)) else: # [Tab][Line] program.append(INS.BACK) else: # [Line] code = ins() if code == 2: # [Line][Line] program.append(INS.EXIT) else: # [Line][Space] or [Line][Tab] raise StopIteration() ################################################################################ MNEMONIC = '\ push copy swap away add sub mul div mod set get part \ call goto zero less back exit ochr oint ichr iint'.split() HAS_ARG = [getattr(INS, name) for name in 'PUSH COPY AWAY PART CALL GOTO ZERO LESS'.split()] HAS_LABEL = [getattr(INS, name) for name in 'PART CALL GOTO ZERO LESS'.split()] def disassemble(program, names=False): if names: names = create_names(program) for ins in program: if isinstance(ins, tuple): ins, arg = ins assert ins in HAS_ARG has_arg = True else: assert INS.PUSH <= ins <= INS.IINT has_arg = False if ins == INS.PART: if names: print(MNEMONIC[ins], '"' + names[arg] + '"') else: print(MNEMONIC[ins], arg) elif has_arg and ins in HAS_ARG: if ins in HAS_LABEL and names: assert arg in names print(' ' + MNEMONIC[ins], '"' + names[arg] + '"') else: print(' ' + MNEMONIC[ins], arg) else: print(' ' + MNEMONIC[ins]) ################################################################################ def create_names(program): names = {} number = 1 for ins in program: if isinstance(ins, tuple) and ins[0] == INS.PART: label = ins[1] assert label not in names names[label] = number_to_name(number) number += 1 return names def number_to_name(number): name = '' for offset in reversed(list(partition_number(number, 27))): if offset: name += chr(ord('A') + offset - 1) else: name += '_' return name def partition_number(number, base): div, mod = divmod(number, base) yield mod while div: div, mod = divmod(div, base) yield mod ################################################################################ CODE = (' \t\n', ' \n ', ' \t \t\n', ' \n\t', ' \n\n', ' \t\n \t\n', '\t ', '\t \t', '\t \n', '\t \t ', '\t \t\t', '\t\t ', '\t\t\t', '\n \t\n', '\n \t \t\n', '\n \n \t\n', '\n\t \t\n', '\n\t\t \t\n', '\n\t\n', '\n\n\n', '\t\n ', '\t\n \t', '\t\n\t ', '\t\n\t\t') EXAMPLE = ''.join(CODE) ################################################################################ NOTES = '''\ STACK ===== push number copy copy number swap away away number MATH ==== add sub mul div mod HEAP ==== set get FLOW ==== part label call label goto label zero label less label back exit I/O === ochr oint ichr iint''' ################################################################################ ################################################################################ class Stack: def __init__(self): self.__data = [] # Stack Operators def push(self, number): self.__data.append(number) def copy(self, number=None): if number is None: self.__data.append(self.__data[-1]) else: size = len(self.__data) index = size - number - 1 assert 0 <= index < size self.__data.append(self.__data[index]) def swap(self): self.__data[-2], self.__data[-1] = self.__data[-1], self.__data[-2] def away(self, number=None): if number is None: self.__data.pop() else: size = len(self.__data) index = size - number - 1 assert 0 <= index < size del self.__data[index:-1] # Math Operators def add(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix + suffix) def sub(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix - suffix) def mul(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix * suffix) def div(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix // suffix) def mod(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix % suffix) # Program Operator def pop(self): return self.__data.pop() ################################################################################ class Heap: def __init__(self): self.__data = {} def set_(self, addr, item): if item: self.__data[addr] = item elif addr in self.__data: del self.__data[addr] def get_(self, addr): return self.__data.get(addr, 0) ################################################################################ import os import zlib import msvcrt import pickle import string class CleanExit(Exception): pass NOP = lambda arg: None DEBUG_WHITESPACE = False ################################################################################ class Program: NO_ARGS = INS.COPY, INS.SWAP, INS.AWAY, INS.ADD, \ INS.SUB, INS.MUL, INS.DIV, INS.MOD, \ INS.SET, INS.GET, INS.BACK, INS.EXIT, \ INS.OCHR, INS.OINT, INS.ICHR, INS.IINT HAS_ARG = INS.PUSH, INS.COPY, INS.AWAY, INS.PART, \ INS.CALL, INS.GOTO, INS.ZERO, INS.LESS def __init__(self, code): self.__data = code self.__validate() self.__build_jump() self.__check_jump() self.__setup_exec() def __setup_exec(self): self.__iptr = 0 self.__stck = stack = Stack() self.__heap = Heap() self.__cast = [] self.__meth = (stack.push, stack.copy, stack.swap, stack.away, stack.add, stack.sub, stack.mul, stack.div, stack.mod, self.__set, self.__get, NOP, self.__call, self.__goto, self.__zero, self.__less, self.__back, self.__exit, self.__ochr, self.__oint, self.__ichr, self.__iint) def step(self): ins = self.__data[self.__iptr] self.__iptr += 1 if isinstance(ins, tuple): self.__meth[ins[0]](ins[1]) else: self.__meth[ins]() def run(self): while True: ins = self.__data[self.__iptr] self.__iptr += 1 if isinstance(ins, tuple): self.__meth[ins[0]](ins[1]) else: self.__meth[ins]() def __oint(self): for digit in str(self.__stck.pop()): msvcrt.putwch(digit) def __ichr(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() while True: char = msvcrt.getwch() if char in '\x00\xE0': msvcrt.getwch() elif char in string.printable: char = char.replace('\r', '\n') msvcrt.putwch(char) break item = ord(char) # Storing Number self.__heap.set_(addr, item) def __iint(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() buff = '' char = msvcrt.getwch() while char != '\r' or not buff: if char in '\x00\xE0': msvcrt.getwch() elif char in '+-' and not buff: msvcrt.putwch(char) buff += char elif '0' <= char <= '9': msvcrt.putwch(char) buff += char elif char == '\b': if buff: buff = buff[:-1] msvcrt.putwch(char) msvcrt.putwch(' ') msvcrt.putwch(char) char = msvcrt.getwch() msvcrt.putwch(char) msvcrt.putwch('\n') item = int(buff) # Storing Number self.__heap.set_(addr, item) def __goto(self, label): self.__iptr = self.__jump[label] def __zero(self, label): if self.__stck.pop() == 0: self.__iptr = self.__jump[label] def __less(self, label): if self.__stck.pop() < 0: self.__iptr = self.__jump[label] def __exit(self): self.__setup_exec() raise CleanExit() def __set(self): item = self.__stck.pop() addr = self.__stck.po

    Read the article

  • spliiting code in java-don't know what's wrong [closed]

    - by ???? ?????
    I'm writing a code to split a file into many files with a size specified in the code, and then it will join these parts later. The problem is with the joining code, it doesn't work and I can't figure what is wrong! This is my code: import java.io.*; import java.util.*; public class StupidSplit { static final int Chunk_Size = 10; static int size =0; public static void main(String[] args) throws IOException { String file = "b.txt"; int chunks = DivideFile(file); System.out.print((new File(file)).delete()); System.out.print(JoinFile(file, chunks)); } static boolean JoinFile(String fname, int nChunks) { /* * Joins the chunks together. Chunks have been divided using DivideFile * function so the last part of filename will ".partxxxx" Checks if all * parts are together by matching number of chunks found against * "nChunks", then joins the file otherwise throws an error. */ boolean successful = false; File currentDirectory = new File(System.getProperty("user.dir")); // File[] fileList = currentDirectory.listFiles(); /* populate only the files having extension like "partxxxx" */ List<File> lst = new ArrayList<File>(); // Arrays.sort(fileList); for (File file : fileList) { if (file.isFile()) { String fnm = file.getName(); int lastDot = fnm.lastIndexOf('.'); // add to list which match the name given by "fname" and have //"partxxxx" as extension" if (fnm.substring(0, lastDot).equalsIgnoreCase(fname) && (fnm.substring(lastDot + 1)).substring(0, 4).equals("part")) { lst.add(file); } } } /* * sort the list - it will be sorted by extension only because we have * ensured that list only contains those files that have "fname" and * "part" */ File[] files = (File[]) lst.toArray(new File[0]); Arrays.sort(files); System.out.println("size ="+files.length); System.out.println("hello"); /* Ensure that number of chunks match the length of array */ if (files.length == nChunks-1) { File ofile = new File(fname); FileOutputStream fos; FileInputStream fis; byte[] fileBytes; int bytesRead = 0; try { fos = new FileOutputStream(ofile,true); for (File file : files) { fis = new FileInputStream(file); fileBytes = new byte[(int) file.length()]; bytesRead = fis.read(fileBytes, 0, (int) file.length()); assert(bytesRead == fileBytes.length); assert(bytesRead == (int) file.length()); fos.write(fileBytes); fos.flush(); fileBytes = null; fis.close(); fis = null; } fos.close(); fos = null; } catch (FileNotFoundException fnfe) { System.out.println("Could not find file"); successful = false; return successful; } catch (IOException ioe) { System.out.println("Cannot write to disk"); successful = false; return successful; } /* ensure size of file matches the size given by server */ successful = (ofile.length() == StupidSplit.size) ? true : false; } else { successful = false; } return successful; } static int DivideFile(String fname) { File ifile = new File(fname); FileInputStream fis; String newName; FileOutputStream chunk; //int fileSize = (int) ifile.length(); double fileSize = (double) ifile.length(); //int nChunks = 0, read = 0, readLength = Chunk_Size; int nChunks = 0, read = 0, readLength = Chunk_Size; byte[] byteChunk; try { fis = new FileInputStream(ifile); StupidSplit.size = (int)ifile.length(); while (fileSize > 0) { if (fileSize <= Chunk_Size) { readLength = (int) fileSize; } byteChunk = new byte[readLength]; read = fis.read(byteChunk, 0, readLength); fileSize -= read; assert(read==byteChunk.length); nChunks++; //newName = fname + ".part" + Integer.toString(nChunks - 1); newName = String.format("%s.part%09d", fname, nChunks - 1); chunk = new FileOutputStream(new File(newName)); chunk.write(byteChunk); chunk.flush(); chunk.close(); byteChunk = null; chunk = null; } fis.close(); System.out.println(nChunks); // fis = null; } catch (FileNotFoundException fnfe) { System.out.println("Could not find the given file"); System.exit(-1); } catch (IOException ioe) { System.out .println("Error while creating file chunks. Exiting program"); System.exit(-1); }System.out.println(nChunks); return nChunks; } } }

    Read the article

  • java.lang.IllegalArgumentException: Method must not be null

    - by abc
    Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Method must not be null:java.lang.IllegalArgumentException: Method must not be null i am getting this deployment error while deploying my application. java -version java version "1.6.0_20" Java(TM) SE Runtime Environment (build 1.6.0_20-b02) Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode) while the same build gets deployed successfully in the same server jetty 6.1.3 with following conf. java version "1.6.0_17" spring version used is 2.5.6.SEC01 how to overcome, googling didnt work? 2010-05-13 15:53:20.903::WARN: Failed startup of context org.mortbay.jetty.webapp.WebAppContext@9ad840{/caw,jar:file:/home/jigar/jetty-6.1.3/webapps/caw.war!/} org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Method must not be null at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:515) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:362) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:530) at org.mortbay.jetty.servlet.Context.startContext(Context.java:135) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:147) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:161) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:147) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117) at org.mortbay.jetty.Server.doStart(Server.java:210) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.xml.XmlConfiguration.main(XmlConfiguration.java:929) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.mortbay.start.Main.invokeMain(Main.java:183) at org.mortbay.start.Main.start(Main.java:497) at org.mortbay.start.Main.main(Main.java:115) Caused by: java.lang.IllegalArgumentException: Method must not be null at org.springframework.util.Assert.notNull(Assert.java:112) at org.springframework.core.BridgeMethodResolver.findBridgedMethod(BridgeMethodResolver.java:63) at org.springframework.beans.GenericTypeAwarePropertyDescriptor.<init>(GenericTypeAwarePropertyDescriptor.java:58) at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:250) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:144) at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:252) at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:282) at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:333) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1247) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) ... 35 more 2010-05-13 15:53:20.906::WARN: Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Method must not be null: java.lang.IllegalArgumentException: Method must not be null at org.springframework.util.Assert.notNull(Assert.java:112) at org.springframework.core.BridgeMethodResolver.findBridgedMethod(BridgeMethodResolver.java:63) at org.springframework.beans.GenericTypeAwarePropertyDescriptor.<init>(GenericTypeAwarePropertyDescriptor.java:58) at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:250) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:144) at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:252) at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:282) at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:333) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1247) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:515) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:362) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:530) at org.mortbay.jetty.servlet.Context.startContext(Context.java:135) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:147) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:161) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:147) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117) at org.mortbay.jetty.Server.doStart(Server.java:210) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.xml.XmlConfiguration.main(XmlConfiguration.java:929) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.mortbay.start.Main.invokeMain(Main.java:183) at org.mortbay.start.Main.start(Main.java:497) at org.mortbay.start.Main.main(Main.java:115) 2010-05-13 15:53:20.964::INFO: Started SelectChannelConnector @ 0.0.0.0:8090

    Read the article

  • How do I test UrlHelper.RouteUrl()?

    - by Jeff Putz
    I'm having a tough go trying to figure out what I need to mock in my tests to show that UrlHelper.RouteUrl() is returning the right URL. It works, but I'd like to have the right test coverage. The meat of the controller method looks like this: var urlHelper = new UrlHelper(ControllerContext.RequestContext); return Json(new BasicJsonMessage { Result = true, Redirect = urlHelper.RouteUrl(new { controller = "TheController", action = "TheAction", id = somerecordnumber }) }); Testing the result object is easy enough, like this: var controller = new MyController(); var result = controller.DoTheNewHotness()); Assert.IsInstanceOf<JsonResult>(result); var data = (BasicJsonMessage)result.Data; Assert.IsTrue(data.Result); result.Redirect is always null because the controller obviously doesn't know anything about the routing. What do I have to do to the controller to let it know? As I said, I know it works when I exercise the production code, but I'd like some testing assurance. Thanks for your help!

    Read the article

  • How to rollback in EF4?

    - by Jaxidian
    In my research about rolling back transactions in EF4, it seems everybody refers to this blog post or offers a similar explanation. In my scenario, I'm wanting to do this in a unit testing scenario where I want to rollback practically everything I do within my unit testing context to keep from updating the data in the database (yeah, we'll increment counters but that's okay). In order to do this, is it best to follow the following plan? Am I missing some concept or anything else major with this (aside from my SetupMyTest and PerformMyTest functions won't really exist that way)? using (var ts = new TransactionScope()) { // Arrange SetupMyTest(context); // Act PerformMyTest(context); var numberOfChanges = context.SaveChanges(false); // if there's an issue, chances are that an exception has been thrown by now. // Assert Assert.IsTrue(numberOfChanges > 0, "Failed to _____"); // transaction will rollback because we do not ever call Complete on it }

    Read the article

  • How to avoid open-redirect vulnerability and safely redirect on successful login (HINT: ASP.NET MVC

    - by Brad B.
    Normally, when a site requires that you are logged in before you can access a certain page, you are taken to the login screen and after successfully authenticating yourself, you are redirected back to the originally requested page. This is great for usability - but without careful scrutiny, this feature can easily become an open redirect vulnerability. Sadly, for an example of this vulnerability, look no further than the default LogOn action provided by ASP.NET MVC 2: [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { FormsService.SignIn(model.UserName, model.RememberMe); if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); // open redirect vulnerability HERE } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "User name or password incorrect..."); } } return View(model); } If a user is successfully authenticated, they are redirected to "returnUrl" (if it was provided via the login form submission). Here is a simple example attack (one of many, actually) that exploits this vulnerability: Attacker, pretending to be victim's bank, sends an email to victim containing a link, like this: http://www.mybank.com/logon?returnUrl=http://www.badsite.com Having been taught to verify the ENTIRE domain name (e.g., google.com = GOOD, google.com.as31x.example.com = BAD), the victim knows the link is OK - there isn't any tricky sub-domain phishing going on. The victim clicks the link, sees their actual familiar banking website and is asked to logon Victim logs on and is subsequently redirected to http://www.badsite.com which is made to look exactly like victim's bank's website, so victim doesn't know he is now on a different site. http://www.badsite.com says something like "We need to update our records - please type in some extremely personal information below: [ssn], [address], [phone number], etc." Victim, still thinking he is on his banking website, falls for the ploy and provides attacker with the information Any ideas on how to maintain this redirect-on-successful-login functionality yet avoid the open-redirect vulnerability? I'm leaning toward the option of splitting the "returnUrl" parameter into controller/action parts and use "RedirectToRouteResult" instead of simply "Redirect". Does this approach open any new vulnerabilities? Side note: I know this open-redirect may not seem to be a big deal compared to the likes of XSS and CSRF, but us developers are the only thing protecting our customers from the bad guys - anything we can do to make the bad guys' job harder is a win in my book. Thanks, Brad

    Read the article

  • Why allow concatenation of string literals?

    - by Caspin
    I recently got bit by a subtle bug. char ** int2str = { "zero", // 0 "one", // 1 "two" // 2 "three",// 3 nullptr }; assert( values[1] == "one"_s ); // passes assert( values[2] == "two"_s ); // fails If you have godlike code review powers you'll notice I forgot the , after "two". After the considerable effort to find that bug I've got to ask why would anyone ever want this behavior? I can see how this might be useful for macro magic, but then why is this a "feature" in a modern language like python? Have you ever used string literal concatenation in production code?

    Read the article

  • Facebook Graph Api doesn't redirect to my callback

    - by Pentium10
    I am following the steps to do the authorization as described here, but I am not redirected to my callback url. I get the following five steps after calling the first one: https://graph.facebook.com/oauth/authorize?display=touch&client_id=...&redirect_uri=... https://www.facebook.com/connect/uiserver.php?display=touch&client_id=...&redirect_uri=...&next=https://graph.facebook.com/oauth/authorize_success?display=touch&client_id=...&redirect_uri=...&type=web_server&cancel_url=https://graph.facebook.com/oauth/authorize_cancel?display=touch&client_id=...&redirect_uri=...&method=permissions.request&return_session=1 http://www.facebook.com/ http://touch.facebook.com/?w2m http://touch.facebook.com/login.php?next=http://touch.facebook.com/?w2m&cancel=http://touch.facebook.com/?w2m&fbconnect=0&r39c26cf0&refid=108 As you see the 5th steps just displays the login screen. If I log in, or I am already logged in I am presented with the home page. I use my application key, and the connect url of the app I've setup in FB Developers page. What I am doing wrong, why I am not redirected to my url?

    Read the article

  • Error URL redirection

    - by xRobot
    urls.py: url(r'^book/(?P<booktitle>[\w\._-]+)/(?P<bookeditor>[\w\._-]+)/(?P<bookpages>[\w\._-]+)/(?P<bookid>[\d\._-]+)/$', 'book.views.book', name="book"), views.py: def book(request, booktitle, bookeditor, bookpages, bookid, template_name="book.html"): book = get_object_or_404(book, pk=bookid) if booktitle != book.book_title : redirect_to = "/book/%s/%s/%s/%s/%i/" % ( booktitle, bookeditor, bookpages, bookid, ) return HttpResponseRedirect(redirect_to) return render_to_response(template_name, { 'book': book, },) . So the urls of each book are like this: example.com/book/the-bible/gesu-crist/938/12/ I want that if there is an error in the url, then I get redirected to the real url by using book.id in the end of the url. For example if I go to: example.com/book/A-bible/gesu-crist/938/12/ the I will get redirected to: example.com/book/the-bible/gesu-crist/938/12/ but I go to wrong url I will get this error: TypeError at /book/A-bible/gesu-crist/938/12/ %d format: a number is required, not unicode . Why ? What I have to do ?

    Read the article

  • How to make ASP.NET authentication persist the Url Fragment when redirecting to the login page?

    - by estourodepilha.com
    After I inserted the configuration below in my Web.Config <authentication mode="Forms"> <forms name="appNameAuth" path="/" loginUrl="login.aspx" protection="All" timeout="30"> <credentials passwordFormat="Clear"> <user name="user" password="password" /> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization> All requests to Menu.aspx#fragment are redirected to login.aspx?ReturnUrl=/Menu.aspx and I expected it to be redirected to login.aspx?ReturnUrl=/Menu.aspx#fragment How to achieve the desired behavior?

    Read the article

  • double.NaN Equality in MS Test

    - by RichK
    Why am I getting this result? [TestMethod] public void nan_test() { Assert.AreEqual(1, double.NaN, 1E-1); <-- Passes Assert.AreEqual(1, double.NaN); <-- Fails } What difference does the delta have in asserting NaN equals a number? Surely it should always return false. I am aware of IsNaN, but that's not useful here (see below). Background: I have a function returning NaN (erroneously) , it was meant to be a real number but the test still passed. I'm using the delta because it's double precision equality, the original test used 1E-9.

    Read the article

  • clear javascript console in Google Chrome

    - by Reigel
    Hi, I was wondering if I could clear up the console with some command.. console.log(), can print... is there a command to clear up console?.. I've tried to console.log(console); and got this functions below... assert: function assert() { [native code] } constructor: function Console() { [native code] } count: function count() { [native code] } debug: function debug() { [native code] } dir: function dir() { [native code] } dirxml: function dirxml() { [native code] } error: function error() { [native code] } group: function group() { [native code] } groupEnd: function groupEnd() { [native code] } info: function info() { [native code] } log: function log() { [native code] } markTimeline: function markTimeline() { [native code] } profile: function profile() { [native code] } profileEnd: function profileEnd() { [native code] } time: function time() { [native code] } timeEnd: function timeEnd() { [native code] } trace: function trace() { [native code] } warn: function warn() { [native code] } __proto__: Object [ I guess there's no way to clear up the console... but I wanted someone to say it to me... ]

    Read the article

  • MbUnit (gallio) and Visual Studio.Net Tests Not Completing or Debugging

    - by Davy
    Hi I'm using Gallio\MbUnit 3.1 with ReSharper and Visual Studio 2008. Everything is working well except this type of test: [Test] [Row("test@badEmail@_test.com")] [Row("test@badEmail@_test.")] public void IsValidEmail_Invalid_Emails_Should_Return_False(string invalidEmail) { Assert.IsFalse(AppHelper.IsValidEmail(invalidEmail), "Email validation failed for " + invalidEmail); } The test doesn't complete or go in to debug mode only when I pass in a parameter E.g. 'string invalidEmail'. If I remove that prameter it seems to work normally. It will run the test if I have: [Test] public void IsValidEmail_Invalid_Emails_Should_Return_False() { var invalidName = test@badEmail@_test.com"; Assert.IsFalse(AppHelper.IsValidEmail(invalidEmail), "Email validation failed for " + invalidEmail); } I appreciate that there may be better ways to achieve this test but I'm trying to work my way through a book and this is how it's explaining things. Any help is appreciated. Davy

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >