text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Re: [OT] wicket users around the world China, ZheJiang NingBo francisco treacy-2 wrote: to know a little bit more of our great (and vast) community, i was just wondering if you're keen on sharing where you come from and/or where you work with wicket... for instance, here argentinian/belgian working with wicket in antibes, [GMAP2] how to add float Panel my requirement desc: 1.add a float panel component at top left corner of the GMAP2, when the map zoom in or zoom out, the panel alway show at top left corner. 2.adjust panel transparency, so user can see map image behind the panel. so i want to know how to code in GMAP2. thanks. -- View Re: Modal window not appearing in IE here is ajax debug message, i found that there has a error var settings = new Object(); settings.minWidth=200; settings.minHeight=200; settings.className=w_blue; settings.width=460; settings.height=500; settings.resizable=true; settings.element = element; settings.cookieId=mwCreateOrder; ModalWindow not appearing in IE ModalWindow can not appear in IE 6.x, but Firefox 3.x has no problem. In IE 6.x, when click show ModalWindow link, the server side code invoke, but the browser not show the modalwindow. ajax debug message detail as follow: INFO: focus removed from wicket-generated-id-120 INFO: focus set on how to build lastest 1.3.x jar I can not found where to get lastest 1.3.x jar file, so I build from source, but there always has error. check out lastest code from;, then build with mvn installl, but build failure because some test case run error. so I build with Re: Modal window not appearing in IE We had a similar problem about modelWindow, Firefox/Opera/Google browser all worked fine, but IE did not show modelwindow, by wicket debug, I found that the server has send ajax modelwindow CDATA, the detail debug information is in attachment. Re: Modal window not appearing in IE /td /tr /wicket:panle i do not know how to resolve the problem, Could someone give me some suggestion about the problem. NHSoft.YHW how to get HttpServletRequest in wicket 1.5 in wicket 1.4.x, the code like : HttpServletRequest request = getWebRequestCycle().getWebRequest().getHttpServletRequest(); but i don't know how to get HttpServletRequest in wicket 1.5 - 外卖订餐分享工具 -- View this message in context: Re: how to get HttpServletRequest in wicket 1.5 in wicket 1.4.x getRequestCycle().setRequestTarget(new RedirectRequestTarget(/connect/qq/login)); how to code for wicket 1.5.0 - 外卖订餐分享工具 -- View this message in context: Re: how to get HttpServletRequest in wicket 1.5 Migrate Question Q1: PackageResourceReference resRef = new PackageResourceReference(parent.getClass(), src); return (urlFor(resRef).toString()); PageParameters is required for urlFor method, if why PageParameters is required. Q2: Image imgThumbnail = new Image(thumbnailImage); Re: how to get HttpServletRequest in wicket 1.5 - 外卖订餐分享工具 -- View this message Re: how to get HttpServletRequest in wicket 1.5 Q9. i found that modalwindow has some problem for firefox browse after upgrading to wicket 1.5. firefox version 6.0.1, modalwindow can not display when click open modalwindow link, but when i switch firefox's private browsing mode, it works . Chrome, IE8, Safari is ok. - Re: how to get HttpServletRequest in wicket 1.5 nhsoft.yhw wrote: My solution Re: how to get HttpServletRequest in wicket 1.5 Q5:my code for wicket1.5 as follow: final Link lnkExport = new Link(export) { public void onClick() { Shop shop = shopService.read(shopId); // temporarily switch off paging of results ModalWindow in IE6, IE7, IE8 browser issues Q1: After the upgrade to 1.5 version , I found that the ModalWindow appear in IE Page Expired error, but in Chrome browser to normal. Same Code for ModalWindow works for Firefox, IE, Chrome with wicket 1.4.18 version. My ModalWindow Use WebPage Mode, not Page Mode. Q2: sometimes Modalwindow Re: ModalWindow in IE6, IE7, IE8 browser issues here is exception stack, but only IE throws the exception ERROR - DefaultExceptionMapper - Connection lost, give up responding. org.apache.wicket.protocol.http.servlet.ResponseIOException: ClientAbortException: java.io.IOException at Re: ModalWindow in IE6, IE7, IE8 browser issues I swith to use modal dialog with panel, it works. ModalWindow seems to have some strange problems, sometimes it is difficult to reproduce. For example, some of my applications ModalWindow normal, some abnormal, but I can not find reason. - 外卖订餐分享工具 -- View this message Is there ModalWindow alternative options Is there ModalWindow alternative options, I found that the ModelWindow component has browser compatibility problems. Original use of ModalWindow is no problem in the wicket 1.4.x version, but after upgrading to 1.5.1 version, I found several used ModalWindow Page is normal, several used Re: Is there ModalWindow alternative options jcgarciam wrote: Is this probably related to the usage of ModalWindow with PageCreator instead of Panel content? in some ModalWindow content Pages I try to use the Panel replace WebPage, if there has the scroll bar in IE6 ModalWindow with panel content mode will display More than one Re: Is there ModalWindow alternative options for example: wicket version 1.5.0 or 1.5.1 DataView with each row having Modalwindow int chrome, all works; in IE8 with X-UA-Compatible mode can not display row data, and server side did not receive browser request; in IE8 with normal mode can not display row data, and server side throw Re: Is there ModalWindow alternative options Martin Grigorov-4 wrote: This looks like which is fixed in trunk -- Martin Grigorov jWeekend Training, Consulting, Development I just checkout lastest wicket snapshot code and build my application, but use the Re: Is there ModalWindow alternative options I've got no problems with the quickstart application, I do not know how to reproduce, I think this issue and modalwindow matter, because all broken pages are used modalwindow components -- View this message in context: RE: Occasional Software caused connection abort: socket write error with 1.5 my application has same problem, but it only throw socket error when IE 6 - 8 brower, chrome and IE9 has no the problem. here is my question: i have test by wicket 1.5.2 take 2 version, the RE: Occasional Software caused connection abort: socket write error with 1.5 You tried google chrome browser? chrome browser I found no problem. -- View this message in context: Sent from the Users forum mailing list archive at Re: ModalWindow shows Error Page in Opera Wicket 1.5.x have fixed the problem. -- View this message in context: Sent from the Users forum mailing list archive at Nabble.com. Re: Occasional Software caused connection abort: socket write error with 1.5 I try to reproduce the problem to create quickStart demo, but this error problem only in my real application occurs, My situation is that only use IE 6 7 8 visits the page with modalwindow will throw be connection problem. I will try to reproduce later. -- View this message in context: RE: Occasional Software caused connection abort: socket write error with 1.5 I do not think so. My application is upgraded from wicket 1.4.18 to 1.5.x, in wicket1.4.x using IE6, IE7, IE8 browser is normal, 'ClientAbortException error' appeared after the upgrade to wicket1.5.1, and use Chrome browser or IE9 is no problem both wicket 1.4.x and 1.5.x. Only some of the Re: EOFException(java.net.SocketException: Connection reset by peer: socket write error) jira issues: Is only in IE6, IE7, IE8 will occur in this problem? -- View this message in context: Re: Exception (Header was already written to response!) when setting response page in IRequestCycleListener I have the same problem, but only in IE browser, firefox or chrome works - first wicket application: 114生活网 -- View this message in context: Re: Seeing sporadic ClassNotFoundExceptions after upgrading from 1.4.9 or 1.4.11 I have same problem also, This situation occasionally occurs. Nitnatsnok wrote 03-13 18:37:30.466[ WicketObjects.java:82 :WARN ] Could not resolve class [resources] java.lang.ClassNotFoundException: resources at Re: Seeing sporadic ClassNotFoundExceptions after upgrading from 1.4.9 or 1.4.11 Martin Grigorov-4 wrote Hi, Try with 1.4.20. I remember such problem have been fixed at some point. 1.4.11 is too old. I am using wicket 1.5.5, This problem has always existed from version 1.4.9 to version 1.5.x. However, this problem seems to have little effect, this problem the Brix CMS has stopped development? I am looking for a product based on wicket cms, I found brix cms is very good, it can meet the customized development needs, but browse brix cms's github code, I found brix cms project nearly two years no code updates, upgrades, brix cms whether the project has stopped development? Brix CMS Site why swarm not render link my hive file: grant { permission ${ComponentPermission} wm.wicket.pages.HomePage, inherit, render; permission ${ComponentPermission} wm.wicket.pages.HomePage, enable; permission ${ComponentPermission} wm.wicket.pages.ManageCenterPage, inherit, render;
https://www.mail-archive.com/search?l=users@wicket.apache.org&q=from:%22nhsoft.yhw%22
CC-MAIN-2022-40
refinedweb
1,517
57.06
Red Hat Bugzilla – Bug 974364 Inaccurate comparison because of String to Double coercion Last modified: 2014-08-06 16:19:45 EDT Description of problem: Platform BZ for Steps to Reproduce: import org.drools.compiler.Person; rule R1 when $p : Person( name < "90201304122000000000000017" ) then end ksession.insert( new Person( "90201304122000000000000015", 38 ) ); Actual results: The rule is not fired Expected results: The rule is fired Toshiya Kobayashi <tkobayas@redhat.com> made a comment on jira DROOLS-167 Sent a pull request for a test case. Probably it should be converted to BigDecimal or just compared as String. Mario Fusco <mario.fusco@gmail.com> updated the status of jira DROOLS-167 to Resolved Mario Fusco <mario.fusco@gmail.com> made a comment on jira DROOLS-167 Fixed with mvel 2.1.6 Fixed. Verified on BRMS 6.0.0-ER2.
https://bugzilla.redhat.com/show_bug.cgi?id=974364
CC-MAIN-2017-34
refinedweb
138
58.58
On Wed, Feb 01, 2017 at 03:26:45PM +0100, wm4 wrote: > On Wed, 1 Feb 2017 14:35:50 +0100 > Michael Niedermayer <michael at niedermayer.cc> wrote: > > > Found-by: ubitux > > Signed-off-by: Michael Niedermayer <michael at niedermayer.cc> > > --- > > libavutil/internal.h | 4 ++++ > > 1 file changed, 4 insertions(+) > > > > diff --git a/libavutil/internal.h b/libavutil/internal.h > > index a19975d474..e97034887b 100644 > > --- a/libavutil/internal.h > > +++ b/libavutil/internal.h > > @@ -243,8 +243,12 @@ void avpriv_request_sample(void *avc, > > #pragma comment(linker, "/include:" EXTERN_PREFIX "avpriv_snprintf") > > #endif > > > > +// Rename shared function (both use and implementation of them) so they are not shared > > +// and each library carries its own copy of a implementation, this is needed as > > So why are they not appropriately named in the first place? > > > +// the fd numbers are not transportable between libs on windows > > AFAIK they are, as long as they're linked to the same stdlib (which > probably is the case for libav*). here is the commit introducing the first function using this system. I belive its commit message is quite good and explains the reasoning. Beyond that iam the wrong one to discuss this with, iam not a windows developer and i didnt design this, which is not to say i like or dislike it. I just added one function IIRC and i wanted to document it as ubitux seemed to be confused for a moment when seeing it the first time commit e743e7ae6ee7e535c4394bec6fe6650d2b0dbf65 Author: Martin Storsjö <martin at martin.st> Date: Fri Aug 9 11:06:46 2013 +0300 libavutil: Make avpriv_open a library-internal function on msvcrt Add one copy of the function into each of the libraries, similarly to what we do for log2_tab. When using static libs, only one copy of the file_open.o object file gets included, while when using shared libraries, each of them get a copy of its own. This fixes DLL builds with a statically linked C runtime, where each DLL effectively has got its own instance of the C runtime, where file descriptors can't be shared across runtimes. On systems not using msvcrt, the function is not duplicated. [...] --: signature.asc Type: application/pgp-signature Size: 181 bytes Desc: Digital signature URL: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2017-February/206577.html
CC-MAIN-2019-18
refinedweb
364
60.45
This is your resource to discuss support topics with your peers, and learn from each other. 02-20-2013 06:26 PM I am trying to make a shared library. I used the Blackberry Project -> Shared Library and went for the Makefile option. The source files and header files are being compiled and included. The hard part is getting the moc to work. Here is my Makefile: LIST=CPU ifndef QRECURSE QRECURSE=recurse.mk ifdef QCONFIG QRDIR=$(dir $(QCONFIG)) endif endif include $(QRDIR)$(QRECURSE) MOC := /Applications/bbndk/host_10_0_9_534/darwin/x86/usr /bin/moc SRC+=moc_file.cpp moc_%.cpp: %.h $(MOC) $(DEFINES) $(INCVPATH) $< -o $@/bin/moc SRC+=moc_file.cpp moc_%.cpp: %.h $(MOC) $(DEFINES) $(INCVPATH) $< -o $@ The project contains a src directory and a public directory. The src directory contains headers and source files and the public directory contains public headers. I have modified the common.mk to include these in the EXTRA_SRCVPATH. My basic assumption is that when make goes looking for moc_file.cpp it would read the rules and realise moc_file.cpp can be created from file.h with the moc command, but this cannot be the case as I continuously get the error No rule to make target `moc_file.o', needed by libry.a. So how does it really work and how can I fix this? 02-21-2013 04:18 PM do you have moc_file.cpp successfully created by moc based on file.h? It seems in your case make can't find a rule to create moc_file.o file based on your moc_file.cpp 02-21-2013 04:51 PM 02-21-2013 04:56 PM That's the problem. I am afraid 'Shared library' type of project is not considered by NDK as 'Cascades-like' project so new project does not know that it needs to run moc on .h files containing Q_OBJECT. I'd look on how ordinary Cascades project handles this and added the same to your makefiles. 02-21-2013 05:02 PM That's what I would hope to do by adding this SRC+=moc_file.cpp moc_%.cpp: %.h $(MOC) $(DEFINES) $(INCVPATH) $< -o $@ by adding the moc_file.cpp to the SRC macro, I'd hope that make would see this file does not exist and call the rule, but it doesn't. Then there is this rule MOC_MODULES := $(patsubst %.h, moc_%, $(shell grep -l Q_OBJECT *.h)) that could be used to find the files that do contain Q_OBJECT but sadly *.h always thorws up an error saying that grep: *.h: No such file or directory. 02-21-2013 05:48 PM 02-22-2013 08:41 AM So, fixed? 03-10-2013 12:42 AM Anybody knows how to run moc if using CDT internal builder in project?
https://supportforums.blackberry.com/t5/Native-Development/moc-rule-in-Makefile-not-working/m-p/2184517
CC-MAIN-2016-44
refinedweb
457
77.33
i have created a recursive method that returns the size of a binary search tree, i would like to analyze the running time of my implementation but i dont know how. I know the best case is O(1) if node is null but what about worst case? my researches online offer conflicting information. One source says to imagine the internal stack which makes me believe O(N^2) and another says to break it up into an equation. I feel like the worst case is O(N) as each of the nodes must be accessed in order to return their value but i have no evidence to support my claim. Any insight would be greatly appreciated. My method is below: private int rSize(Node node){ //traverses through each left then right node and returns the size count if(node==null){ return 0; } else{ return (rSize(node.left) + rSize(node.right) + 1); } }
https://www.daniweb.com/programming/software-development/threads/504140/how-to-analyze-the-running-time-of-a-recursive-function
CC-MAIN-2017-26
refinedweb
152
67.99
Robert Boehne <address@hidden> writes: > I) ? I must caution against installing config.h. You will collide with the potential same config.h and HAVE* et al defines that the application using your header files has figured out for itself. It's much preferable to make sure that the installed include-files do not depend on the autoconf'd parameters in any way. If you really need to use the definitions that configure has figured out for you, it's much better, I think, to partial-evaluate so that instead of: bar.h: #ifdef HAVE_FOO_H #include <foo.h> #endif you make it unconditional (empty or just with the include). This will make that file machine-dependent, but you can most likely limit this to one file and have all the other header files be shared. And if you install config.h, it should be as PACKAGE-config.h. /assar
http://lists.gnu.org/archive/html/automake/2000-10/msg00114.html
CC-MAIN-2015-27
refinedweb
148
67.55
Designing your ActionScript application Creating the HelloWorld project and the Greeter class Adding code to the Greeter class Creating an application that uses your ActionScript code Publishing and testing your ActionScript application Enhancing the HelloWorld application You can create external ActionScript source files with an .as extension using Flash, Flex Builder, Dreamweaver, or any text editor. ActionScript 3.0 can be used within a number of application development environments, including the Flash authoring and Flex Builder tools. This section walks through the steps in creating and enhancing a simple ActionScript 3.0 application using the Flash authoring tool or Flex Builder. The application you’ll build presents a simple pattern for using external ActionScript 3.0 class files in Flash and Flex applications. That pattern will apply to all of the other sample applications in this manual. You should have some idea about the application you want to build before you start building it. The representation of your design can be as simple as the name of the application and a brief statement of its purpose, or as complicated as a set of requirements documents containing numerous Unified Modeling Language (UML) diagrams. This manual doesn’t discuss the discipline of software design in detail, but it’s important to keep in mind that application design is an essential step in the development of ActionScript applications. Our first example of an ActionScript application will be a standard “Hello World” application, so its design is very simple: The application will be called HelloWorld. It will display a single text field containing the words “Hello World!” In order to be easily reused, it will use a single object-oriented class, named Greeter, which can be used from within a Flash document or a Flex application. After you create a basic version of the application, you will add new functionality to have the user enter a user name and have the application check the name against a list of known users. With that concise definition in place, you can start building the application itself.. In Flex Builder, select File > New> Flex Project, If the New Flex Project dialog box asks you to select a Flex Server Technology, select Basic, and then click Next. Type HelloWorld as the Project Name, and then click Finish. Your new project will be created and should be showing in the Navigator panel. By default the project should already contain a file named HelloWorld.mxml, and that file should be open in the Editor panel. Now to create a custom ActionScript class file in the Flex Builder tool, select File > New > ActionScript File. In the New ActionScript File dialog box, select HelloWorld as the parent folder, type Greeter.as the filename, and then click Finish. A new ActionScript editing window is displayed. Continue with Adding code to the Greeter class. The Greeter class defines an object, Greeter, that you will be able to use in your HelloWorld application. Type the following code into the new file: package { public class Greeter { public function sayHello():String { var greeting:String; greeting = "Hello World!"; return greeting; } } } The Greeter class includes a single sayHello() method, which returns a string that says “Hello World!”. Select File > Save to save this ActionScript file. The Greeter class is now ready to be used in an application.’s how to attach the Greeter class to your application. Open the HelloWorld.mxml file, and type the following code: <" /> </mx:Application> This Flex project includes three MXML tags: An <mx:Application> tag, which defines the Application container An <mx:Script> tag that includes some ActionScript code An <mx:TextArea> tag, which defines a field to display text messages to the user The code in the <mx:Script> tag defines a initApp() method that is called when the application loads. The initApp() method sets the text value of the mainTxt TextArea to the “Hello World!” string returned by the sayHello() method of the custom class Greeter, which you just wrote. Select File > Save to save the application. Continue with. Select Run > Run. Make sure that the Project field shows “HelloWorld” and the Application file field shows “HelloWorld.mxml”. In the Run dialog box, click Run. The HelloWorld application starts. If any errors or warnings are displayed in the Output window when you test your application, fix the causes of these errors in the HelloWorld.mxml or Greeter.as files, and then try testing the application again. If there are no compilation errors, a browser window opens showing the Hello World application. The text “Hello World!” should be displayed. You have just created a simple but complete object-oriented application that uses ActionScript 3.0. Continue with Enhancing the HelloWorld application. To make the application a little more interesting, you’ll now make it ask for and validate a user name against a predefined list of names. First, you will update the Greeter class to add new functionality. Then you will update the application to use the new functionality. Open the Greeter.as file. Change the contents of the file to the following (new and changed lines are shown in boldface): package { public class Greeter { /** * Defines the names that should features: The validNames array lists valid user names. The array is initialized to a list of three names when the Greeter class is loaded. The sayHello() method now accepts a user name and changes the greeting based on some conditions. If the userName is an empty string (""), the greeting property is set to prompt the user for a name. If the user name is valid, the greeting becomes "Hello, userName." Finally, if either of those two conditions are not met, the greeting variable is set to "Sorry userName, you are not on the list." The validName() method returns true if the inputName is found in the validNames array, and false if it is not found. The statement validNames.indexOf(inputName) checks each of the strings in the validNames array against the inputName string. The Array.indexOf() method returns the index position of the first instance of an object in an array, or the value -1 if the object is not found in the array. you will edit the Flash or Flex file that references this ActionScript class. Open the HelloWorld.mxml file. Next modify the <mx:TextArea> tag to indicate to the user that it is for display only, by changing the background color to a light gray and preventing the user from editing the displayed text: <mx:TextArea Now add the following lines right after the <mx:TextArea> closing tag. These lines create a new TextInput field that lets the user enter a user name value: <mx:HBox <mx:Label <mx:TextInput </mx:HBox> The enter attribute specifies that when the user presses the Enter key in the userNameTxt field, the text in the field will be passed to the Greeter.sayHello() method, and the greeting displayed in the mainTxt field will change accordingly. The final contents of the HelloWorld.mxml file should look like this: <" backgroundColor="#DDDDDD" editable="false" /> <mx:HBox <mx:Label <mx:TextInput </mx:HBox> </mx:Application> Save the edited HelloWorld.mxml file. Select File > Run to run the application. When you run the application, you will be prompted to enter a user name. If it is valid (Sammy, Frank, or Dean), the application will display the “ Hello, userName” confirmation message.
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3_Flex/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fdf.html
CC-MAIN-2016-36
refinedweb
1,222
63.59
Given the overwhelming number of responses to my previous post, I thought should chat to myself on the subject. Question 1, Is this behaviour by design, or is it an oversight? Question 2, Should package developers protect against closing these files? Question 3, Is it better to leave the decision to the user and not close files? For an example function, see ltn12.sink.file(). DB David Burgess wrote: > In 5.1 the files io.stderr, io.stdout and io.stdin may be closed. > > Given this behaviour methinks it would be helpful to provide support > for duplicating files (like the Win32 code below). > > This means that the duplicates of the standard files can be passed to > package functions that unconditionally close files. > (e.g. Luasocket) > > static int f_dup (lua_State *L) { > FILE *f = tofile(L); > const char *mode = luaL_optstring(L, 2, "wb"); > int fd = _dup( _fileno( f )); > FILE **pf = newfile(L); > *pf = _fdopen(fd, mode); > if (*pf == NULL && fd >= 0) _close(fd); > return (*pf == NULL) ? pushresult(L, 0, "dup file") : 1; > } > > David B. >
http://lua-users.org/lists/lua-l/2005-10/msg00044.html
crawl-001
refinedweb
172
76.01
Tekstorm Tekstorm interview questions and answers. We have tried to share some of the manual testing interview questions, selenium interview questions & testing interview questions also, but we are recommending spending some quality time to get comfortable with what might be asked when you go for the Tekstorm. Tekstorm Interview Questions [ Remote Location ] Company Name: Tekstorm Company Location: Bangalore, India Updated on: 19.06.2021 - Difference between equals and ==? Ans : (==) -> is a reference comparison; both objects point to the same memory location (.equals()) -> evaluates to the comparison of values in the objects - When to use if-else and switch-case? - Difference between Xpath vs CSS Selectors? - Disadvantages of Selenium Ans: Captcha, WIN pop-ups, only Web Apps automation - Types of Waits? - Keywords – super and this - System – File.separator - ThreadLocal - Concurrency - Multi-Threading - Replace() vs replaceall() in java - “Do you have experience in handling java system functions? - Actually how you handle windows or os level pop-ups?” - How you write the multi-threading to launch different browsers using selenium? - How you handle if you want to change the properties values for each thread separately? - How can methods be made thread-safe? - How can shared variables be made thread-safe? - What are a few different ways we can run entities in parallel with TestNG? - What are XPath axes? Ans: As a location path defines the location of a node using an absolute or relative path, axes are used to identify elements by their relationship like a parent, child, sibling, etc. Axes are named so because they refer to the axis on which elements are lying relative to an element. - What are selenium actions? Ans: Actions class is an ability provided by Selenium for handling keyboard and mouse events. In Selenium WebDriver, handling these events includes operations such as drag and drop, clicking on multiple elements with the control key, among others - How you select child web elements? Or ancestor elements? - Diff beween css and xpath ? - What are all the ways to find web elements in a browser? - Questions on inner classes (Hands-on code in IDE) - Hands-on experience in using the TestNG framework - How you write a test suit using TestNG? - Write a method to parse the values of a form using some data ( Hands-on coding in IDE) - Final keyword? - What are the methods we have in the CSS selectors? - What startswith() function will do using XPath? - Immutability of objects? - How you write multi-threading? which is the best way to implement it? - What are wrapper classes? (Autoboxing and unboxing concepts) - fileSeperator() function – question related to fileSeperator() ( Hands-on coding in IDE) - write a test method in a given class ( hands-on coding ) - private vs protected modifiers? - which is the best way to select web elements and why? - What is static? - Tell me about yourself and the technologies and the frameworks worked on - what would be the order of println? package com.tekstrom_1; public class Container { public Container() { System.out.println(""in container""); } public class Nested { public Nested() { System.out.println(""in nested""); } public void methodCall() { System.out.println(""in method""); } } }
https://www.softwaretestingo.com/tekstorm-interview-questions/
CC-MAIN-2022-40
refinedweb
510
50.73
I want to get timestamp for my log in c. i have written a function to get timestamp. But when i return the variable i m getting different value. My code: #include <stdio.h> #include <stdlib.h> #include <time.h> char* get_timestamp(){ time_t rawtime; struct tm * timeinfo; char buffer[16]; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer,16,"%G%m%d%H%M%S",timeinfo); puts(buffer); return buffer; } int main() { puts(get_timestamp()); return 0; } output: 20130315204815 Ir?0315204815 Can anyone help out from this... Thank you. buffer[16] is a local array, which stops existing at the end of char* get_timestamp() function. Then you return a pointer to an array that does not exist. You are returning a pointer to a stack variable and therefore it is not valid to use after the function returns: char buffer[16]; Will be allocated on the stack in the function. When you return the stack is cleaned up and buffer is no longer valid. With minimal changes this is probably a better function signature: void get_timestamp( char *buffer, size_t buffLen ) The assumption being that you have properly allocated space for buffer before calling get_timestamp. The string you're returning is an automatic variable. When you exit the function accessing this variable is impossible. According to the specs it's undefined behavior. Use malloc to allocate the string and you'll be fine. Just don't forget to free it afterwards. As the other said, you're using data that resides on the stack and stops existing once you leave the function that declared it. I see two simple possibilities to solve this problem: Option 1: allocate the buffer variable in the calling function, and pass a pointer into get_timestamp void get_timestamp( char *buffer, size_t buffersize ) { .... strftime (buffer,buffersize,"%G%m%d%H%M%S",timeinfo); } int main() { char buffer[16]; puts(get_timestamp(buffer,16)); return 0; } Note/Edit: I folded unwind's very valid remark regarding passing the size of buffer into this suggested solution. Option 2: if you cannot or don't want to change the signature of your function you can use a static variable, but don't forget that static variables can cause issues in multithreaded programs. static char buffer[16]; char* get_timestamp(){ ... } int main() { puts(get_timestamp()); return 0; } You could of course use malloc but that seems overkill in this situation, and is more error prone than the two fixes I described. In answering this question I wanted a function that was simple, thread friendly, did not return a char* (which is often tedious to manage), thread-safe and could stand on its own feet. I have an aversion to functions that return char* or pointers that must be managed. The function below does not call malloc. The function takes no parameters and returns a timestamp. I think it works well. struct Timestamp { time_t seconds; long milliseconds; char timestring[32]; }; struct Timestamp getTimestamp() { char timebuffer[32] = {0}; struct timeval tv = {0}; struct tm *tmval = NULL; struct tm gmtval = {0}; struct timespec curtime = {0}; struct Timestamp timestamp; int i = 0; // Get current time clock_gettime(CLOCK_REALTIME, &curtime); // Set the fields timestamp.seconds = curtime.tv_sec; timestamp.milliseconds = round(curtime.tv_nsec/1.0e6); if((tmval = gmtime_r(×tamp.seconds, &gmtval)) != NULL) { // Build the first part of the time strftime(timebuffer, sizeof timebuffer, "%Y-%m-%d %H:%M:%S", &gmtval); // Add the milliseconds part and build the time string snprintf(timestamp.timestring, sizeof timestamp.timestring, "%s.%03ld", timebuffer, timestamp.milliseconds); } return timestamp; } int main() { char timebuffer[64] = {0}; int i = 0; struct timespec sleeptime = {0, 5000000L}; struct Timestamp timestamp; for (i=0; i < 20; i++) { timestamp = getTimestamp(); printf("Time is: %s \n", timestamp.timestring); nanosleep(&sleeptime, NULL); } return 0; } Similar Questions
http://ebanshi.cc/questions/596713/how-to-get-timestamp-in-c
CC-MAIN-2017-22
refinedweb
617
56.05
. Linux compilation error (opensuse 12.2, 64bit) gcc -DHAVE_CONFIG_H -I. -I.. -pthread -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -pthread -I/usr/include/gimp-2.0 -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/cairo -I/usr/include/libpng14 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/gtk-2.0 -I/usr/lib64/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/pango-1.0 -I/usr/include -g -O2 -MT aaa.o -MD -MP -MF .deps/aaa.Tpo -c -o aaa.o aaa.c In file included from aaa.h:22:0, from aaa.c:21: /usr/include/glib-2.0/glib/gmacros.h:32:2: error: #error "Only <glib.h> can be included directly." Problem are the lines with "#include <glib/gmacros.h>" and "#include <glib/gtypes.h>". Looks like beyond some glib version, sub-modules cannot be included separately. I fixed this by replacing the above includes (1st, 2nd or both) with this one: #include <glib.h> in all source files containing the 1 or 2 mentioned includes. Compilation went well until the final link: gcc -g -O2 -o focusblur aaa.o brush.o depthmap.o diffusion.o focusblurenums.o focusblurparam.o focusblurrc.o focusblurstock.o gimpplugin.o interface.o render.o shine.o source.o -pthread -lgthread-2.0 -lrt -lglib-2.0 /lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: brush.o: undefined reference to symbol 'hypotf@@GLIBC_2.2.5' /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: note: 'hypotf@@GLIBC_2.2.5' is defined in DSO /lib64/libm.so.6 so try adding it to the linker command line /lib64/libm.so.6: could not read symbols: Invalid operation collect2: error: ld returned 1 exit status Any ideas? Yay, solved with Looks libm was somewhat missing in commandline Instead of running plain "./configure", run: ./configure LIBS=-lm then make ..... I try it but... do not solve for me. I've the same error in your first post. I've gimp 2.8 and openSuSe 12.2 64 bit, thanks. Did you also fix the #include Did you also fix the #include in all source files? you must replace "#include <glib/gmacros.h>" or "#include <glib/gtypes.h>" or both in all source files with: "#include <glib.h>" (I used mc to find all occurences and replaced them manually. You will edit about 10 files, it's not too much) Great! Thank a lot! How to create Z-depth map from one photo easily? Hi again: So the last version of FocusBlur I already have, but there's problem with making Z-depth map: Exists any plugin or script for make depthmap from one photography which I want to have lensblured? Making perfect Z-depth map manualy is too hard for my taste and I haven't found anything yet right here and in google. Thank you for feedback - regular GIMPer Last version for Windows 32-bit? I use GIMP 2.6.11 running on WinXP 32-bit... Is there the last version of binaries (3.2.6) for 32-bit Windows copy? Thank you for feedback, regular user I compiled the 32 bit version for 3.2.6 the link is posted here. -Rod Thank you, trying out Thank you for feedback, I'm trying it out now ;) focusblur-3.2.5 & 3.2.6 binaries Gimp 64 bit Window Bonjour, 1 478 496 bytes. Pages
http://registry.gimp.org/comment/16773
CC-MAIN-2014-49
refinedweb
600
63.25
Finding list item, table cell, tree node, or control by location973901 Nov 18, 2012 10:46 PM One of my favorite features about swing was the ability to get a UI component reference via Container.getComponentAt(int x, int y), or a particular list item via JList.locationToIndex(Point p) (or other similar methods). I haven't been able to find the same or similar functionality in JFX so far... can someone point me in the right direction? Thanks! Thanks! This content has been marked as final. Show 2 replies 1. Re: Finding list item, table cell, tree node, or control by locationJames_D Nov 19, 2012 1:33 AM (in response to 973901)I don't know a way. When I started with JavaFX I had the same question; however I found I don't actually need to do this. In Swing I always needed this when I was, say, processing mouse clicks on a JList. In JavaFX, you can register event handlers with the cells directly. This doesn't work in swing (at least, not without a huge amount of effort). So whereas in Swing the way to map a mouse click on a JList to the corresponding list item was to register a listener with the JList and then pass the mouse click coordinates to locationToIndex(...), in JavaFX you just register the listener with the cell: Of course, this might not be your use case, and you may really need this functionality. Someone else may have a more direct response... import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import javafx.util.Callback; public class ListTest extends Application { @Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); ListView<String> listView = new ListView<String>(); listView.getItems().addAll("Apples", "Oranges", "Grapefruit", "Bananas"); listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() { @Override public ListCell<String> call(ListView<String> param) { return new CustomListCell(); } }); root.setCenter(listView); Scene scene = new Scene(root, 300, 300); primaryStage.setScene(scene); primaryStage.show(); } private class CustomListCell extends ListCell<String> { private final EventHandler<MouseEvent> listener = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.printf("Mouse clicked on list cell with %s (item number %d)",getItem(), getIndex()); if (isEmpty()) { System.out.print(" (Empty cell)"); } System.out.println(); } }; private CustomListCell() { this.addEventHandler(MouseEvent.MOUSE_CLICKED, listener); } @Override public void updateItem(String item , boolean empty) { super.updateItem(item, empty); if (! empty) { setText(item); } else { setText(null); } } } public static void main(String[] args) {launch(args);} } 2. Re: Finding list item, table cell, tree node, or control by location973901 Nov 19, 2012 3:15 AM (in response to James_D)In most cases I like to use as little code as possible, so subclassing the list cells didn't seem very attractive to me. Also, at least from my experience with TableView, much of the underlying API is not public or documented, and I haven't found an easy way yet of enumerating all of the nodes a particular event will touch before reaching its target. So getting an object reference to the component I need to address is sometimes tedious. Getting elements by coordinates just seems natural to me. Having said that, I do love JFX's event model, and with your outline I should have no problem doing what I need to do. Your response was complete and answered my question well; I very much appreciate the time and effort. I have a similar question up (Swing functionality missing in JavaFX) that I have been DYING to find info on. If you know anything on that subject as well, I would love you forever. Alternative to SpringLayout? And I promise I will be active on these forums answering questions and being more helpful than a high maintenance knowledge-sucker as soon as I get a solid handle on this stuff. =P
https://community.oracle.com/thread/2467427?tstart=165
CC-MAIN-2016-36
refinedweb
661
58.08
How to Get Input with Java’s Scanner Class. The techniques that I present here are used in many of the programs shown in the rest of this book. If you’re using an older version of Java, you should still read this, because many programs use the Scanner class. The simple program below uses the Scanner class to read an integer value from the user and then displays the value back to the console to verify that the program received the value entered by the user. Here’s a sample of the console window for this program: Enter an integer: 5 You entered 5. The program begins by displaying the message Enter an integer: on the first line. Then it waits for you to enter a number. When you type a number (such as 5) and press the Enter key, it displays the confirmation message ( You entered 5.) on the second line. import java.util.Scanner;@@ra1 public class ScannerApp { static Scanner sc = new Scanner(System.in);@@ra6 public static void main(String[] args) { System.out.print("Enter an integer: ");@@ra10 int x = sc.nextInt();@@ra11 System.out.println("You entered " + x + ".");@@ra12 } } Importing the Scanner class in Java Before you can use the Scanner class in a program, you must import it. To do that, you code an import statement at the beginning of the program, before the class declaration: import java.util.Scanner; Note that java and util aren’t capitalized, but Scanner is. If you’re using other classes in the java.util package, you can import the entire package by coding the import statement like this: import java.util.*; Declaring and creating a Scanner object in Java Before you can use the Scanner class to read input from the console, you must declare a Scanner variable and create an instance of the Scanner class. You might want to create the Scanner variable as a class variable and create the Scanner object in the class variable initializer, as shown in line 6 of the program above: static Scanner sc = new Scanner(System.in); That way, you can use the sc variable in any method in the class. To create a Scanner object, you use the new keyword followed by a call to the Scanner class constructor. Note that the Scanner class requires a parameter that indicates the input stream that the input comes from. You can use System.in here to specify standard keyboard console input. Getting input To read an input value from the user, you can use one of the methods of the Scanner class that are listed below. As you can see, the primitive data type has a separate method. Notice in the first column of the table that each method listing begins with the type of the value that’s returned by the method. The nextInt method, for example, returns an int value. Also, notice that each of the methods ends with an empty set of parentheses. That means that these methods don’t require parameters. If a method does require parameters, the parameters are listed within these parentheses. Because these methods read a value from the user and return the value, you most often use them in statements that assign the value to a variable. Line 11, for example, reads an int and assigns it to a variable named x. When the nextInt method is executed, the program waits for the user to enter a value in the console window. To let the user know what kind of input the program expects, usually you should call the System.out.print method before you call a Scanner method to get input. Line 10 calls System.out.print to display the message Enter an integer: on the console. That way, the user knows that the program is waiting for input. If the user enters a value that can’t be converted to the correct type, the program crashes, which means that it terminates abruptly. As the program crashes, it displays a cryptic error message that indicates what caused the failure. If you enter three instead of an actual number, for example, the console window looks something like this: Enter an integer: three ScannerApp.main(ScannerApp.java:11) This message indicates that an exception called InputMismatchException has occurred, which means that the program was expecting to see an integer but got something else instead. If you don’t know how to provide for exceptions like these so that the program can display a friendlier message and give the user another shot at entering a correct value, you have to put up with the fact that if the user enters incorrect data, your program crashes ungracefully. You can prevent the nextInt and similar methods from crashing with incorrect input data by first using one of the methods listed here to test the next input to make sure it’s valid.
https://www.dummies.com/programming/java/get-input-javas-scanner-class/
CC-MAIN-2019-30
refinedweb
815
62.88
04 September 2012 11:53 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> At the site, the 300,000 tonne/year standalone HDPE plant, which is currently producing high molecular HDPE blow moulding grade, will be changed to HDPE natural pipe production, the source said. “We are rather new in the pipe market. We plan to market this product to Jam’s other 300,000 tonne/year HDPE/LLDPE swing plant, which is producing HDPE injection grade, will be switched to LLDPE film production, the source said. “This bimodal C4-LLDPE film is a terpolymer type which we are trying to market locally to the niche demand,” the source added. Such C4-LLDPE film is used in the film packaging sector for heavy duty sacks. Because of these switches in production, Jam has stopped accepting new orders starting from 1 September for 40 days for HDPE blow moulding grade. Jam is an active exporter of HDPE blow moulding and injection grades into “We may still accept some HDPE injection orders for now, but commitments will be small ahead of the change in production,”
http://www.icis.com/Articles/2012/09/04/9592403/irans-jam-petchem-to-switch-to-lldpe-film-hdpe-pipe-output.html
CC-MAIN-2014-15
refinedweb
182
66.67
#include <hallo.h> * Paul Hampson [Wed, Mar 02 2005, 08:05:14PM]: > > I've used this, but briefly, in NetBSD. So maybe I'm missing something > > when I ask: how is this different from "mount --bind" in kernels 2.4 and up? It is different. --bind does only 1:1 copy (files are written to the source directory, for example), unionfs puts the changed files in one of the underlying directories. > Hmm. I misread this as the oft-wished-for transparent overlay > filesystem. > > Either I'm daft, or the naming/description might need work... > "merge" is possibly the wrong word here? Hm. Is that better: The unionfs driver provides a unification file system for the Linux kernel. It allows to virtually merge the contents of several directories and/or stack them, so that apparent file changes in the unionfs end in file changes in only one of the source directories (which makes possible to "change" files on read-only filesystems). Regards, Eduard. -- <sesom> äöü ÃDÃVÃ\ Ã_ <sesom> Sind das Umlaute oder Fragezeichen? <HE> sesom: Das ist UTF8. <sesom> Stimmt. Was kommt bei dir an? <HE> Zeichenmüll. Attachment: signature.asc Description: Digital signature
https://lists.debian.org/debian-devel/2005/03/msg00069.html
CC-MAIN-2015-35
refinedweb
194
67.04
File I/O - ALLEGRO_FILE - ALLEGRO_FILE_INTERFACE - ALLEGRO_SEEK - al_fopen - al_fopen_interface - al_fopen_slice - al_fclose - al_fread - al_fwrite - al_fflush - al_ftell - al_fseek - al_feof - al_ferror - al_ferrmsg - al_fclearerr - al_fungetc - al_fsize - al_fgetc - al_fputc - al_fprintf - al_vfprintf - al_fread16le - al_fread16be - al_fwrite16le - al_fwrite16be - al_fread32le - al_fread32be - al_fwrite32le - al_fwrite32be - al_fgets - al_fget_ustr - al_fputs - Standard I/O specific routines - Alternative file streams These functions are declared in the main Allegro header file: #include <allegro5/allegro.h> ALLEGRO_FILE typedef struct ALLEGRO_FILE ALLEGRO_FILE; An opaque object representing an open file. This could be a real file on disk or a virtual file. ALLEGRO_FILE_INTERFACE typedef struct ALLEGRO_FILE_INTERFACE A structure containing function pointers to handle a type of "file", real or virtual. See the full discussion in al_set_new_file_interface. The fields are: void* (*fi_fopen)(const char *path, const char *mode); bool (*fi_fclose)(ALLEGRO_FILE *f); size_t (*fi_fread)(ALLEGRO_FILE *f, void *ptr, size_t size); size_t (*fi_fwrite)(ALLEGRO_FILE *f, const void *ptr, size_t size); bool (*fi_fflush)(ALLEGRO_FILE *f); int64_t (*fi_ftell)(ALLEGRO_FILE *f); bool (*fi_fseek)(ALLEGRO_FILE *f, int64_t offset, int whence); bool (*fi_feof)(ALLEGRO_FILE *f); int (*fi_ferror)(ALLEGRO_FILE *f); const char * (*fi_ferrmsg)(ALLEGRO_FILE *f); void (*fi_fclearerr)(ALLEGRO_FILE *f); int (*fi_fungetc)(ALLEGRO_FILE *f, int c); off_t (*fi_fsize)(ALLEGRO_FILE *f);. The fi_fclose function must clean up and free the userdata, but Allegro will free the ALLEGRO_FILE handle. If fi_fungetc is NULL, then Allegro's default implementation of a 16 char long buffer will be used. ALLEGRO_SEEK typedef enum ALLEGRO_SEEK - ALLEGRO_SEEK_SET - seek relative to beginning of file - ALLEGRO_SEEK_CUR - seek relative to current file position - ALLEGRO_SEEK_END - seek relative to end of file al_fopen ALLEG. al_fopen_interface ALLEGRO_FILE *al_fopen_interface(const ALLEGRO_FILE_INTERFACE *drv, const char *path, const char *mode) Opens a file using the specified interface, instead of the interface set with al_set_new_file_interface. al_fopen_slice ALLEGRO_FILE *al_fopen_slice(ALLEGRO_FILE *fp, size_t initial_size, const char *mode) Opens a slice (subset) of an already open random access file as if it were a stand alone file. While the slice is open, the parent file handle must not be used in any way. The slice is opened at the current location of the parent file, up through initial_size bytes. The initial_size may be any non-negative integer that will not exceed the bounds of the parent file. Seeking with ALLEGRO_SEEK_SET will be relative to this starting location. ALLEGRO_SEEK_END will be relative to the starting location plus the size of the slice. The mode can be any combination of: - r: read access - w: write access - e: expandable For example, a mode of "rw" indicates the file can be read and written. (Note that this is slightly different from the stdio modes.) Keep in mind that the parent file must support random access and be open in normal write mode (not append) for the slice to work in a well defined way. If the slice is marked as expandable, then reads and writes can happen after the initial end point, and the slice will grow accordingly. Otherwise, all activity is restricted to the initial size of the slice. A slice must be closed with al_fclose. The parent file will then be positioned immediately after the end of the slice. Since: 5.0.6, 5.1.0 al_fclose bool al_fclose(ALLEGRO_FILE *f) Close the given file, writing any buffered output data (if any). Returns true on success, false on failure. errno is set to indicate the error. al_fread size_t al_fread(ALLEGRO_FILE *f, void *ptr, size_t size) Read 'size' bytes into the buffer pointed to by 'ptr', from the given file. Returns the number of bytes actually read. If an error occurs, or the end-of-file is reached, the return value is a short byte count (or zero). al_fread() does not distinguish between EOF and other errors. Use al_feof and al_ferror to determine which occurred. See also: al_fgetc, al_fread16be, al_fread16le, al_fread32be, al_fread32le al_fwrite size_t al_fwrite(ALLEGRO_FILE *f, const void *ptr, size_t size) Write 'size' bytes from the buffer pointed to by 'ptr' into the given file. Returns the number of bytes actually written. If an error occurs, the return value is a short byte count (or zero). See also: al_fputc, al_fputs, al_fwrite16be, al_fwrite16le, al_fwrite32be, al_fwrite32le al_fflush bool al_fflush(ALLEGRO_FILE *f) Flush any pending writes to the given file. Returns true on success, false otherwise. errno is set to indicate the error. See also: al_get_errno al_ftell int64_t al_ftell(ALLEGRO_FILE *f) Returns the current position in the given file, or -1 on error. errno is set to indicate the error. On some platforms this function may not support large files. See also: al_fseek, al_get_errno al_fseek bool al_fseek(ALLEGRO_FILE *f, int64_t offset, int whence). See also: al_ftell, al_get_errno al_feof bool al_feof(ALLEGRO_FILE *f): al_ferror, al_fclearerr al_ferror int al_ferror(ALLEGRO_FILE *f) Returns non-zero if the error indicator is set on the given file, i.e. there was some sort of previous error. The error code may be system or file interface specific. See also: al_feof, al_fclearerr, al_ferrmsg al_ferrmsg const char *al_ferrmsg(ALLEGRO_FILE *f) Return a message string with details about the last error that occurred on the given file handle. The returned string is empty if there was no error, or if the file interface does not provide more information. See also: al_fclearerr, al_ferror al_fclearerr void al_fclearerr(ALLEGRO_FILE *f) Clear the error indicator for the given file. The standard I/O backend also clears the end-of-file indicator, and other backends should try to do this. However, they may not if it would require too much effort (e.g. PhysicsFS backend), so your code should not rely on it if you need your code to be portable to other backends. See also: al_ferror, al_feof al_fungetc int al_fungetc(ALLEGRO_FILE *f, int c) and al_ftell are relative to the number of pushbacks. If a pushback causes the position to become negative, the behavior of al_fseek and al_ftell are undefined. See also: al_fgetc, al_get_errno al_fsize int64_t al_fsize(ALLEGRO_FILE *f) Return the size of the file, if it can be determined, or -1 otherwise. al_fgetc int al_fgetc(ALLEGRO_FILE *f) Read and return next byte in the given file. Returns EOF on end of file or if an error occurred. See also: al_fungetc al_fputc int al_fputc(ALLEGRO_FILE *f, int c) Write a single byte to the given file. The byte written is the value of c cast to an unsigned char. Parameters: - c - byte value to write - f - file to write to Returns the written byte (cast back to an int) on success, or EOF on error. al_fprintf int al_fprintf(ALLEGRO_FILE *pfile, const char *format, ...) Writes to a file with stdio "printf"-like formatting. Returns the number of bytes written, or a negative number on error. See also: al_vfprintf al_vfprintf int al_vfprintf(ALLEGRO_FILE *pfile, const char *format, va_list args) Like al_fprintf but takes a va_list. Useful for creating your own variations of formatted printing. Returns the number of bytes written, or a negative number on error. See also: al_fprintf al_fread16le int16_t al_fread16le(ALLEGRO_FILE *f) Reads a 16-bit word in little-endian format (LSBbe al_fread16be int16_t al_fread16be(ALLEGRO_FILE *f) Reads a 16-bit word in big-endian format (MSBle al_fwrite16le size_t al_fwrite16le(ALLEGRO_FILE *f, int16_t w) Writes a 16-bit word in little-endian format (LSB first). Returns the number of bytes written: 2 on success, less than 2 on an error. See also: al_fwrite16be al_fwrite16be size_t al_fwrite16be(ALLEGRO_FILE *f, int16_t w) Writes a 16-bit word in big-endian format (MSB first). Returns the number of bytes written: 2 on success, less than 2 on an error. See also: al_fwrite16le al_fread32le int32_t al_fread32le(ALLEGRO_FILE *f) Reads a 32-bit word in little-endian format (LSBbe al_fread32be int32_t al_fread32be(ALLEGRO_FILE *f) Read a 32-bit word in big-endian format (MSBle al_fwrite32le size_t al_fwrite32le(ALLEGRO_FILE *f, int32_t l) Writes a 32-bit word in little-endian format (LSB first). Returns the number of bytes written: 4 on success, less than 4 on an error. See also: al_fwrite32be al_fwrite32be size_t al_fwrite32be(ALLEGRO_FILE *f, int32_t l) Writes a 32-bit word in big-endian format (MSB first). Returns the number of bytes written: 4 on success, less than 4 on an error. See also: al_fwrite32le al_fgets char *al_fgets(ALLEGRO_FILE *f, char * const buf, size_t max) Read a string of bytes terminated with a newline or end-of-file into the buffer given. The line terminator(s), if any, are included in the returned string. A maximum of max-1 bytes are read, with one byte being reserved for a NUL terminator. Parameters: - f - file to read from - buf - buffer to fill - max - maximum size of buffer Returns the pointer to buf on success. Returns NULL if an error occurred or if the end of file was reached without reading any bytes. See al_fopen about translations of end-of-line characters. See also: al_fget_ustr al_fget_ustr ALLEGRO_USTR *al_fget_ustr(ALLEGRO_FILE *f) Read a string of bytes terminated with a newline or end-of-file. The line terminator(s), if any, are included in the returned string. On success returns a pointer to a new ALLEGRO_USTR structure. This must be freed eventually with al_ustr_free. Returns NULL if an error occurred or if the end of file was reached without reading any bytes. See al_fopen about translations of end-of-line characters. See also: al_fgetc, al_fgets al_fputs int al_fputs(ALLEGRO_FILE *f, char const *p) Writes a string to file. Apart from the return value, this is equivalent to: al_fwrite(f, p, strlen(p)); Parameters: - f - file handle to write to - p - string to write Returns a non-negative integer on success, EOF on error. Note: depending on the stream type and the mode passed to al_fopen, newline characters in the string may or may not be automatically translated to native end-of-line sequences, e.g. CR/LF instead of LF. Standard I/O specific routines al_fopen_fd ALLEGRO_FILE *al_fopen_fd(int fd, const char *mode) Create an ALLEGRO_FILE object that operates on an open file descriptor using stdio routines. See the documentation of fdopen() for a description of the 'mode' argument. Returns an ALLEGRO_FILE object on success or NULL on an error. On an error, the Allegro errno will be set and the file descriptor will not be closed. The file descriptor will be closed by al_fclose so you should not call close() on it. al_make_temp_file ALLEGRO_FILE *al_make_temp_file(const char *template, ALLEGRO_PATH **ret_path) Make a temporary randomly named file given a filename 'template'. 'template' is a string giving the format of the generated filename and should include one or more capital Xs. The Xs are replaced with random alphanumeric characters, produced using a simple pseudo-random number generator only. There should be no path separators. If 'ret_path' is not NULL, the address it points to will be set to point to a new path structure with the name of the temporary file. Returns the opened ALLEGRO_FILE on success, NULL on failure. Alternative file streams By default, the Allegro file I/O routines use the C library I/O routines, hence work with files on the local filesystem, but can be overridden so that you can read and write to other streams. For example, you can work with blocks of memory or sub-files inside .zip files. There are two ways to get an ALLEGRO_FILE that doesn't use stdio. An addon library may provide a function that returns a new ALLEGRO_FILE directly, after which, all al_f* calls on that object will use overridden functions for that type of stream. Alternatively, al_set_new_file_interface changes which function will handle the following al_fopen calls for the current thread. al_set_new_file_interface void al_set_new_file_interface(const ALLEGRO_FILE_INTERFACE *file_interface) Set the ALLEGRO_FILE_INTERFACE table for the calling thread. This will change the handler for later calls to al_fopen. See also: al_set_standard_file_interface, al_store_state, al_restore_state. al_set_standard_file_interface void al_set_standard_file_interface(void) Set the ALLEGRO_FILE_INTERFACE table to the default, for the calling thread. This will change the handler for later calls to al_fopen. See also: al_set_new_file_interface al_get_new_file_interface const ALLEGRO_FILE_INTERFACE *al_get_new_file_interface(void) Return a pointer to the ALLEGRO_FILE_INTERFACE table in effect for the calling thread. See also: al_store_state, al_restore_state. al_create_file_handle ALLEGRO_FILE *al_create_file_handle(const ALLEGRO_FILE_INTERFACE *drv, void *userdata) Creates an empty, opened file handle with some abstract user data. This allows custom interfaces to extend the ALLEGRO_FILE struct with their own data. You should close the handle with the standard al_fclose function when you are finished with it. See also: al_fopen, al_fclose, al_set_new_file_interface al_get_file_userdata void *al_get_file_userdata(ALLEGRO_FILE *f) Returns a pointer to the custom userdata that is attached to the file handle. This is intended to be used by functions that extend ALLEGRO_FILE_INTERFACE.
http://liballeg.org/a5docs/5.2.1.1/file.html
CC-MAIN-2017-39
refinedweb
2,049
54.52
At the core of xdg-app is a small helper binary that uses Linux features like namespaces to set up sandbox for the application. The main difference between this helper and a full-blown container system is that it runs entirely as the user. It does not require root privileges, and can never allow you to get access to things you would not otherwise have. This is obviously very useful for desktop application sandboxing, but has all sort of other uses. For instance, you can sandbox your builds to avoid them being polluted from the host, or you can run a nonprivileged service with even less privileges. The current helper was a bit too tied to xdg-app, so as part of Project Atomic we decided to create a separate project based on this code, but more generic and minimal. Thus Bubblewrap was born. Bubblewrap is a wrapper tool, similar to sudo or chroot. You pass it an executable and its argument on the command line. However, the executable is run in a custom namespace, which starts out completely empty, with just a tmpfs mounted as the root, and nothing else. You can then use commandline arguments to build up the sandbox. For example, a very simple use of bubblewrap to run a binary with access to everything, but readonly: $ bwrap --ro-bind / / touch ~/foo touch: cannot touch ‘/home/alex/foo’: Read-only file system Or you can use bubblewrap as an regular chroot that doesn’t require you to be root to use it: $ bwrap --bind /some/chroot / /bin/sh Here is a more complicated example with a read-only host /usr (and no other host files), a private pid namespace, and no network access: $ bwrap --ro-bind /usr /usr \ --dir /tmp \ --proc /proc \ --dev /dev \ --ro-bind /etc/resolv.conf /etc/resolv.conf \ --symlink usr/lib /lib \ --symlink usr/lib64 /lib64 \ --symlink usr/bin /bin \ --chdir / \ --unshare-pid \ --unshare-net \ /bin/sh See the bubblewrap manpage for more details. Today I changed xdg-app to use bubblewrap instead of its own helper, which means if you start an app with xdg-app it is using bubblewrap underneath. For now it is using its own copy of the code (using git submodules), but as bubblewrap starts to get deployed more widely we can start using the system installed version of it. 3 thoughts on “Using bubblewrap in xdg-app” Can you quickly summarise how bubblewrap is different to projects like Firejail ()? Do you have any contact address? I wanted to send you a gnome-contacts bugreport without creating another bugzilla account. In case you read this: I cannot add notes to my contacts on archlinux. They will not be saved, just ignored. The command line gives: invalid child property id 2 for “top-attach” of type ‘GParamInt’ in ‘GtkGrid’ You can also reply me via email. Thanks
https://blogs.gnome.org/alexl/2016/04/29/using-bubblewrap-in-xdg-app/
CC-MAIN-2017-34
refinedweb
478
66.67
Launching tail-f from the command line. Is it possible to launch the “Monitor (tail-f)” when opening notepad++ ? I’m trying to automate this when opening notepad++. No, the possible commandline parameters do not include it. One could, depending on how complicated stuff goes, use one of the scripting plugins like PythonScript(PS) or NppExec to try to solve it. For example, PS has notepad.getCommandLine method if you would start npp with something like notepad++.exe -multiInst -?you can check for the question mark and call notepad.runMenuCommand('View', 'Monitoring (tail -f)')if needed. To use a scripting plugin like Pythonscript like @Ekopalypse suggests, you’d have to put the code to do this in its “startup” script. I suppose you’d also have to have some mechanism to tell it which file you wanted to put in “tail” mode, as the typical remembered session contains more than one file, and you probably wouldn’t want to put ALL files in “tail” mode. put the code to do this in its “startup” script. preferable a “user” startup.py and in addition one needs to change the PS configuration from LAZY to ATSTARTUP. Probably @Ekopalypse will come up with a nice, short, fully working example for the OP. :-) If OP wants to go that way - maybe. ;-D It would serve as a good example of “adding a custom command line parameter to Notepad++” for future readers as well, who might have different need than “tail”. the issue is, that you cannot set a custom parameter but the question mark seems to work. But I haven’t really checked the commandline code to see if there is a possible workaround. you cannot set a custom parameter but the question mark seems to work. Ah. Presuming it worked more fully, more questions arise: I have a Explorer right-click “edit with N++” thing that I often use to pull into an existing N++ instance already running. If one queried the command line after that, would they see the original command line, or the one from the right-click? Does a multiple instance invoked from the first instance impact? you query the current instance, so you should always get the commandline parameters associated whit this instance, regardless if multiInst is used or not. But I mean, to follow the OP’s example, maybe I have N++ running then I next want to run tail on a file, so I use Explorer with my special “tail with Notepad++” rightclick. I guess there would be no good way to do the trapping with P.S., even if Notepad++ interface to get the command line was better than it is. maybe I’m, again, not seeing the wood because of the trees. Let me try to explain what I understand so far. There is an running (or not as it doesn’t matter from my understanding) npp instance. Now you click on the explorer context menu “open with npp in tail mode”. This shortcut must be configured, of course, with something like npp -multiInst -? If that new instance starts up it will execute startup.py And here we would check against the -? flag and act accordingly. Is that what you are talking about or do I have a plank at my head? I was wrong, there is a way to provide user parameters. By this we could start npp with something like notepad++.exe -multiInst -nosession -z -tailmode and would be able to get it up and running This PS, saved as startup.py (user NOT machine and PS configuration changed from LAZY to ATSTARTUP) should do the trick from Npp import notepad, MENUCOMMAND if '-tailmode' in notepad.getCommandLine(): notepad.menuCommand(MENUCOMMAND.VIEW_MONITORING) and npp like this notepad++.exe -multiInst -nosession "FULL_PATH_OF_THE_FILE" -z -tailmode
https://community.notepad-plus-plus.org/topic/19247/launching-tail-f-from-the-command-line
CC-MAIN-2021-43
refinedweb
629
73.88
14 Feb 2008 18:52 Re: Bug with dotimes() and make-thread() Kevin Reid <kpreid <at> mac.com> 2008-02-14 17:52:48 GMT 2008-02-14 17:52:48 GMT On Feb 14, 2008, at 12:30, obregonmateo <at> gmail.com wrote: > However, I've found a BUG that shows up in the following code. > Sometimes this snippet generates an erroneous result: > > ;; first run: > > CL-USER> (let ((res nil)) > (dotimes (n 3) > (push (sb-thread:make-thread #'(lambda () (cons n n))) res)) > (mapcar #'sb-thread:join-thread (reverse res))) > > ((0 . 0) (2 . 2) (3 . 3)) ... > ((0 . 0) (1 . 1) (2 . 2)) ... > ((0 . 0) (1 . 1) (3 . 3)) This is not a bug, but permitted behavior of DOTIMES. According to the CLHS: "It is implementation-dependent whether dotimes establishes a new binding of var on each iteration or whether it establishes a binding for var once at the beginning and then assigns it on any subsequent iterations." SBCL currently does the latter. Therefore, your three lambdas close over the same binding, which is the one being mutated by DOTIMES. The variation you are seeing comes from the OS scheduler: whether the thread retrieves n before or after DOTIMES proceeds to its next iteration. You can also see this type of behavior without threads: (let ((res nil)) (dotimes (n 3) (push (lambda () (cons n n)) res)) (mapcar #'funcall (reverse res))) This will always return ((3 . 3) (3 . 3) (3 . 3)). One way to do this correctly is: (dotimes (n 3) (let ((n n)) (push (sb-thread:make-thread #'(lambda () (cons n n)))) This establishes a new, never-reassigned, binding for each closure. -- -- Kevin Reid <> ------------------------------------------------------------------------- This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008.
http://permalink.gmane.org/gmane.lisp.steel-bank.general/1927
CC-MAIN-2013-20
refinedweb
290
69.41
class that contains an abstract Area property. shapes.cs: The subclasses of the Shape class. shapetest.cs: A test program to display the areas of some Shape-derived objects. To compile the example, use the following command: csc abstractshape.cs shapes.cs shapetest.cs This will create the executable file shapetest.exe. This file declares the Shape class that contains the Area property of the type double. // compile with: csc /target:library abstractshape.cs public abstract class Shape { private string name; public Shape(string s) { // calling the set accessor of the Id property. Id = s; } public string Id { get { return name; } set { name = Area side; public Square(int side, string id) : base(id) { this.side = side; } public override double Area { get { // Given the side, return the area of a square: return side * side; } } } public class Circle : Shape { private int radius; public Circle(int radius, string id) : base(id) { this.radius = radius; } public override double Area { get { // Given the radius, return the area of a circle: return radius * radius * System.Math.PI; } } } public class Rectangle : Shape { private int width; private int height; public Rectangle(int width, int height, string id) : base(id) { this.width = width; this.height = height; } public override double Area { get { // Given the width and height, return the area of a rectangle: return width *); } } } /* Output: Shapes Collection Square #1 Area = 25.00 Circle #1 Area = 28.27 Rectangle #1 Area = 20.00 */
http://msdn.microsoft.com/en-us/library/yd3z1377(v=vs.90).aspx
CC-MAIN-2014-52
refinedweb
233
66.74
NAME vflush - flush vnodes for a mount point SYNOPSIS #include <sys/param.h> #include <sys/vnode.h> int vflush(struct mount *mp, int rootrefs, int flags, struct thread *td); DESCRIPTION The vflush() function removes any vnodes in the vnode table that belong to the given mount structure. Its arguments are: mp The mount point whose vnodes should be removed. rootrefs The number of references expected on the root vnode. vrele(9) will be invoked on the root vnode rootrefs times. flags The flags indicating how vnodes should be handled. FORCECLOSE If set, busy vnodes will be forcibly closed. SKIPSYSTEM If set, vnodes with the VV_SYSTEM flag set will be skipped. WRITECLOSE If set, only regular files currently opened for writing will be removed. td The calling thread. RETURN VALUES A value of 0 is returned if the flush is successful; otherwise, EBUSY will be returned. SEE ALSO vgone(9), vgonel(9), vrele(9) AUTHORS This manual page was written by Chad David 〈davidc@acns.ab.ca〉.
http://manpages.ubuntu.com/manpages/intrepid/man9/vflush.9freebsd.html
CC-MAIN-2014-49
refinedweb
166
67.96
Save Hi @kisaf, while is not the recommended way since we could not guarantee the safeness of this method, you could use a global variable. This variable will be available across multiple frames but only to the current python scope (if you define a variable in a Python Generator, you can't get it from a Python Tag). Here a short example from a Python Scripting Tag import c4d global previousCount def main(): global previousCount if 'previousCount' not in globals(): previousCount = 0 previousCount += 1 print previousCount Besides that, you are free to use any kind of datatype/structure python or the Cinema 4D API provides. BaseContainer from the Cinema 4D API can be well suited since you can store it in multiple levels such as Object/tag or even document. All of them inherit from BaseList2D which provide the GetData/SetData which let you access the BaseContainer where you can store your BaseContainer holding your data as long as you use a unique ID from. If you have any questions please let me know and do not hesitate, especially if you decide to go to the second way, which may sound a bit more complicated. Cheers, Maxime. In addition to @m_adam's answer, you can use GetWorldPluginData() to save variables. Those even do exist after restarting Cinema 4D. You can clear them on application exit. Hi @mp5gosu, thanks for the addition, in this case c4d.GetWorldContainer is more suited since it's not about a plugin but a script. But in all cases you are right, data stored are persistent and it's not recommended to store any kind of caching data in these containers. It takes some memory and this can become very problematic if the developer forgets to free the container at the application exit. Moreover, you can easily screw up, user preference with that, so, be careful when dealing with these methods. Cheers, Maxime. Since the OP has asked explicitly for scripts, I would like to add: @m_adam 's "Global" method will not work for scripts, as their Python scope is (apparently) only valid for the current execution. It does work for Python tags and XPresso Python nodes where the scope seems to exist for the lifetime of the tag. If you work with tags/nodes and have actual variables to store in the globals, you need to account for the timing and the frequency of execution (e.g. do not rely that the next execution is actually the next frame). This will not apply for one-time executions like an initialization, but even there you may want to determine an anchor point (e.g. at frame 0) where the value is reset or calculated for the first time. Thanks a lot @Cairyn I overlooked this part and you are right, from the Script Manager my solution does not work, only for embedded BaseList2D such as Python Tag, Python Generator and so on. So the only reliable way is to store data in a BaseContainer, or any "generic way" e.g. files. Cheers, Maxime. Thank you very much guys! I think that plugin will be better solution then script in this case. Cheers
https://plugincafe.maxon.net/topic/11327/save-variables-during-current-session-until-c4d-is-closed
CC-MAIN-2019-18
refinedweb
526
66.67
Search: Search took 0.01 seconds. New Ext JS 5 "reference" namespace pollution versus itemid Controller setter methods are not being createdStarted by CSchmitz81, 22 Jun 2014 8:08 PM - Last Post By: - Last Post: 26 Jun 2014 11:45 AM - by CSchmitz81 accessing refs from application event handlerStarted by EXTraordinary, 21 Feb 2014 6:12 AM - Last Post By: - Last Post: 21 Feb 2014 8:41 AM - by EXTraordinary Getter method for refs not available Controllers referencing other controllers! Controller - control - naming :: Logic problem - Last Post By: - Last Post: 14 Oct 2013 1:19 PM - by mitchellsimoens - simple display ref - Last Post By: - Last Post: 5 Jul 2013 12:17 PM - by Phil.Strong Element is not destroyed completely when suspendEvents() has been called before Dynamic refs in ControllerStarted by novadys-sbu, 26 Apr 2013 6:47 AM - Last Post By: - Last Post: 29 Apr 2013 5:18 AM - by mitchellsimoens How to use refs from a controller in Architect and Touch 2.1Started by karimgarza, 9 Jan 2013 5:24 AM - Last Post By: - Last Post: 9 Jan 2013 7:50 AM - by karimgarza different behavior between sencha-touch-debug.js and sencha-touch-all-debug.jsStarted by leandroafonso, 29 Nov 2012 5:06 AM - Last Post By: - Last Post: 29 Nov 2012 10:20 AM - by mitchellsimoens Touch Navigation View - Uncaught ReferenceError: getNavig is not defined - Last Post By: - Last Post: 9 Nov 2012 1:42 PM - by mitchellsimoens Ext JS 4.1 Controller Refs Selector with CSS Class how to do a complex query in the refs property of a controller? The getter of Controller is fail! How to reference store and define control callback in controller? Controller refs help - Last Post By: - Last Post: 19 Apr 2012 11:45 AM - by mitchellsimoens How do I refresh the refs in my controller when their target is recreated? Control problem Update Label content Way to add a button to a Ext.TemplateStarted by jonathansimmons, 26 Mar 2012 7:01 PM - Last Post By: - Last Post: 26 Mar 2012 7:21 PM - by jonathansimmons Results 1 to 25 of 29
http://www.sencha.com/forum/tags.php?tag=refs
CC-MAIN-2014-35
refinedweb
352
63.22
C library function - fprintf() Description The C library function int fprintf(FILE *stream, const char *format, ...) sends formatted output to a stream. Declaration Following is the declaration for fprintf() function. int fprintf(FILE *stream, const char *format, ...) Parameters stream − This is the pointer to a FILE object that identifies the stream. format − This is the C string that contains the text to be written to the stream. otherwise, a negative number is returned. Example The following example shows the usage of fprintf() function. #include <stdio.h> #include <stdlib.h> int main() { FILE * fp; fp = fopen ("file.txt", "w+"); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012); fclose(fp); return(0); } Let us compile and run the above program that will create a file file.txt with the following content − We are in 2012 Now let's see the content of the above file using the following program − #include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break; } printf("%c", c); } fclose(fp); return(0); } Let us compile and run above program to produce the following result. We are in 2012
http://www.tutorialspoint.com/c_standard_library/c_function_fprintf.htm
CC-MAIN-2016-26
refinedweb
195
76.52
wind_kindMembers Posts11 Joined Last visited Profile Information - GenderNot Telling wind_kind's Achievements 0 Reputation Bound draggable at top only wind_kind replied to wind_kind's topic in GSAPBrilliant. Thanks. Bound draggable at top only wind_kind posted a topic in GSAPI've tried a couple of things now but I need help with this please. I have a draggable block that I want to restrict from going past the top of the screen but should be able to drag past the bottom fully. If you view the pen I did, you will see an arrow/tab at the bottom. Ideally this tab will be halfway visible at the bottom and when the block is dragged all the way up the bottom half should be visible plus 5px of the grey background. So when dragging the red block to the top it should stop 5px before so I don't see the grey peeking out at the bottom. So far I can drag it all the way and then I did some checks to just get the red block in place but I have to get those bounds right. Like I said, I tried using hitTest and some of my own logic and checking the element Y position etc but my knowledge with this is limited. - ah brilliant. It works great and I learned about the yPercent. This is such a great tool. Thanks. - Thanks for the reply OSUblake. Your example is close to what I am looking to do and playing around with the min max gets me close but I don't want to be able to drag toward the bottom at all and when dragging up the bottom of the nav should never move past the bottom of the screen. No matter how I change it, I can always drag the nav up a lot. Restrict draggable element wind_kind posted a topic in GSAPI have the basics figured out from following the brilliant docs, thanks for that. I am stuck however. I would like the nav in my example to be draggable only to the top and only by about 45 pixels. When it reaches 45px you shouldn't be able to drag it any further and then on release obviously it tweens back to where it started (but that I have working already). It would be cool if I can have the edgeResistance kick in as well close to the end of the drag but it's not required. It should be easy but I can't get my head around how I will achieve this. scaling to stage width wind_kind posted a topic in TransformManager (Flash)Hi I have another couple of question about scaling. I have the box I'm scaling in a content sprite that scales itself as the movie dimensions change along with the browser window size. Question 1. How do I scale the box to the stage width and when stage resizes the box resize with it, I thought it should do that anyway because it is inside a container that resizes the rest of the content but it just sticks to its set width. Question2. This doesn't really have to do with tweenmax but hopefully someone can help anyway. I have an if statement that checks to see if any instance of one of the boxes are already loaded on the stage and if so tween it of stage and remove the child from the parent it was attached to. So obviously the statement doesn't work (I know how if statements work, sort of but I don't really know how what commands to use to get the desired result) Just trying my luck her if somone can help. If not the first question would be great if someone could help. Thanx in advance package { import flash.display.SpreadMethod; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.ContextMenuEvent; import flash.events.Event; import flash.events.MouseEvent; import flash.filters.BlurFilter; import flash.filters.GlowFilter; import flash.net.URLLoader; import flash.ui.Mouse; import gs.TweenMax; public class main extends Sprite { //public static var origW:Number = 1024 //original stage width //public static var origH:Number = 768 //original stage height //public static var //graphic resources private var bg:Sprite = new Sprite; private var cont:Sprite = new Sprite; private var art:Sprite = new Sprite; private var photo:Sprite = new Sprite; private var project:Sprite = new Sprite; var box:Sprite = new Sprite; var box1:Sprite = new Sprite; var box2:Sprite = new Sprite; //get the new stage height var sw:Number = stage.stageWidth; var sh:Number = stage.stageHeight; //constructor public function main () { //Tel the player not to scale the assets stage.scaleMode = StageScaleMode.NO_SCALE; //Tell the player to put co-ords 0,0 to the top left corner stage.align = StageAlign.TOP_LEFT; //Listen for resize events stage.addEventListener(Event.RESIZE, onResize); //Create and add body resource to the display list bg = new bg_mc(); addChild(bg); cont = new content(); addChild(cont); art = new art_mc(); cont.addChild(art); art.x = 94.2; art.y = 512.5; photo = new photo_mc(); cont.addChild(photo); photo.x = 136.1; photo.y = 517.9; project = new project_mc(); cont.addChild(project); project.x = 150; project.y = 535; //Size everything after creation to insure the app is drawn //properly the first time it is seen prior to any user initiated //resizing onResize(null); art.addEventListener(MouseEvent.CLICK, ClickListener) photo.addEventListener(MouseEvent.CLICK, ClickListener1) project.addEventListener(MouseEvent.CLICK, ClickListener2) //set button properties art.buttonMode = true; art.useHandCursor = true; photo.buttonMode = true; photo.useHandCursor = true; project.buttonMode = true; project.useHandCursor = true; //check ClickListener function ClickListener(event:MouseEvent):void { art.mouseEnabled = false; photo.mouseEnabled = true; project.mouseEnabled = true; trace("button clicked:" + event.currentTarget); if (Boolean(cont.getChildByName('box1'))) { TweenMax.to(box1, 0.2, { x:500 } ); cont.removeChild(box); } if (Boolean(cont.getChildByName('box2'))){ TweenMax.to(box2, 0.2, { x:500 } ); cont.removeChild(box); } box.graphics.lineStyle(2, 0xffffff, 0.5, false, "none"); box.graphics.beginFill(0x000000, 0.5); box.graphics.drawRect(0, 0, 10, 10); box.graphics.endFill(); cont.addChild(box); TweenMax.multiSequence ([ { target:box, time:0.2, y:625 }, { target:box, time:0.5, scaleY:12 }, { target:box, time:1, x:35, scaleX:95 } ]); } function ClickListener1(event:MouseEvent):void { art.mouseEnabled = true; photo.mouseEnabled = false; project.mouseEnabled = true; trace("button clicked:" + event.currentTarget); if (Boolean(cont.getChildByName('box'))) { TweenMax.to(box, 0.2, { x:500 } ); cont.removeChild(box); } else{ if (Boolean(cont.getChildByName('box2'))){ TweenMax.to(box2, 0.2, { x:500 } ); cont.removeChild(box2); } } box1.graphics.lineStyle(2, 0xffffff, 0.5, false, "none"); box1.graphics.beginFill(0x000000, 0.5); box1.graphics.drawRect(0, 0, 10, 10); box1.graphics.endFill(); cont.addChild(box1); TweenMax.multiSequence ([ { target:box1, time:0.2, y:625 }, { target:box1, time:0.5, scaleY:12 }, { target:box1, time:1, x:35, scaleX:95 } ]); } function ClickListener2(event:MouseEvent):void { art.mouseEnabled = true; photo.mouseEnabled = true; project.mouseEnabled = false; trace("button clicked:" + event.currentTarget); if (Boolean(cont.getChildByName('box'))) { TweenMax.to(box, 0.2, { x:500 } ); cont.removeChild(box); } else{ if (Boolean(cont.getChildByName('box1'))){ TweenMax.to(box1, 0.2, { x:500 } ); cont.removeChild(box1); } } box2.graphics.lineStyle(2, 0xffffff, 0.5, false, "none"); box2.graphics.beginFill(0x000000, 0.5); box2.graphics.drawRect(0, 0, 10, 10); box2.graphics.endFill(); cont.addChild(box2); TweenMax.multiSequence ([ { target:box2, time:0.2, y:625 }, { target:box2, time:0.5, scaleY:12 }, { target:box2, time:1, x:35, scaleX:95 } ]); } } //listening for stage resize public function onResize(event:Event):void { sh = stage.stageHeight; sw = stage.stageWidth; //then update the children with this new size bg.height = sh; bg.width = sw; cont.height = sh; cont.width = sw; } } } - sorry but I have another one for you. When I draw the box and I use this: box.graphics.lineStyle(1); to get a border, then when I scale the box the border or line scales in width and height as well. Is there a different way of doing it? function ClickListener(event:MouseEvent):void { trace("button clicked:" + event.currentTarget); var box:Sprite = new Sprite(); art.useHandCursor = true; box.graphics.beginFill(0x000000, 0.8); box.graphics.drawRect(0, 0, 10, 10); box.graphics.endFill(); cont.addChild(box); TweenMax.multiSequence ([ { target:box, time:0.2, y:625 }, { target:box, time:0.5, scaleY:12 }, { target:box, time:1, x:35, scaleX:95 } ]); } I'm going to bed now so I won't bother anybody after this one. thanx - awesome!! Thanx a mill. Great job with TweenMax, it's so easy to understand once you get use to it and a little help into the right direction, (I'm very new to all this, as you can probably tell by now). thanx again - that seems to work but I have another question. Can I do the tweens sequentially and how is this done? - thanx I'll give it go. scaling hairloss [SOLVED] wind_kind posted a topic in TransformManager (Flash)Hi Can anybody please tell me what I am doing wrong cause I'm missing something really easy and stupid here. my sprite doesn't scale like I want it, instead it just tweens to some position off of the stage. I want to do this if it is possible at all.(uploaded swf) this is my code art.addEventListener(MouseEvent.CLICK, ClickListener) photo.addEventListener(MouseEvent.CLICK, ClickListener) project.addEventListener(MouseEvent.CLICK, ClickListener) function ClickListener(event:MouseEvent):void { trace("art button clicked") var box:Sprite = new Sprite(); box.graphics.beginFill(0xffffff, 1); box.graphics.drawRect(10, 600, 10, 10); box.graphics.endFill(); cont.addChild(box); TweenMax.to(box, 1, {scaleY:3}); } Thanx for any help
https://greensock.com/profile/79-wind_kind/
CC-MAIN-2021-49
refinedweb
1,597
61.43
Flash CS5.5 Compiler Errorsjafproductions Jun 2, 2011 12:22 PM Just upgraded from CS5 to CS5.5 Code that worked in CS5 now gives compiler errors: Symbol 'VideoPlayerMC', Layer 'Layer 2', Frame 1, Line 21 1119: Access of possibly undefined property state through a reference with static type flash.events:VideoEvent. Symbol 'VideoPlayerMC', Layer 'Layer 2', Frame 1, Line 42 1119: Access of possibly undefined property PLAYHEAD_UPDATE through a reference with static type Class. etc.... Problem only seems to happen if I publish to Flash Player 10.2 or to Air for IOS 1. Re: Flash CS5.5 Compiler Errorsjafproductions Jun 3, 2011 8:06 AM (in response to jafproductions) It appears that the VideoEvent class is no longer supported in Air 2.5 or Flash Player 10.2 We have to use a new class called StageVideo. If anyone finds some sample code to use StageVideo please post here. - 3. Re: Flash CS5.5 Compiler Errorskglad Jun 5, 2011 11:11 AM (in response to jafproductions) stagevideo is a class used to allow hardware acceleration of video. but it has particular restrictions (like it's not in the display list and will appear below everything in the display list). the older video classes have not been removed. and, in particular, stagevideo is not a substitute for a previous video class. the videoevent class has been changed. if you don't need to use stagevideo or any of the 10.2 updates, publish for fp10 so you can use your code. 4. Re: Flash CS5.5 Compiler Errorsjafproductions Jun 6, 2011 7:23 AM (in response to jafproductions) My original question has not been resolved. the CS5.5 gives compiler errors when I use VideoEvent class Here is some code to test: import fl.video.*; import fl.video.VideoEvent; video1.addEventListener(VideoEvent.STATE_CHANGE, HandleStateChange); function HandleStateChange(e:VideoEvent):void { if (VideoState.CONNECTION_ERROR == e.state) trace(e.state); if (e.state=="seeking") trace(e.state); } 5. Re: Flash CS5.5 Compiler Errorsrelaxatraja Jun 7, 2011 2:19 AM (in response to jafproductions) Get the video flv component from the components panel and drag it on the stage and delete it. Then publish it once. 6. Re: Flash CS5.5 Compiler Errorsgritty_d May 8, 2012 3:34 AM (in response to relaxatraja) An older thread but if you want to solve this and not really need Player 10.2 - just publish back on Flash player 9 and it will work again 7. Re: Flash CS5.5 Compiler Errors_hadi May 10, 2012 3:22 AM (in response to jafproductions) this bug will be solved if you type the original string value of the actual event instead of the original from ex: - FlvPlayBack.addEventListener(VideoEvent.PLAYHEAD_UPDATE , updateProgress); becomes - FlvPlayBack.addEventListener('playheadUpdate' , updateProgress) 8. Re: Flash CS5.5 Compiler ErrorsDanelKirch Jul 31, 2012 3:00 AM (in response to _hadi) one could also use following ( works in FP 11.2 and probably in air2.5+ ): flvPlayback.addEventListener( fl.video.VideoEvent.PLAYHEAD_UPDATE, videoEventHandler, false, 0, true); function videoEventHandler( v:fl.video.VideoEvent ):void { switch ( v.type ) { case fl.video.VideoEvent.PLAYHEAD_UPDATE: trace ( v.playheadTime ); break; } } Its probably conflicting with flash.events.VideoEvent. Code formating
https://forums.adobe.com/message/4393495
CC-MAIN-2015-32
refinedweb
529
60.01
import "github.com/cockroachdb/cockroach/pkg/util/interval" Package interval provides two implementations for an interval tree. One is based on an augmented Left-Leaning Red Black tree. The other is based on an augmented BTree. btree_based_interval.go bu23.go interval.go llrb_based_interval.go range_group.go const ( // DefaultBTreeMinimumDegree is the default B-tree minimum degree. Benchmarks // show that the interval tree performs best with this minimum degree. DefaultBTreeMinimumDegree = 32 // DefaultBTreeFreeListSize is the default size of a B-tree's freelist. DefaultBTreeFreeListSize = 32 ) Operation LLRBMode of the underlying LLRB tree. LLRBMode . ErrEmptyRange is returned if an interval is used where the start value is equal to the end value. ErrInvertedRange is returned if an interval is used where the start value is greater than the end value. ErrNilRange is returned if an interval is used where both the start value and the end value are nil. This is a specialization of ErrEmptyRange. ExclusiveOverlapper defines overlapping as a pair of ranges that share a segment of the keyspace in the exclusive. "exclusive" means that the start keys are treated as inclusive and the end keys are treated as exclusive. InclusiveOverlapper defines overlapping as a pair of ranges that share a segment of the keyspace in the inclusive way. "inclusive" means that both start and end keys treated as inclusive values. Compare returns a value indicating the sort order relationship between a and b. The comparison is performed lexicographically on (a.Range().Start, a.ID()) and (b.Range().Start, b.ID()) tuples where Range().Start is more significant that ID(). Given c = Compare(a, b): c == -1 if (a.Range().Start, a.ID()) < (b.Range().Start, b.ID()); c == 0 if (a.Range().Start, a.ID()) == (b.Range().Start, b.ID()); and c == 1 if (a.Range().Start, a.ID()) > (b.Range().Start, b.ID()). "c == 0" is equivalent to "Equal(a, b) == true". Equal returns a boolean indicating whether the given Interfaces are equal to each other. If "Equal(a, b) == true", "a.Range().End == b.Range().End" must hold. Otherwise, the interval tree behavior is undefined. "Equal(a, b) == true" is equivalent to "Compare(a, b) == 0". But the former has measurably better performance than the latter. So Equal should be used when only equality state is needed. func RangeGroupsOverlap(rg1, rg2 RangeGroup) bool RangeGroupsOverlap determines if two RangeGroups contain any overlapping Ranges or if they are fully disjoint. It does so by iterating over the RangeGroups together and comparing subsequent ranges. A Comparable is a type that describes the ends of a Range. func (c Comparable) Compare(o Comparable) int Compare returns a value indicating the sort order relationship between the receiver and the parameter. Given c = a.Compare(b): c == -1 if a < b; c == 0 if a == b; and c == 1 if a > b. func (c Comparable) Equal(o Comparable) bool Equal returns a boolean indicating if the given comparables are equal to each other. Note that this has measurably better performance than Compare() == 0, so it should be used when only equality state is needed.. type Interface interface { Range() Range // Returns a unique ID for the element. // TODO(nvanbenschoten): Should this be changed to an int64? ID() uintptr } An Interface is a type that can be inserted into an interval tree. An Operation is a function that operates on an Interface. If done is returned true, the Operation is indicating that no further work needs to be done and so the DoMatching function should traverse no further. type Overlapper interface { // Overlap checks whether two ranges overlap. Overlap(Range, Range) bool } Overlapper specifies the overlapping relationship. type Range struct { Start, End Comparable } A Range is a type that describes the basic characteristics of an interval. Equal returns whether the two ranges are equal. String implements the Stringer interface. type RangeGroup interface { // Add will attempt to add the provided Range to the RangeGroup, // returning whether the addition increased the range of the group // or not. Add(Range) bool // Sub will attempt to remove the provided Range from the RangeGroup, // returning whether the subtraction reduced the range of the group // or not. Sub(Range) bool // Clear clears all ranges from the RangeGroup, resetting it to be // used again. Clear() // Overlaps returns whether the provided Range is partially contained // within the group of Ranges in the RangeGroup. Overlaps(Range) bool // Encloses returns whether the provided Range is fully contained // within the group of Ranges in the RangeGroup. Encloses(Range) bool // ForEach calls the provided function with each Range stored in // the group. An error is returned indicating whether the callback // function saw an error, whereupon the Range iteration will halt // (potentially prematurely) and the error will be returned from ForEach // itself. If no error is returned from the callback, the method // will visit all Ranges in the group before returning a nil error. ForEach(func(Range) error) error // Iterator returns an iterator to visit each Range stored in the // group, in-order. It is not safe to mutate the RangeGroup while // iteration is being performed. Iterator() RangeGroupIterator // Len returns the number of Ranges currently within the RangeGroup. // This will always be equal to or less than the number of ranges added, // as ranges that overlap will merge to produce a single larger range. Len() int fmt.Stringer } RangeGroup represents a set of possibly disjointed Ranges. The interface exposes methods to manipulate the group by adding and subtracting Ranges. All methods requiring a Range will panic if the provided range is inverted or empty. One use case of the interface is to add ranges to the group and observe whether the addition increases the size of the group or not, indicating whether the new range's interval is redundant, or if it is needed for the full composition of the group. Because the RangeGroup builds as more ranges are added, insertion order of the ranges is critical. For instance, if two identical ranges are added, only the first to be added with Add will return true, as it will be the only one to expand the group. Another use case of the interface is to add and subtract ranges as needed to the group, allowing the internals of the implementation to coalesce and split ranges when needed to factor the group to its minimum number of disjoint ranges. func NewRangeList() RangeGroup NewRangeList constructs a linked-list backed RangeGroup. func NewRangeTree() RangeGroup NewRangeTree constructs an interval tree backed RangeGroup. type RangeGroupIterator interface { // Next returns the next Range in the RangeGroup. It returns false // if there are no more Ranges. Next() (Range, bool) } RangeGroupIterator is an iterator that walks in-order over a RangeGroup. type Tree interface { // AdjustRanges fixes range fields for all nodes in the tree. This must be // called before Get, Do or DoMatching* is used if fast insertion or deletion // has been performed. AdjustRanges() // Len returns the number of intervals stored in the Tree. Len() int // Get returns a slice of Interfaces that overlap r in the tree. The slice is // sorted nondecreasingly by interval start. Get(r Range) []Interface // GetWithOverlapper returns a slice of Interfaces that overlap r in the tree // using the provided overlapper function. The slice is sorted nondecreasingly // by interval start. GetWithOverlapper(r Range, overlapper Overlapper) []Interface // Insert inserts the Interface e into the tree. Insertions may replace an // existing Interface which is equal to the Interface e. Insert(e Interface, fast bool) error // Delete deletes the Interface e if it exists in the tree. The deleted // Interface is equal to the Interface e. Delete(e Interface, fast bool) error // Do performs fn on all intervals stored in the tree. The traversal is done // in the nondecreasing order of interval start. A boolean is returned // indicating whether the traversal was interrupted by an Operation returning // true. If fn alters stored intervals' sort relationships, future tree // operation behaviors are undefined. Do(fn Operation) bool // DoMatching performs fn on all intervals stored in the tree that overlaps r. // The traversal is done in the nondecreasing order of interval start. A // boolean is returned indicating whether the traversal was interrupted by an // Operation returning true. If fn alters stored intervals' sort // relationships, future tree operation behaviors are undefined. DoMatching(fn Operation, r Range) bool // Iterator creates an iterator to iterate over all intervals stored in the // tree, in-order. Iterator() TreeIterator // Clear this tree. Clear() // Clone clones the tree, returning a copy. Clone() Tree } Tree is an interval tree. For all the functions which have a fast argment, fast being true means a fast operation which does not adjust node ranges. If fast is false, node ranges are adjusted. func NewTree(overlapper Overlapper) Tree NewTree creates a new interval tree with the given overlapper function. It uses the augmented Left-Leaning Red Black tree implementation. type TreeIterator interface { // Next returns the current interval stored in the interval tree and moves // the iterator to the next interval. The method returns false if no intervals // remain in the interval tree. Next() (Interface, bool) } TreeIterator iterates over all intervals stored in the interval tree, in-order. Package interval imports 9 packages (graph) and is imported by 44 packages. Updated 2019-07-26. Refresh now. Tools for package owners.
https://godoc.org/github.com/cockroachdb/cockroach/pkg/util/interval
CC-MAIN-2019-47
refinedweb
1,525
57.67
Arrow Functions parameter do not require ()around the parameter list. - Arrow functions with a single expression can use the concise function body which returns the result of the expression without the returnkeyword. provided contains a function that takes in 2 values and returns the sum of those numbers. Anonymous Functions Anonymous functions in JavaScript do not have a name property. They can be defined using the function keyword, or as an arrow function. See the code example for the difference between a named function and an anonymous function. Function Expressions Function expressions create functions inside an expression instead of as a function declaration. They can be anonymous and/or assigned to a variable. Function Parameters Inputs to functions are known as parameters when a function is declared or defined. Parameters are used as variables inside the function body. When the function is called, these parameters will have the value of whatever is passed in as arguments. It is possible to define a function without parameters. return Keyword Functions return (pass back) values using the return keyword. return ends function execution and returns the specified value to the location where it was called. A common mistake is to forget the return keyword, in which case the function will return undefined by default. Function Declaration Function declarations are used to create named functions. These functions can be called using their declared name. Function declarations are built from: - The functionkeyword. - The function name. - An optional list of parameters separated by commas enclosed by a set of parentheses (). - A function body enclosed in a set of curly braces {}. Calling Functions Functions can be called, or executed, elsewhere in code using parentheses following the function name. When a function is called, the code inside its function body runs. Arguments are values passed into a function when it is called.
https://production.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-functions/cheatsheet
CC-MAIN-2020-29
refinedweb
304
58.69
Your Account Hear us Roar Earlier today I received a couple of emails that pointed out an error I had in my code. In the CronJob class I have two initialize methods and Ruby does not allow methods to be overloaded. If you want to fix the error, replace the two initialize methods with the code below: def initialize(minute="*", hour="*", day="*", month="*", weekday="*", command="*") @minute = minute @hour = hour @day = day @month = month @weekday = weekday @command = command end © 2013, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.oreillynet.com/cs/user/view/cs_msg/42162
CC-MAIN-2013-48
refinedweb
105
59.64
A Makefile for your Go project Vincent Bernat My most loathed feature of Go was the mandatory use of GOPATH: I do not want to put my own code next to its dependencies. I was not alone and people devised tools or crafted their own Makefile to avoid organizing their code around GOPATH. Hopefully, since Go 1.11, it is possible to use Go’s modules to manage dependencies without relying on GOPATH. First, you need to convert your project to a module:1 $ go mod init hellogopher go: creating new go.mod: module hellogopher $ cat go.mod module hellogopher Then, you can invoke the usual commands, like go build or go test. The go command resolves imports by using versions listed in go.mod. When it runs into an import of a package not present in go.mod, it automatically looks up the module containing that package using the latest version and adds it. $ go test ./... go: finding github.com/spf13/cobra v0.0.5 go: downloading github.com/spf13/cobra v0.0.5 ? hellogopher [no test files] ? hellogopher/cmd [no test files] ok hellogopher/hello 0.001s $ cat go.mod module hellogopher require github.com/spf13/cobra v0.0.5 If you want a specific version, you can either edit go.mod or invoke go get: $ go get github.com/spf13/cobra@v0.0.4 go: finding github.com/spf13/cobra v0.0.4 go: downloading github.com/spf13/cobra v0.0.4 $ cat go.mod module hellogopher require github.com/spf13/cobra v0.0.4 Add go.mod to your version control system. Optionally,2 you can also add go.sum as a safety net against overridden tags. If you really want to vendor the dependencies, you can invoke go mod vendor and add the vendor/ directory to your version control system. Thanks to the modules, in my opinion, Go’s dependency management is now on a par with other languages, like Ruby. While it is possible to run day-to-day operations—building and testing—with only the go command, a Makefile can still be useful to organize common tasks, a bit like Python’s setup.py or Ruby’s Rakefile. Let me describe mine. Using third-party tools# Most projects need some third-party tools for testing or building. We can either expect them to be already installed or compile them on the fly. For example, here is how code linting is done with Golint: BIN = $(CURDIR)/bin $(BIN): @mkdir -p $@ $(BIN)/%: | $(BIN) @tmp=$$(mktemp -d); \ env GO111MODULE=off GOPATH=$$tmp GOBIN=$(BIN) go get $(PACKAGE) \ || ret=$$?; \ rm -rf $$tmp ; exit $$ret $(BIN)/golint: PACKAGE=golang.org/x/lint/golint GOLINT = $(BIN)/golint lint: | $(GOLINT) $(GOLINT) -set_exit_status ./... The first block defines how a third-party tool is built: go get is invoked with the package name matching the tool we want to install. We do not want to pollute our dependency management and therefore, we are working in an empty GOPATH. The generated binaries are put in bin/. The second block extends the pattern rule defined in the first block by providing the package name for golint. Additional tools can be added by just adding another line like this. The last block defines the recipe to lint the code. The default linting tool is the golint built using the first block but it can be overridden with make GOLINT=/usr/bin/golint. Tests# Here are some rules to help running tests: TIMEOUT = 20 PKGS = $(or $(PKG),$(shell env GO111MODULE=on $(GO) list ./...)) TESTPKGS = $(shell env GO111MODULE=on $(GO) list -f \ '{{ if or .TestGoFiles .XTestGoFiles }}{{ .ImportPath }}{{ end }}' \ $(PKGS)) TEST_TARGETS := test-default test-bench test-short test-verbose test-race test-bench: ARGS=-run=__absolutelynothing__ -bench=. test-short: ARGS=-short test-verbose: ARGS=-v test-race: ARGS=-race $(TEST_TARGETS): test check test tests: fmt lint go test -timeout $(TIMEOUT)s $(ARGS) $(TESTPKG need some additional tools. COVERAGE_MODE = atomic COVERAGE_PROFILE = $(COVERAGE_DIR)/profile.out COVERAGE_XML = $(COVERAGE_DIR)/coverage.xml COVERAGE_HTML = $(COVERAGE_DIR)/index.html test-coverage-tools: | $(GOCOVMERGE) $(GOCOV) $(GOCOVXML) # ❶ test-coverage: COVERAGE_DIR := $(CURDIR)/test/coverage.$(shell date -u +"%Y-%m-%dT%H:%M:%SZ") test-coverage: fmt lint test-coverage-tools @mkdir -p $(COVERAGE_DIR)/coverage @for pkg in $(TESTPKGS); do \ # ❷ go test \ -coverpkg=$$(go list -f '{{ join .Deps "\n" }}' $$pkg | \ grep '^$(MODULE)/' | \. In ❶, we require the following tools—built like golint previously: gocovmergemerges profiles from different runs into a single one; gocov-xmlconverts a coverage profile to the Cobertura format, for Jenkins; gocovis needed to convert a coverage profile to a format handled by gocov-xml. In ❷, for each package to test, we run go test with the -coverprofile argument. We also explicitly provide the list of packages to instrument to -coverpkg by using go list to get a list of dependencies for the tested package and keeping only our owns. Update (2019-09) As mentioned in the comments, since Go 1.10, it is possible to test several packages while still using -coverprofile. Therefore, the test-coverage recipe can be simplified a bit and we can drop gocovmerge. Build# Another useful recipe is to build the program. While this could be done with just go build, it is not uncommon to have to specify build tags, additional flags, or to execute supplementary build steps. In the following example, the version is extracted from Git tags. It will replace the value of the Version variable in the hellogopher/cmd package. VERSION ?= $(shell git describe --tags --always --dirty --match=v* 2> /dev/null || \ echo v0) all: fmt lint | $(BIN) go build \ -tags release \ -ldflags '-X hellogopher/cmd.Version=$(VERSION)' \ -o $(BIN)/hellogopher main.go The recipe also runs code formatting and linting. The excerpts provided in this post are a bit simplified. Have a look at the final result for more perks, including fancy output and integrated help! Update (2019-09) There is an interesting thread about this article on Reddit. It contains a clue on how to lock tools needed for build as well. Several people also prefer to use Mage, a build tool using Go. Ironically, it requires a non-trivial build step. For an application not meant to be used as a library, I prefer to use a short name instead of a name derived from an URL, like github.com/vincentbernat/hellogopher. It makes it easier to read import sections:↩︎ import ( "fmt" "os" "hellogopher/cmd" "github.com/pkg/errors" "github.com/spf13/cobra" ) Starting from Go 1.16, without a go.sumfile, you need additional steps to generate it. It seems easier to add it to your version control system. ↩︎
https://vincent.bernat.ch/en/blog/2019-makefile-build-golang
CC-MAIN-2021-25
refinedweb
1,097
59.09
Working with several teams in React I noticed that more often than not, the naming of properties or even components have some issues. Not the ones you'll expect from a junior developer, but something deeper. The first day we have a class or watch a tutorial about code quality we learn that: "You should always use meaningful names" We all get that classic example with variables named using just one letter, like this: let a: string; let b: number; And then another example of how we should name them to be meaningful: let name: string; let age: number; The classic argue of the "cocky" student is that for the computer, both pieces of code are the same. And the classic response of the teacher is that for us humans a is not the same as name. I'm personally even in favor of "large names", so I'll rather see a function called loadUserConfiguration to loadConfig. Now, the issue I noticed with React development is not so much about the length of the property names, but more about the "meaning" of those properties. Read the following code and before reading the rest of the article, try to figure out what's the issue with the naming of the properties in it: const LoadButton = ({ getUsers, ...props }) => ( <button onClick={getUsers} {...props}>Load</button> ); const UserList = props => { const [users, setUsers] = useState<string[]>([]); const getUsers = () => fetch("/users") .then(response => response.json()) .then(fetchedUsers => setUsers(fetchedUsers)); return ( <div {...props}> <ul>{users.map(user => ( <li>{user}</li> ))}</ul> <LoadButton getUsers={getUsers} /> </div> ); }; The main issue with that piece of code is in the properties of LoadButton, to be precise, that getUsers property. Both parts of that name have some issues: - First: Having Usersas part of the name of the property of a generic LoadButtonis not generic at all. If the component was called LoadUsersButtonor something similar, maybe it would make some kind of sense, but for a generic component it doesn't. You might think: "then just name it something like getData", but ... - Second: Having getas part of the name of that property is leaking implementation details of the parent into the children. LoadButtonis not getting nothing by itself, is just a button with the text "Load" inside of it, so it should be only informing when the "load" event happens (when is clicked). The parent will then figure out what it wants to do with that "load" event. So, the fixed version could be something like: const LoadButton = ({ onLoad, ...props }) => ( <button onClick={onLoad} {...props}>Load</button> ); Or even better, get rid of that all together and just use onClick: const LoadButton = props => ( <button {...props}>Load</button> ); const UserList = props => { const [users, setUsers] = useState<string[]>([]); const getUsers = () => fetch("/users") .then(response => response.json()) .then(fetchedUsers => setUsers(fetchedUsers)); return ( <div {...props}> <ul>{users.map(user => ( <li>{user}</li> ))}</ul> <LoadButton onClick={getUsers} /> </div> ); }; Both the first and the last piece of code do the same, but the meaning of the properties in the last one is more straightforward, by avoiding unnecessary details about the implementation. This kind of mistakes are really easy to spot. You just need to step inside a component, forget about the rest of the app, and check if all the properties it has are relevant/meaningful in its context. That's it. Thanks for reading! Posted on by: ▲ LUKE知る ▲ Developer and gamer Discussion
https://dev.to/lukeshiru/the-importance-of-naming-23hi
CC-MAIN-2020-40
refinedweb
561
60.35
Create a Remote Domain Applies to: Exchange Server 2010 SP3, Exchange Server 2010 SP2 Topic Last Modified: 2011-03-19 Remote domains are SMTP domains that are external to your Microsoft Exchange organization. You can create remote domain entries to define the settings for message transfer between your Exchange organization and domains outside your Active Directory forest. The settings for remote domains are global configuration settings for the Exchange organization. Looking for other management tasks related to transport servers? Check out Managing Transport Servers. You can't create a remote domain that has the same name as an already configured accepted domain. For example, if your organization accepts mail for fabrikam.com, you can't create a remote domain for fabrikam.com. You need to be assigned permissions before you can perform this procedure. To see what permissions you need, see the "Remote domains" entry in the Transport Permissions topic. In the console tree, navigate to Organization Configuration>. The name can't exceed 64 characters. This field is required. Domain Name Use this field to identify the SMTP namespace of the remote domain. For example, type contoso.com. The remote domain name can't exceed 256 characters. This field is required. Include all subdomains To apply the remote domain configuration to all subdomains of the remote domain, such as mail.contoso.com, select this check box. Use this domain for my Office 365 tenant If the new remote domain you're creating represents the part of your organization that is hosted on Microsoft Office 365, select this check box. To create the remote domain entry with these settings, "Remote domains" entry in the Transport Permissions topic. You use the New-RemoteDomain cmdlet to create new remote domains in your organization. This example shows how this cmdlet can be used to create a new remote domain for contoso.com. For detailed syntax and parameter information, see New-RemoteDomain.
https://technet.microsoft.com/en-us/library/aa997639(v=exchg.141).aspx
CC-MAIN-2016-44
refinedweb
317
50.23
0 Hi, i am having trouble with an assignment. i need to create an array, store numbers in the array... sqaure, cube and square root those numbers individually using different methods. display the resuts with a dialog box. after that i need to find the sum of the numbers in the array and the average, and also display that with a dialog box. when that is done i need to ask the user if they want to play again, if they answer yes, to restart the program. the problem i am having is creating a void method that finds the sum and average of the numbers in the array. method must be a void for this task. (my lecturer said to use a for loop but i can't get it to work) can someone please help? i'm new to this so, sorry for a lack of explanation. /** * Write a description of class sqaurerootCube here. * * @author (your name) * @version (a version number or a date) */ import java.text.DecimalFormat; import javax.swing.JOptionPane; public class sqaurerootCube { public static void main (String[]args) { DecimalFormat fmt = new DecimalFormat ("0.##"); int num = 0; do { String number = JOptionPane.showInputDialog("How many numbers do you want to enter?"); try { num = Integer.parseInt(number); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog (null, "That is not an integer"); } } while(num <0 ); String num1; double[] numbers ; numbers = new double[num]; for(int count = 0; count <= (num-1); count++) { num1 = JOptionPane.showInputDialog("Enter number "+ (count+1) + " between 25 and 150"); numbers[count]= Integer.parseInt(num1); } for(int count = 0; count<= (num-1); count++) { JOptionPane.showMessageDialog (null, "number " + (count+1)+ " sqaured = " + calcSqaure(numbers[count])+ "\nnumber " + (count+1)+ " cubed = "+ calcCube(numbers[count]) + "\nsqaure root of number "+(count+1)+" = "+ fmt.format(calcSqaureRoot(numbers[count]))); } } public static double calcSqaure(double x) { return Math.pow (x,2); } public static double calcCube(double x) { return Math.pow (x,3); } public static double calcSqaureRoot(double x) { return Math.pow (x,0.5); } public static void average() { } }
https://www.daniweb.com/programming/software-development/threads/189671/help-with-methods
CC-MAIN-2016-50
refinedweb
329
51.95
csTraceBeamResult Struct Reference Return structure for the csColliderHelper::TraceBeam() method. More... #include <cstool/collider.h> Detailed Description Return structure for the csColliderHelper::TraceBeam() method. Definition at line 168 of file collider.h. Member Data Documentation closest_isect will be set to the closest intersection point (in world space). Definition at line 180 of file collider.h. closest_mesh will be set to the closest mesh that is hit. Definition at line 184 of file collider.h. Closest triangle from the model. closest_tri will be set to the closest triangle that is hit. The triangle will be specified in world space. Definition at line 175 of file collider.h. Sector in which the collision occured. Definition at line 193 of file collider.h. The squared distance between 'start' and the closest hit or else a negative number if there was no hit. Definition at line 189 of file collider.h. The documentation for this struct was generated from the following file: - cstool/collider.h Generated for Crystal Space 2.0 by doxygen 1.6.1
http://www.crystalspace3d.org/docs/online/new0/structcsTraceBeamResult.html
CC-MAIN-2016-30
refinedweb
172
54.18
A common need is an owner draw CListCtrl that allows a particular cell to contain another control such as an edit box, combo box, color picker etc... Such a control would be very useful in many applications, as it would provide a way to easily configure application specific properties such as background color etc... CListCtrl This article is about code samples that do just that. Over the years, I have seen several code samples that allow a CComboBox or CEdit control to be inserted in a particular cell of a CListCtrl-derived control. I have also tried this out myself. With this solution, the control itself is not persistent, so you cannot see what type of control a particular cell is filled with unless it has focus. Also, usually you need to activate the control and then manipulate it, which is completely impractical: for instance, you would need to first click on a checkbox to activate it, and then check/uncheck it. Another issue is you do not know all the implementation details of the inserted control, meaning you might get completely undesired results, with no possibility of fixing. This is just what I obtained in my trial using Visual Studio 6.0. CComboBox CEdit This convinced me that what was needed was another completely new solution that did not make use of the inserted CWnd-derived controls. CWnd There are system functions that allow you to paint the old style theme-less ‘classic’ look of buttons as these appeared in versions of Windows prior to XP. In addition, the OS has a whole collection of functions that enable you to handle themes: OpenThemeData etc… OpenThemeData Using these facilities, I have written this project in which, instead of inserting another CWnd-derived control into a cell of a CListCtrl, you paint the image of a combo box, checkbox etc. I have tested this with Windows 7, Vista, and XP, tried out changing themes, and have obtained acceptable results. The biggest drawback is that changing the theme while the application with CConfigListCtrl is open does not produce the best results: MeasureItem is not called again as it should be, meaning the row height is not immediately recalculated. I have not found a way for forcing an instant recalculation of this. This is not too dramatic, as changing theme is presumably done very rarely by an average user. CConfigListCtrl MeasureItem There are other more minor faults, as would be expected: a small amount of flickering – which might be eliminated by improving the code. A lot of work has been required for this project, spread in bits and pieces over the years (I started in 2006). There are still lots of features to add: no spin edit control, no editable combo, left/right/center text alignment to do... Otherwise, all control types have a look and feel consistent with each other, including the color picker, which supports themes. The overall concept is really very simple: there is a main CConfigListCtrl class, and CCellCtrl derived classes inserted in cells. CConfigListCtrl calls CCellCtrl virtual functions, such as drawing, and passes messages to other CCellCtrl virtual functions, such as mouse clicking. CCellCtrl The main CConfigListCtrl has no knowledge of the implementation details of the inserted controls, and new control types can be implemented without touching the CConfigListCtrl source code. All that is required is that the inserted control must derive from CCellCtrl or CCellDropDown if it contains a handle to a drop down pop up. The drop down pop up must derive from CListCtrlCellWnd, which itself derives from CWnd. CCellDropDown CListCtrlCellWnd Pointers to CCellCtrl-derived controls are stored in the m_CtrlMap member variable of CConfigListCtrl. This is just a DWORD – CCellCtrl pointer map where the DWORD contains the locations of cells in the control. m_CtrlMap DWORD Cleanup is done by traversing m_CtrlMap and deleting all the allocated memory. Below is a diagram showing how all the classes interact. MFC classes are marked in orange. Abstract classes are marked in gray. I have included two downloadable code samples: The value of any cell can be evaluated. The value of a CCellCtrl-filled cell has a format that is the same as the default value lpszDefaultTextValue parameter given in InsertCtrl, for instance, as described in the section 'Description of main functions'. lpszDefaultTextValue InsertCtrl Tab and Shift+Tab are supported and focus moves to the relevant CCellCtrl within CConfigListCtrl. F4 opens the pop up of a CCellDropDown-derived class, Esc closes it without setting the control to the currently selected item in the pop up. Enter closes it, but sets the control to the currently selected item. Arrow keys should allow the user to move around the items in the pop up. If there is not enough room to show the drop down downwards, then it is shown upwards instead. It is possible to enable or disable a cell in a particular control. See below: ...Row and columns can also be inserted or removed: ...Controls can be inserted or removed in a particular cell. If inserting a control in a cell which already has a control, the previous control is automatically deleted. ...It is possible to insert, select, or remove items in a cell which contains a CCellComboBox: CCellComboBox ...Supports theme change as already mentioned. If changed to 'Classic', you will get the following display. I suggest closing and reopening the application, as CListCtrl’s row height is not recalculated immediately after a theme change. This seems an MFC bug to me, but I may be mistaken. Will also run correctly in XP. A screenshot is shown below with the olive theme: This section describes how to build from scratch a project that uses CConfigListCtrl. To start with, create an MFC application using Visual Studio 2010. For simplicity, select Dialog based (not MDI or SDI). Ensure the ‘Common Control Manifest’ checkbox is checked and Finish. Extract all of ConfigListCtrlSource into a folder which contains the .cpp and .h files. Include all the root files to the project. Add a new filter ‘CellCtrls’ and attach the two new filters ‘Header Files’ and ‘Source Files’. Include all the files in the subfolder CellCtrls here. See the image below. (I have called my project ‘MFCTestCConfigCtrl’, but you may call it something else, of course.) Add a resource: right click on your *.rc file in the Resources tab and select ‘Add Resource…’. Select 'Bitmap' and click the button 'Import'. Navigate to the res\ folder and select checkbox.bmp. Rename the bitmap 'IDB_CHECKBOX'. (Open the bitmap's 'Properties' dialog box for that.) IDB_CHECKBOX In your project configuration properties, select Linker, Input, and add ‘UxTheme.lib’ to ‘Additional dependencies’: In your dialog, add a list control using Toolbox. This list control must have the following properties set: ‘Owner Draw Fixed’ must be ‘True’. ‘View’ must be ‘Report’. In ‘Class Wizard’, add a member variable, say m_ConfigListCtrl for the list control you just added. In the relevant xxxDlg.h header file, change the type of m_ConfigListCtrl from CListCtrl to CConfigListCtrl and add the #include "ConfigListCtrl.h" directive at the top. m_ConfigListCtrl #include "ConfigListCtrl.h" Add the following code at the top of your xxxDlg.cpp file, so you can use CCellxxx controls: CCellxxx #include "CellCtrls\CellEdit.h" #include "CellCtrls\CellCheckBox.h" #include "CellCtrls\CellComboBox.h" #include "CellCtrls\CellDateCtrl.h" #include "CellCtrls\CellColorCtrl.h" #include "CellCtrls\CellTimeCtrl.h" Override the PreTranslateMessage virtual function and add message handlers for WM_SIZING and WM_MOVE. Add the following code: PreTranslateMessage WM_SIZING WM_MOVE BOOL CMFCTestCConfigCtrlDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message==WM_KEYDOWN) m_bKeyUp = FALSE; if(pMsg->message==WM_KEYUP) m_bKeyUp = TRUE; if((pMsg->wParam == VK_ESCAPE || pMsg->wParam == VK_RETURN)) { if (m_bKeyUp) { m_bKeyUp = FALSE; return m_ConfigListCtrl.OnEnterEsc(pMsg->wParam); } else return TRUE; } return CDialogEx::PreTranslateMessage(pMsg); } void CMFCTestCConfigCtrlDlg::OnMove(int x, int y) { CDialog::OnMove(x, y); // Seems no way round this and have to explicitly call m_ConfigListCtrl this way. // Note: this is needed because when move, we want to either close any open // popups associated with the control or move these as well. It looks funny // otherwise. m_ConfigListCtrl.OnParentMove(x, y); } void CMFCTestCConfigCtrlDlg::OnSizing(UINT fwSide, LPRECT pRect) { CDialogEx::OnSizing(fwSide, pRect); m_ConfigListCtrl.OnSizing(fwSide, pRect); } You still need to add m_bKeyUp, which is a BOOL private member of your class instantiated to FALSE in the constructor. m_bKeyUp BOOL FALSE ...That is it! You have added a CConfigListCtrl to your project. For a bit of manipulation, you might add the following code in the "TODO: Add extra initialization here" area of OnInitDialog: OnInitDialog m_ConfigListCtrl.InsertColumn(0, _T("A column")); m_ConfigListCtrl.SetColumnWidth(0, 160); m_ConfigListCtrl.InsertItem(0, _T("")); m_ConfigListCtrl.SetItem(0,0,new CCellComboBox, _T("Selected Item\n1st item\n2nd item\nSelected Item")); For more details on how to manipulate CCellCtrls, see the next section. Of course, a function available within CListCtrl can still be used within CConfigListCtrl. The most useful probably are SetColumnWidth and GetItemText. I will only describe the new functions or functions that have been overloaded here. SetColumnWidth GetItemText int InsertColumn(int nCol, const LVCOLUMN* pColumn); int InsertColumn(int nCol, LPCTSTR lpszColumnHeading, int nFormat = LVCFMT_LEFT, int nWidth = -1, int nSubItem = -1); BOOL DeleteColumn(int nCol); int InsertItem(const LVITEM* pItem); int InsertItem(int nItem, LPCTSTR lpszItem); int InsertItem(int nItem, LPCTSTR lpszItem, int nImage); BOOL DeleteItem(int nItem); inline BOOL DeleteAllItems(); These functions are all overloaded. The functionality is same as for their CListCtrl equivalent, except that the underlying data placing CCellCtrls needs to be altered so that these remain in correct cells and are not out of phase. Also, if you insert a column at the beginning, all data in the cells needs to be programmatically shifted right, otherwise the content does not match the column headers. In addition, there are the following specialized functions for insertion/deletion of controls in cells: int InsertItem(int nItem, CCellCtrl *pCellCtrl, LPCTSTR lpszDefaultTextValue = _T("\0")); BOOL SetItem(int nItem, int nSubItem, CCellCtrl *pCellCtrl, LPCTSTR lpszDefaultTextValue = _T("\0")); void InsertCtrl(int nItem, int nSubItem, CCellCtrl *pCellCtrl); void DeleteCtrl(int nItem, int nSubItem); pCellCtrl can be a pointer to any one of: CCellEdit, CCellCheckBox, CCellComboBox, CCellDateCtrl, or CCellColorCtrl. The pointer can be created by using the C++ new directive directly within the function call. No need to worry about corresponding delete statements as cleanup is done within the CConfigListCtrl class. pCellCtrl CCellEdit CCellCheckBox CCellDateCtrl CCellColorCtrl new delete The default value lpszDefaultTextValue is used as follows: COLORREF CCellTimeCtrl To help manipulation, the following controls have been written: BOOL IsOnCellCtrl(int iItem, int iSubItem, CCellCtrl **ppCellCtrl); CCellCtrl *GetItemCellCtrl(int iItem, int iSubItem); Returns the relevant cell control if present in the {iItem, iSubItem} location on CConfigListCtrl. IsOnCellCtrl returns TRUE if present, FALSE otherwise. GetItemCellCtrl returns NULL if no cell control is present. {iItem, iSubItem} IsOnCellCtrl TRUE GetItemCellCtrl NULL CCellCtrl *GetActiveCellCtrl() const Returns the cell control that currently has focus. void EnableCtrl(int iItem, int iSubItem, BOOL Enable = TRUE); BOOL IsCtrlEnabled(int iItem, int iSubItem); EnableCtrl enables/disables a control in a particular cell if the cell has a control. IsCtrlEnabled returns whether the cell has an enabled or disabled control. If the cell does not have a control at all, the value returned is whether the instance of CConfigListCtrl is enabled. EnableCtrl IsCtrlEnabled BOOL SetCtrlAlignment(int iItem, int iSubItem, Alignment align); BOOL GetCtrlAlignment(int iItem, int iSubItem, Alignment &align); SetCtrlAlignment and GetCtrlAlignment will set or get the alignment of a cell if this contains a CCellCtrl. These functions return TRUE if the cell has a control, FALSE otherwise. Alignment only has an effect for CCellEdit, CCellCheckBox, and CCellComboBox. No effect for CCellDateCtrl, as not implemented. Alignment is not implemented on a standard MFC Date Picker control either (as presumably not very useful). Alignment has no meaning for a CCellColor control. Button stays on right hand side for a right aligned CCellComboBox. The standard MFC CComboBox displays button on left, with a small bug in Windows 7: the button’s corners are rounded on wrong side, which is strange since the right button style is available in themes. SetCtrlAlignment GetCtrlAlignment CCellColor It is sometimes useful to be able to determine the behaviour of a certain cell control type. This can be done preferably using the dynamic_cast directive as in, for example: dynamic_cast CCellComboBox * pComboCrtl = dynamic_cast<CCellComboBox *>(m_ListCtrl.GetItemCellCtrl(iRow, iColumn)); if (pComboCrtl) pComboCrtl->SetSelectedItem(iIndex); Below is a list of specialised CCellCtrl control functions: BOOL CCellComboBox::InsertItem(int Idx, LPCTSTR strText); BOOL CCellComboBox::RemoveItem(int Idx); Inserts or removes an item in a combo box. The point at which insertion takes place is given by Idx. If Idx is out of the range of existing values, returns FALSE, and no action takes place. Otherwise, returns TRUE. Idx BOOL CCellComboBox::SetSelectedItem(LONG lSelectedItem); LONG CCellComboBox::GetSelectedItem() const; Sets or gets the currently selected item of a combo box. LONG CCellComboBox::GetDisplayedRows() const; void CCellComboBox::SetDisplayedRows(LONG lDisplayedRows); Sets or gets the number of selected rows shown when the drop down list of a combo box is open. static void CCellDateCtrl::SetDateFormat(const CString & strDateFormat); This static function will set the date format for all CCellDateCtrls within an application that uses CConfigListCtrl. By default, the date format is given by the short date format specified on your computer (usually DD/MM/YYYY in UK). The tags that strDateFormat can use are given by: Day, Month, Year, and Era Format Pictures. strDateFormat void CCellDateCtrl::SetYMD(WORD Y, WORD M, WORD D); Will set the year month and day values for the control. void CCellTimeCtrl::SetTimeFormat(const CString& NewTimeFomat); Will set the time format for the control. Tags that can be used are ‘H’, ‘HH’, ‘h’, ‘hh’, ‘m’, ‘mm’, ‘s’, ‘ss’, ‘t’ and ‘tt’. COLORREF CCellColorCtrl::GetSelectedColor() Will obtain the color as a COLORREF format I am aware of the following faults: CMonthCalCtrl::GetMinReqRect PopupColorBar I started this project after having read 'Design Patterns' by Gamma, Helm, Johnson, and Vlissides, so was inspired by that book. Otherwise, all my sources have been within MSDN. For the repeat effect of new CCellSpinCtrl, following article was very useful: Mouse Repeat. CCellSpinCtrl CCellPushButton RemoveCtrl This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) void CConfigurableCtrlDlg::OnClickMylist(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); // TODO: Add your control notification handler code here *pResult = 0; } virtual BOOL OnPressButton(UINT nFlags, CPoint point) = 0; virtual void DrawCtrl(CDC *pDC, const LPRECT prcCell, UINT uiItemState = 0) = 0; virtual const RECT &GetTextRect() const = 0; // Probably just return bounding rectangle here. void CConfigListCtrl::RemoveCtrl(int nItem, int nSubItem) { CCellCtrl *pCellCtrl; if (m_CtrlMap.Lookup(GetMapKey(nItem, nSubItem), pCellCtrl)) { m_CtrlMap.RemoveKey(GetMapKey(nItem, nSubItem)); if (m_ActiveCell.m_pCellCtrl == pCellCtrl) DeActivateCell(); // Upade m_HotCell if (m_HotCell.m_pCellCtrl == pCellCtrl) // Add by Yong-Tae.Kim m_HotCell.Assign(NULL, -1, -1); delete pCellCtrl; pCellCtrl = NULL; // Add by Yong-Tae.Kim m_CtrlSet.Remove(GetMapKey(nItem, nSubItem)); } } General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. News on the future of C# as a language
http://www.codeproject.com/Articles/235278/An-MFC-CListCtrl-derived-class-that-allows-other-c?msg=4310404
CC-MAIN-2014-10
refinedweb
2,495
55.13
SslCherry? SslCherry? is a simple one-page python file that integrates the python package M2Crypto with CherryPy to provide HTTPS support. Usage from cherrypy import cpg import sslcherry ... cpg.root = Root() sslcherry.start(configFile='foo.conf') Your config file should contain something like this: [server] sslKeyFile=foo.pem Where "foo.pem" is a file containing your private key and certificate, in the same format that apache uses. Security Although the original author of M2Crypto was unsure of its security, M2Crypto has been developed heavily from those days and is in production use. As usual, use at your own risk. Bugs Attachments - sslcherry.3.py (2.7 kB) - v3: Fix SSL error handling so that it doesn't terminate/lock-up the server, added by Tim Evans <t.evans-cp@aranz.com> on 03/17/07 15:22:42.
http://tools.cherrypy.org/wiki/SSLWithM2Crypto
crawl-002
refinedweb
138
60.82
Support for the Java EE specification in NetBeans IDE enables you to take full advantage of the many Java EE features simplifying application development. A significant development in the Java EE. Contents To follow this tutorial, you need the following software and resources. For this tutorial you need to register a local instance of GlassFish server with the IDE. If you have installed the "Java EE" form should resemble the following image. When you click OK, the server will create the user and open the File Users panel. You will see that there is now a user named manager. Now that the user is created, you will create an enterprise application that will check that the user is able to see the data. In this exercise you will create a simple Java class library project that will contain the remote interfaces for the session bean. The compiled class library JAR will be added to the classpath of the EJB module and the application client that will be used to call the session bean. In the next section you will create a session bean in an enterprise application. The session bean will be accessed via a remote interface. When you create the session bean, the IDE will automatically create the remote interface in the class library and add the class library JAR to the classpath of the enterprise application. The enterprise application will consist of a simple session bean that is accessed via a remote interface in the class library project. In this exercise you will create an enterprise application that contains an EJB module. For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users or projects. In this exercise you will create a session bean in the EJB module project. the AccountStatus class and opens the file in the source editor. The IDE also creates the AccountStatusRemote remote interface for the bean in the bean package in the SecureRemoteInterface class library project and added the SecureRemoteInterface class library JAR to the classpath of the EJB module project. If you open the Libraries category of the Properties dialog box of the EJB module you will see that the JAR is added to the compile-time libraries. public class AccountStatus glassfish-application.xml deployment descriptor for the enterprise application. Because the enterprise application does not need deployment descriptors to run, the IDE did not create the deployment descriptors by default. So you first need to create the deployment descriptor file and then edit the file in the multi-view editor to configure the security role mappings. Alternatively, you can open the New File wizard by choosing File > New File from the main menu. In this case, be sure that you select the Secure project in the Project dropdown list. When you click Finish, the IDE creates glassfish-application.xml and opens the file in the multi-view editor. If you expand the Secure enterprise application project node in the Projects window, you can see that the descriptor file is created under the Configuration Files node. The editor should now be similar to the following. You can click on the XML tab in the multi-view editor to view deployment descriptor file in XML view. You can see that the deployment descriptor file now contains the following: <glassfish-application> <security-role-mapping> <role-name>USERS</role-name> <group-name>bank_users</group-name> </security-role-mapping> </glassfish-application> The getStatus method is now secure and only those users in the group bank_users that you specified on the server can access the method. You now need a way to test the security settings. The simplest way is to create a basic application client that will prompt the user for a username and password. In this section you will create a simple application client to access the AccountStatus session bean. You will use the @EJB annotation in the code to call the bean via the remote interface and the IDE will automatically add the class library JAR that contains the interface to the classpath of the application client. When you click Finish, Main.java opens in the source editor. The IDE adds the following code to the application client to look up the session bean. @EJB private static AccountStatusRemote accountStatus; If you expand the Libraries node in the Projects window you can see that the IDE added the SecureRemoteInterface JAR to the project classpath. public static void main(String[] args) { System.out.println(accountStatus.getStatus()); } For more on applications clients, see Creating and Running an Application Client on the GlassFish Server. The application is now ready. You will first deploy the enterprise application to the server. After you deploy the enterprise application you can run the application client to test that the method in the enterprise application is secure and that the user roles are mapped correctly. When you run the application client you will be prompted for a username and password for a user in the bank_users group. When you click Deploy, the IDE builds the EAR file, starts the application server (if it's not running) and deploys the EAR file to the server. The account contains 250$ This very basic example demonstrates how to use Java annotations to secure a method in an enterprise bean. For more information about using annotations and deployment descriptors.
https://netbeans.org/kb/docs/javaee/secure-ejb.html
CC-MAIN-2016-50
refinedweb
897
53.51
I came across a blog post discussing an interview question for developers: "Write a function to determine if a number is a power of 2." Subsequently, I noticed a great discussion on StackOverflow discussing methods of solving this problem, and another blog post describing ten ways to do this in C. I've translated a few implementations into Factor to contrast the various approaches. The signature of the words we will create looks like this: : power-of-2? ( n -- ? ) And some basic test cases used to verify that it works: [ t ] [ { 1 2 4 1024 } [ power-of-2? ] all? ] unit-test [ f ] [ { -1 0 3 1025 } [ power-of-2? ] any? ] unit-test Implementations We can shift the number to the right, checking to see that the first odd value observed is 1: : shift-right/power-of-2? ( n -- ? ) dup 0 <= [ drop f ] [ [ dup even? ] [ 2/ ] while 1 = ] if ; Or, we can use a virtual sequence of bits and count the number of "on" bits (should be only 1): : bits/power-of-2? ( n -- ? ) dup 0 <= [ drop f ] [ make-bits [ t? ] count 1 = ] if ; Or, we can compute the integer log2 raised to the second power, and compare: : log2/power-of-2? ( n -- ? ) dup 0 <= [ drop f ] [ dup log2 2^ = ] if ; Or, we can calculate the next-power-of-2, and compare: : next-power/power-of-2? ( n -- ? ) dup 1 = [ drop t ] [ dup next-power-of-2 = ] if ; Or, we can compare the number with its two's complement: : complement/power-of-2? ( n -- ? ) dup 0 <= [ drop f ] [ dup dup neg bitand = ] if ; Or, we can decrement the number and compare it with the original: : decrement/power-of-2? ( n -- ? ) dup 0 <= [ drop f ] [ dup 1 - bitand zero? ] if ; Or, we can define a lookup table (using the literals vocabulary to define the table at compile time) holding all possible 64-bit powers of 2 (restricting the range of valid inputs to 64-bits): CONSTANT: POWERS-OF-2 $[ 64 iota [ 2^ ] map ] Using this, we can check a given number against all the values in the lookup table: : check-all/power-of-2? ( n -- ? ) POWERS-OF-2 member? ; Or, we can do a linear search, stopping when we see numbers too large: : linear-search/power-of-2? ( n -- ? ) POWERS-OF-2 over [ >= ] curry find nip = ; Or, knowing that the lookup table is sorted, we can do a binary search: : binary-search/power-of-2? ( n -- ? ) POWERS-OF-2 sorted-member? ; Or, we can compute a hash-set (at compile time), and check for membership: : hash-search/power-of-2? ( n -- ? ) $[ POWERS-OF-2 fast-set ] in? ; Or, we can use the integer log2 as an index into the lookup table. : log-search/power-of-2? ( n -- ? ) dup 0 <= [ drop f ] [ dup log2 POWERS-OF-2 nth = ] if ; Testing We can make a list of all our implementations: CONSTANT: IMPLEMENTATIONS { shift-right/power-of-2? bits/power-of-2? log2/power-of-2? next-power/power-of-2? complement/power-of-2? decrement/power-of-2? check-all/power-of-2? linear-search/power-of-2? binary-search/power-of-2? hash-search/power-of-2? log-search/power-of-2? } And then test their functionality: : test-power-of-2 ( -- ? ) IMPLEMENTATIONS [ 1quotation [ call( n -- ? ) ] curry [ { 1 2 4 1024 } swap all? ] [ { -1 0 3 1025 } swap any? not ] bi and ] all? ; Sure enough, they seem to work: ( scratchpad ) test-power-of-2 . t Performance We can benchmark the performance of the various implementations operating on 1,000,000 random 32-bit numbers: : bench-power-of-2 ( -- assoc ) IMPLEMENTATIONS randomize 20 2^ [ random-32 ] replicate '[ [ name>> "/" split1 drop ] [ 1quotation [ drop ] compose [ each ] curry [ _ ] prepose nano-count [ call( -- ) nano-count ] dip - ] bi ] { } map>assoc ; Running the benchmark, we see that log2/power-of-2? is the (slightly) fastest version: The raw numbers from one of my benchmark runs: ( scratchpad ) bench-power-of-2 sort-values . { { "log2" 118107290 } { "complement" 119691428 } { "decrement" 121455742 } { "log-search" 122799186 } { "next-power" 127366447 } { "shift-right" 137695485 } { "binary-search" 204224141 } { "check-all" 267042396 } { "hash-search" 269629705 } { "linear-search" 280441186 } { "bits" 1112186059 } } Improvement But, can we do better? We have already created a faster implementation than the math vocabulary, which defines power-of-2? using "decrement". Focusing on that implementation, perhaps we can still introduce some improvements. We can do less work, by exiting early using a short-circuit combinator if the first test fails: : decrement+short/power-of-2? ( n -- ? ) { [ dup 1 - bitand zero? ] [ 0 > ] } 1&& ; Or, we can add type information, assuming only fixnum values (restricting our possible input values to a 60-bit number between -576,460,752,303,423,488 and 576,460,752,303,423,487): TYPED: decrement+typed/power-of-2? ( n: fixnum -- ? ) dup 0 <= [ drop f ] [ dup 1 - bitand zero? ] if ; Or, if we are okay with restricting the input values, we can try writing it in C: - Build a simple C function in power-of-2.c: #include <stdint.h> int64_t isPowerOfTwo (int64_t x) { return ((x > 0) && ((x & (x - 1)) == 0)); } - Build a C library we can use : $ cc -fno-common -c power-of-2.c $ cc -dynamiclib -install_name power-of-2.dylib \ -o power-of-2.dylib power-of-2.o $ sudo mv power-of-2.dylib /usr/local/lib USING: alien alien.c-types alien.syntax alien.libraries ; "libpowerof2" "power-of-2.dylib" cdecl add-library LIBRARY: libpowerof2 FUNCTION: int isPowerOfTwo ( int x ) ; - And, finally, build a Factor word that uses it: : decrement+alien/power-of-2? ( n -- ? ) isPowerOfTwo 1 = ; Running the benchmarks shows the typed version only slightly beating the short-circuit version, with a roughly 10% improvement: { { "decrement+typed" 111711456 } { "decrement+short" 112070520 } { "decrement+alien" 113014058 } { "decrement" 123256748 } } Given that we want some ability to generalize our function to all integer inputs, I'd be happy declaring decrement+short/power-of-2? the "winner". Can you do better? The code for this is on my Github. 2 comments: Delightful. With SBCL: (defun logcount-power-of-2-p (n) (and (= 1 (logcount n)) (plusp n))) (defun logand-power-of-2-p (n) (and (zerop (logand n (1- n))) (plusp n))) SLIME> (time (loop for i from 1 to (expt 2 20) do (logcount-power-of-2-p (random 1152921504606846975)))) Evaluation took: 0.073 seconds of real time 0.076661 seconds of total run time (0.076661 user, 0.000000 system) 105.48% CPU 175,873,707 processor cycles 0 bytes consed NIL SLIME> (time (loop for i from 1 to (expt 2 20) do (bitand-power-of-2-p (random 1152921504606846975)))) Evaluation took: 0.070 seconds of real time 0.069996 seconds of total run time (0.069996 user, 0.000000 system) 100.00% CPU 166,922,226 processor cycles 0 bytes consed NIL
http://re-factor.blogspot.com/2011/04/powers-of-2.html
CC-MAIN-2017-13
refinedweb
1,124
65.22
NAME Connection - Simple connectivity functions for Jabber SYNOPSIS # client connection: my $c = new Jabber::Connection( server => 'jabber.org', log => 1, ); # component connection: # my $c = new Jabber::Connection( # server => 'localhost:5700', # localname => 'comp.localhost', # ns => 'jabber:component:accept', # log => 1, # debug => 1, # ); die "oops: ".$c->lastError unless $c->connect(); $c->register_beat(10, \&every_10_seconds); $c->register_handler('presence',\&presence); $c->register_handler('iq',\&handle_iq_conference); $c->register_handler('iq',\&handle_iq_browse); $c->auth('qmacro','password','myresource'); # client auth # $c->auth('secret'); # component auth $c->send('<presence/>'); $c->start; DESCRIPTION The Jabber::Connection package provides basic functions for connecting clients and components to a Jabber server. METHODS - new() The connection constructor. Returns a new Jabber::Connection object. The parameters are specified in a param => value list. For a basic client connection, you can specify the minimum my $c = new Jabber::Connection(server => 'jabber.org'); If no port is specified, the default 5222 will be used. There are other parameters that can be passed: - ns the namespace that qualifies the connection stream. If left unspecified, this will default to 'jabber:client'. For a TCP socket-based component, specify 'jabber:component:accept'. [ *** These are the only two stream namespaces supported now *** ] - localname the name of the component in a component connection. - ssl whether the connection should use SSL [ *** not supported yet! *** ] See the SYNOPSIS for examples of new(). - connect() Use this to establish the stream to the Jabber server. There are no parameters required. If a problem occurs, the function returns 0, and the error reason is available by calling lastError(). Example: $c->connect(); - disconnect() Use this to terminate the stream and end the connection. Example: $c->disconnect(); - process() Call this function to look for incoming fragments on the stream. You can specify an optional argument which is the number of seconds to wait while looking. If no argument is given, a value of 0 is assumed. An incoming fragment is parsed and assembled into a Node object which is dispatched to any handlers that have been registered for the Node object's tag name. Examples: $c->process(); # look for any fragments but don't # wait around if there aren't any $c->process(5); # wait for up to 5 seconds for fragments # to come in on the stream - auth() Perform authorization. This function takes either one or three arguments, depending on what type of connection has been made. If you have made a component connection, the secret must be specified here as the single argument. If you have made a client connection, the username, password and resource must be specified. Example: $c->auth('secret'); # component auth $c->auth('user','password','resource'); # client auth For a component authorization, the <handshake/> based process is used. For a client authorization, the JSM is queried for the supported authentication methods, and then one is picked, degrading gracefully through zero-k, digest and plaintext methods. - send() Send data across the stream with this function. You can send either XML in string form, or send a Node object. Examples: $c->send('<presence/>'); my $msg = $nf->newNode('message')->insertTag('body')->data('hello'); $msg->attr('to','qmacro@jabber.org'); $c->send($msg); - lastError() Returns the last error that occured. This will usually be the text from a stream error. - ask() Send something and wait for a response relating to what was sent. This relation is established using an id attribute in the top level tag of the node being sent. If there is no id attribute, one is inserted with a value automatically assigned. - register_handler() When a fragment is received and turned into a Node object, a dispatching process is started which will call handlers (callbacks) that you can set using this function. The function takes two arguments. The first is used to identify the node type (the element) - e.g. 'message', 'presence' or 'iq'. The second is a reference to a subroutine. You can register as many handlers as you wish. Each of the handlers registered for a specific node type will be called in turn (in the order that they were registered). Each of the handlers are passed two things - the node being dispatched, and a 'parcel' which can be used to share data between the handlers being called. The parcel value passed to the first handler in the call sequence is undef. Whatever value is returned by a particular handler is then passed onto the next handler. If a handler returns nothing (e.g. by simply the returnstatement), then the parcel data remains unaffected and is passed on intact to the next handler. (You don't have to do anything with the parcel; it's there just in case you want to pass something along the call sequence.) If a handler returns the special value represented by the constant r_HANDLED, the call sequence is ended - no more handlers in the list are called in the dispatch for that node. Examples: $c->register_handler( message => sub { ... } ); $c->register_handler('iq', \&handle_version); $c->register_handler('iq', \&handle_time); $c->register_handler('iq', \&handle_browse); - register_beat() You can register subroutines to be called on a regular basis using the heartbeatfeature. The first argument is the number of seconds ('every N seconds'), the second is a subroutine reference. Example: $c->register_beat(1800, \&getRSS); This example registers a subroutine getRSS() to be called every half an hour. Note: the heart doesn't start beating until the start() function is called. - start() Start a process loop. This has a similar effect to something like while (1) { $c->process(1) } except that it also maintains a heartbeat (see register_beat()). SEE ALSO Jabber::NodeFactory, Jabber::NS AUTHOR DJ Adams VERSION early This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/Jabber::Connection
CC-MAIN-2015-48
refinedweb
943
56.76
MAY 2017 COMPLIMENTARY 2nd Annual FLAVOR AWARDS 2017 Winners onth M o ly g r ’ a s F CONTENTS 60 65 COVER STORY 22 FLAVOR AWARDS: 2017 WINNERS. 12 | MAY 2017 | FARGOMONTHLY.COM 73 18 60 62 65 RECURRING Editor's Letter Mixologist of the Month Community Spotlight Health & Wellness Spotlight 70 73 80 85 RESOURCES Career Finder Event Calendar Live Music & Trivia Calendar Drink Specials FARGO MONTHLY | MAY 2017 Visit FARGOMONTHLY.COM for extended content, events, drink specials and more. GET WITH IT Spotlight Media 15 Broadway N. Suite 500, Fargo info@spotlightmediafargo.com 701-478-7768 fargomonthly fargomonthly.com @fargomonthly ON THE COVER We staged the cover shot at Drunken Noodle with their popular Pad Thai dish, which is also the winner of the "Best Pasta Dish" award in Fargo Monthly's Flavor Awards this year. Find out the rest of the winners in our cover story on page 22. PHOTO BY Paul Flessland @fargomonthly MAY 2017 Volume 7 / Issue 5 A SPOTLIGHT MEDIA PRODUCTION Fargo Monthly Magazine is published 12 times a year and is free. Copies are available at more than 500 Fargo-Moorhead locations and digitally at fargomonthly.com. Publisher Mike Dragosavich drago@spotlightmediafargo.com CREATIVE Editorial Director Andrew Jason andrew@spotlightmediafargo.com Editor Erica Rapp erica@spotlightmediafargo.com Graphic Designers Sarah Geiger, Ryan Koehler, Matt Anderson Photographer Paul Flessland photography@spotlightmediafargo.com Contributors Erica Rapp, Greg Tehven, Kylee Seifert Copy Editors Erica Rapp, Ethan Mickelson, Joe Kerlin Sales Administrative Assistant Pam Mjoness Business Operations Manager Heather Hemingway Administration Nicole Houseal Circulation Delivery Mitch Rapp, Hal Ecker, Nolan Kaml Fargo Monthly is published by Spotlight Media, LLC. Copyright 2017 Fargo Monthly and fargamonthly.com. All rights reserved. No parts of this periodical Inc. 15 Broadway N, Suite 500 Fargo, ND 58102 or info@spotlightmediafargo.com ADVERTISING: 701-478-SPOT (7768) MIKE TANK MEET THE TEAM SAM LAYNE ANDREW ETHAN KELSEY LEARN MORE ABOUT US AT SPOTLIGHTMEDIAFARGO.COM NATE PAUL NICOLE JOE ERICA BECCA SARAH RYAN HEATHER RYLEE KARA JENNY PAUL JESSE MATT TRACY PAM Spring into Summer Shopping Guide Grow your style with our 2017 "Spring into Summer" Shopping Guide. Blooming with fresh finds, this locally sourced guide is sure to elevate your interior space and prime the exterior of your home for outdoor entertaining. The NFL Life with Kyle Emanuel NDSU's footprint in the National Football League is continuing to grow. From talented football stars like Kyle Emanuel to distinguished coaches peppered around the league, the Bison connections are getting stronger. We dip into the NFL this month to examine a few of the NFL connections. Open For Business Are drones and automated systems the next two big industries in North Dakota? A number of business and political leaders seem to think so. In this wide-ranging cover story, Fargo Inc! covers everything from drone racing to precision agriculture to selfdriving cars. They also preview the upcoming Drone Focus Conference 2017, and U.S. Sen. John Hoeven even makes an appearance. Photo by Paul Flessland EDITOR back for seconds O ne of the things that I’m most grateful for when it comes to this job is the relationships that I’ve developed with the people in this community, and a large part of those relationships are with those in the bar and restaurant industry. It’s safe to say that some of the people that I’ve met in this sector of business have become close friends, and that’s why the Flavor Awards and this issue are so important to me. It’s not just because I love writing about local food (which you should know is very true by now), but I get to see firsthand all of the hard work that it takes for a chef to completely redo a menu, a mixologist to come up with an original cocktail that the public will love, a brewer to bring an entirely new recipe to local beer lovers, a restaurant owner to come up with great Happy Hour specials for their regulars and much more. When I first started working on our second annual Flavor Awards back in January, I was incredibly excited to see so 18 | MAY 2017 | FARGOMONTHLY.COM erica@spotlightmediafargo.com much support from the local dining scene once again. I was also thrilled to see a lot more variety in the amount and types of establishments that were nominated this year and participated, along with some back-to-back winners in a few categories. We planned the nomination and voting process for months and launched it well in advance so that we could reach as many people in the area as possible to find out what their favorite local dishes, drinks and establishments are. Instead of shining a direct spotlight on the restaurants, I feel that it’s important to focus more on the actual items being created and it’s something that sets these awards apart from others like it. The public knows what they love, and that’s what I enjoy. The point of our Flavor Awards issue is not to just highlight a bunch of No. 1s. Our goal for these awards and this issue is to get people excited about the wonderful food and drinks that are created right here in our community and to give credit and recognition to the establishments that work so hard at their craft. Bakers, chefs, mixologists, bartenders, restaurant owners, brewers and anyone else alike–I have the utmost respect for your hard work and all that you do to bring your creations to this community. This one’s for all of you. If you submitted a nomination or voted for this year’s Flavor Awards, thank you. Since we’re usually the ones giving food and drink recommendations each month, we appreciate your thoughts this time around. Your nominations could easily be somebody’s new favorite thing, and that’s pretty awesome. Feel free to send me suggestions or thoughts for next year’s awards! Cheers, and happy dining. SAVE THE DATE Fargo Monthly’s Burgers, BBQ and Beer Festival Thursday, June 15 Moorhead Center Mall Parking Ramp Visit burgerfestfargo.com for updates and more information. F s onth ly go M r ’ a The Details We know that it's dang near impossible to ask every single human being in FargoMoorhead what their favorite dishes and drinks are, but we did our best to come up with a survey method that would reach thousands of people. And it worked. Here are some of the details behind the Flavor Awards. These results are generated by the public. This is about what you, the people of Fargo-Moorhead, like to eat and drink. The nomination process took place from February 20 through March 13, with hundreds of individuals submitting the names of their favorite local dishes and drinks based on a given category. We took note of every single item that was nominated and narrowed things down to find the top five in each category with the most nominations. Some categories had to be narrowed down to the top six or seven due to multiple ties. The final voting round with the top nominees in all 18 categories took place from March 17 to April 5. Each establishment was allowed to have a maximum of two items per category in the final voting round. BEST BURGER JL Beers 518 1st Ave. N, Fargo 4240 32nd Ave. S, Fargo 810 13th Ave. E, West Fargo 2902 Highway 10 E, Moorhead APPETIZER Toasted Frog 305 Broadway N, Fargo If you're not a pickle fan, think again, because this heavenly appetizer will probably change your mind. This Toasted Frog classic is made up of dill pickle spears wrapped in Havarti cheese, fried and served with a Sriracha-Ranch dipping sauce. All it takes is one bite to fall in love with these cheesy-fried pickles of greatness. BEST TACO Vinyl Taco 520 1st Ave. N, Fargo This taco was the runner-up to another one of Vinyl Taco's creations in last year's Flavor Awards, so it comes as no surprise to see it at the top this year. In this tortilla, crispy crusted chicken is accompanied by fresh spinach, shredded cheese, fresh diced mango and a house-made sweet onion vinaigrette for a sweet and savory flavor combo. BEST DESSERT Nichole's Fine Pastry 13 8th St. S, Fargo This decadent dessert tower is something you might see in your dreams, and you probably won't be able to resist eating every last bite of this good-looking treat. The bottom layer of the tower is a layer of chocolate cake with an outer coating of chocolate crunch. The rest is a silky dark chocolate mousse enrobed in a dark chocolate glaze and it's sure to make your heart skip a beat at first bite. And you can't forget about that perfect little golden flake on top. BEST BLOODY MARY Lucky's 13 Pub 4301 17th Ave. S, Fargo What more could you ask for in a Bloody Mary when you're getting a mini sandwich on top? Not much, really. This Bloody Mary creation is made with vodka, Lucky 13's signature homemade mix–which is award-worthy in itself–topped with a mini BLT sandwich and served with a 7-ounce pony beer. You can't complain about multiple treats in one. Before you run out the door to the restaurant right now, this special delight is only available with the BLT on top Saturdays from 9 a.m.-4 p.m. and Sundays from 11 a.m.-4 p.m. BEST SUSHI ROLL Wasabi Sushi & Asian Grill 623 NP Ave., Fargo This sushi roll is not only a culinary masterpiece when it comes to flavor, but truly picture perfect. Wasabi's Dakota Roll is made up of spicy tuna, crunch and avocado and it's topped with a spicy crab salad that features spicy mayo, wasabi sauce and Sriracha. It's an impeccable blend of classic flavors with just the right amount of spice, and you really can't ask for much more in such a good roll. BEST PASTA DISH Drunken Noodle 623 NP Ave., Fargo You can't go wrong with this common Thai dish, and what makes it even better is that you can enjoy this pasta delight at Drunken Noodle for lunch, dinner or even your fourth meal late at night. This popular dish is made with rice noodles stir-fried with egg, tamarind sauce, bean sprouts and green onions, and it's served with crushed peanuts and a lime wedge for that extra zest. BEST LOCAL BEER Junkyard Brewing Company 1416 1st Ave N, Moorhead Junkyard Brewing Company has perfected this stout-style recipe with a mix of powdered peanut butter, roasted barley, Peanut Butter Cap'n Crunch cereal and a secret natural peanut ingredient. Similar to peanut butter cup candy, this tasty brew is sure to impress flavor palates of all sorts. Whether you're a craft beer lover or not, you really can't pass up the opportunity to try this bandit of a beer, because it's sure to rob the No. 1 spot in your heart. *Be sure to stay updated with the brewery on social media to find out when Peanut Butter Bandit is available on tap or in cans! 38 | MAY 2017 | FARGOMONTHLY.COM BEST WINGS Doolittles Woodfire Grill 2112 25th St. S, Fargo Yes, that sauce might get all over your hands, but Doolittles doesn't "mess" around with their wing game, and you'll know that for a fact after one bite. These traditional wings are rubbed in 14 different herbs and spices before being coated in a special housemade sauce that's got all of your favorite buffalo flavors plus sweet hints of honey and herbal notes of thyme and basil. Better yet, the wings are cooked rotisserie style, so you'll also get that perfect woodfire-smoked taste with every bite. BEST PIZZA Rhombus Guys 606 Main Ave., Fargo This Rhombus Guys classic is definitely a gift from the pizza Gods and truly a slice of heaven for meat lovers with its well-rounded combination of pepperoni, sausage, Canadian bacon, beef, bacon, mozzarella cheese and marinara sauce. It's the perfect pie to satisfy all types of meat-eaters out there, and you'll be hard-pressed to find someone in your pizza party who doesn't enjoy it. BEST SANDWICH Grand Junction 435 Main Ave., Moorhead 3051 25th St. S, Fargo 1100 19th Ave. N, Fargo 5050 13th Ave. S, Fargo As a staple sandwich shop for many years in the FargoMoorhead area–not to mention a previous Flavor Awards winner–Grand Junction sure has things figured out when it comes to grilling up savory East Coast-style subs. Their Chicken Cordon Bleu sandwich is a mouth-watering combination of chicken breast, ham, swiss cheese, tomatoes, lettuce, honey mustard and mayo for a comforting delight in a heavenly slice of French bread. BEST VEGETARIAN DISH Vinyl Taco 520 1st Ave. N, Fargo Vegetarian dishes vary far and wide across every restaurant in town, but the public clearly fancies tacos this time around. This veggie taco is loaded with grilled queso fresco, creamed corn, pico, black beans, serrano-avocado salsa and blanco crema. Even if you're not a vegetarian, this taco will do you no wrong. BEST COCKTAIL The Boiler Room 210 Broadway N, Fargo If you're looking for a cocktail that is refreshing yet perfectly comforting for the winter months, this seasonal winter mule from The Boiler Room is going to satisfy all of your tastebuds. This approachable cocktail is made in the classic copper mug with Smirnoff Cherry Vodka, lime juice, simple syrup and orange juice before it's topped off with ginger beer and garnished with a Luxardo cherry, an orange slice and cinnamon sticks. It's a fantastic blend of invigorating fruit flavors with a heart-warming finish from the cinnamon. Try the White Chocolate Mocha! 5675 26th Ave. S, Fargo 2550 University Drive S, Fargo This locally-owned coffee shop will warm your soul the second you walk in the door and smell the donuts. Yes, you read that correctly. You get a mini donut with your drink purchase and that's pretty great. With two thriving locations in town, Beans Coffee Bar has become a true favorite with the community and its coffee lovers. The shop gets all of their baked goods from local bakeries and they even have areas designated for kids to play. BEST BFREAKFAST DISH The Shack on Broadway 3215 Broadway N, Fargo If you're starting your day with breakfast at The Shack, then you're definitely starting your day on the right track. This dish is comfort food at its best, and it's got one big, fluffy homemade biscuit completely smothered in a special housemade sausage gravy and served with a side of freshly-shredded (never frozen) hashbrowns. Your happiness will skyrocket with each and every bite, even if it's earlier than 7 a.m. 51 BEST LATE-NIGHT MEAL Taco Bros. Food Truck 428 Roberts St. N, Fargo Available only from spring to early fall depending on the weather, Taco Bros. has become an incredibly popular local favorite for lunch, dinner and late-night eats of delicious real Mexican food. The Trust You Bro Platter is really all about trust (which is easy knowing how good the food is), and it's filled with a mix of anything the chef feels like serving you. This platter has got a gringo taco, which is a flatbread asada taco with pico, lettuce, cheese, Sriracha sour cream and chipotle mayo; a corn taco with chicken, pico, lettuce, cheese and Sriracha sour cream; rice and beans. BEST NEW JOINT 614 Main Ave., Fargo frontstreettaproom.com/events facebook.com/FrontStreetTaproom *The public was asked to consider not only the food and/or drink quality of this establishment while nominating and voting, but also overall traits such as customer service, atmosphere, affordability, selection, etc. This award was open to any establishments in the dining industry that opened within the last year. Occupying what used to be the One World boutique for many years, Front Street Taproom has brought a refreshing flare to the Main Avenue block of downtown and is proving to be the ultimate tribute to locallymade products. And if there's one thing that's incredibly important to this community, it's supporting local crafts. Because let's be real, the brewers in this region are highly skilled at what they do, and Front Street allows them to be recognized further. The taproom–with its vintage, cozy and welcoming feel–has 30 local beers on tap from North Dakota and Minnesota and recently has started serving local ciders, kombucha teas and wine. The taproom's unique atmosphere is truly a great place to gather with friends (sans all the distractions from televisions like most bars), play games over brews or even hold a meeting or a party. Oh, and if this place wasn't attractive to you already, their recent back patio addition will for sure draw you in to enjoy a cold brew under the sun. Establishment Features: • Happy Hour: $1 off pints MondayThursday from 4-6 p.m. and noon-5 p.m. on Fridays. • Back alleyway patio seating. • Upper level public seating space that's also available for party or meeting rental. • Growler fills. • Open Mic Night with local DJ CMPTRDSTR Monday nights at 7 p.m. •Trivia every Tuesday at 7 p.m. Trivia is also written by the staff, making it unique to the bar. • Vinyl Night with Vinyl Giant at 7 p.m. on Wednesdays. • Live music Thursday, Friday and Saturday nights starting at 9 p.m. • You can bring in food from wherever you'd like, and you can also get Rhombus Guys pizza delivered for free since it's right next door. The taproom also serves local snacks such as Jen's Bread, pickled eggs from Fargo Brewing Company Ale House, Grandma G's Funükum, Maddie & Maize popcorn and more. BEST OVERALL ESTABLISHMENT 630 1st Ave. N, Fargo wurstfargo.com facebook.com/WurstBierHall *The public was asked to consider not only the food and/or drink quality of this establishment while nominating and voting, but also overall traits such as customer service, atmosphere, affordability, selection, etc. This award was open to any establishments in the dining industry. Good beer, good food and good vibes. It's safe to say that those are three things Würst Bier Hall has mastered that keep people coming back time and time again. This German beer hall has 41 craft beers on tap and a well-rounded food menu focusing on a variety of German classics such as sausages, bratwursts, sandwiches, burgers and local fan favorites such as the spaetzle mac & cheese and Establishment Features: • Rock and roll bingo every Wednesday at 9 p.m. • Trivia on Thursdays at 9 p.m. knoephla soup. Recently, Würst has also added spirits to their drink menu and has dived right in to offering tasty beertails (beer + liquor), mixed brews and cocktails. With a spaciously unique atmosphere and long communal tables lining the room, Würst has become one of the best places in town to gather with those who matter most to you. Whether you're stopping by for lunch, enjoying a beer over bingo or passing a famous boot full of beer around with your closest friends (following the rules of the boot, mind you), there's truly something for everyone to indulge in at this Fargo favorite. Bavarian Pretzels • American Craft Beer Week (May 1420) with tap takeovers • Patio seating • Oktoberfest (fall) and Maifest (spring) celebrations with special events and bar games Beer flight "Beerly Legal" (beertail) Cajun Chicken Ranch Grand Junction The Decoy Rustica Tavern Mary's Garden Shotgun Sally's Wings Old Broadway Sports Zone Baklava Cheesecake Santa Lucia Wheez The Juice Drekker Brewing Company Scotch Eggs Boiler Room Wings Tailgators Sports Cafe T M O IXO L GIS of the Month jason lundblad @ Urban 42 Kitchen & Bar 1635 42nd St. S, Fargo Inside the Delta Hotels by Marriott Fargo (Former Ramada) U rban 42’s general manager Jason Lundblad has over 20 years of experience in the bar and restaurant industry, so there’s no doubt you’ll get a quality cocktail from him every single time around. His recipe for a Chili Chocolate Martini is an impeccable blend of classic flavors with charming notes of cherry, chocolate and a spicy kick with every sip. We bet you’ll order more than one. BY Erica Rapp PHOTOS BY Paul Flessland 60 | MAY 2017 | FARGOMONTHLY.COM Q&A Can you tell us about your experience in the bar and restaurant industry? I started out working at the Fargo Country Club in 1994 busing tables. I eventually worked my way up to a server, to a bartender, to dining room supervisor and then eventually was the food and beverage manager for about three years as well. Then, I worked at the Holiday Inn in the Spirits Lounge as the beverage manager for about a year. I started here around 2015 in Basies as the beverage manager and was recently promoted a few weeks ago to the Urban 42 general manager. With Urban 42 being brand new to the public, what are you most excited about going forward? What I’m most excited about is our concept. We’re using fresh, local products and our cuisine is regional. It focuses on local ingredients. To me, it’s important to really promote Fargo-Moorhead and show people who come in from out of town–to really give them the opportunity to see how great it is from a food and beverage or culinary perspective. Can you tell us about the drink you made? The inspiration came from sampling the Kahlua Chili Chocolate Liqueur and we started to think of classic flavors that would pair well with that. Cherry, chocolate, chili–they all really go well together and it makes for a great after-dinner drink. It’s something that you can take your time with and really savor. Not everybody is a traditional cheesecake dessert-eater. Some people like to drink their dessert. It’s basic ingredients that people know about–basically just showcasing those ingredients and only those ingredients and not complicating it with anything more. What would you say is your personal style of cocktail making? Personally, I prefer to mix the simple, classic drinks but make them perfect. So, take two or three ingredients and making it perfect without focusing on trying to do too much. I believe in taking a classic cocktail and perfecting it by using fresh ingredients, the best products and the correct measurements. What’s a piece of advice you always stick to as a mixologist or bar manager? At the end of the day, the perfect cocktail is the one the customer orders. Don’t forget that we’re in the business of making the customer feel special and like they’re the center of attention, not the other way around. Chili Chocolate Martini • 1 ½ oz. Svedka Cherry Vodka • ½ oz. Kahlua Chili Chocolate Liqueur • ½ oz. Luxardo cherry juice • ½ oz. half & half Fill a shaker with ice and add all ingredients. Pour into a mixing glass and place shaker on top, then shake the mixture. Strain into a martini glass and garnish with two Luxardo cherries. 61 COMMUNITY SPOTLIGHT the fargo thesis F or: By Greg Tehven Photo by J. Alan Paul Photography Greg Tehven is an entrepreneur advocate and one of the original founders of Emerging Prairie. 62 | MAY 2017 | FARGOMONTHLY.COM "We are committed to believing in ourselves and our place, connecting friends and visitors and loving the heck out of it." cultural hub, highlighting his efforts to create a unique opportunity for visitors and locals to embrace local art. It takes all of us to believe our place is special. It isn't about being on someone's payroll to make change, it’s's work on the Community Activities Office has allowed the Prairie Den to become home to 140+ members and host over 100 events a year. The meet-up groups, from the Virtual Reality club to the Bit Coin. 63 spring HEALTH & WELLNESS SPOTLIGHT spring self-cleaning BY Kylee Seifert | PHOTOS BY Paul Flessland W hen the word spring comes to mind, words such as fresh, blossoming, awakening, invigorating and renewing follow close behind. After a long, cold winter, these words and the smells of spring are welcomed with open arms. I think we can all admit that our winter hibernation generally consists of heavy comfort foods, minimal vitamin D, limited fresh air, hiding under layers of bulky, warm clothes and that loving selfreminder that bikini season is still eons away. Now, it’s finally time to come out from under those layers and into the fresh blossoming of the new season. Season change is an ideal time to cleanse and detox, but spring cleaning doesn’t just have to mean cleaning out your closets and cupboards. Spring cleaning can be applied to your health, too. In fact, most of my clients find that “spring self-cleaning" is not only extremely beneficial, but essential. Here are some ways to invigorate yourself as you move into this new, beautiful season. Kylee is a certified personal trainer, certified primal nutrition coach, certified transformational coach and a health and wellness coach. She has been in the health and fitness industry for eight years and has become an established expert in the field. Her holistic business is centered around balancing fitness, nutrition and mindset mastery. 65 Swap Out Your Foods When I say “detox” I find myself treading lightly. Many associate the “d” word with cayenne pepper and honey cleansing or juicing into an oblivious state of starvation. This is far from the type of spring cleansing I encourage. Instead, swap out the heavy, warm comfort foods with fresh, cooling fruits and vegetables that are in season. Eating seasonal fruits and vegetables offers a host of benefits, including better flavor, higher nutritional content, lower price, more economically friendly and it encourages variety, to name a few. Abiding by nature’s natural rhythm helps keep us in better seasonal health. This is what is meant by nature’s rhythm: oranges are a winter yield that provides our bodies with vitamin C to help fight off colds and illnesses. Leafy greens are a spring produce to help us cleanse and alkalize our system moving out of the winter season and watermelon and cucumbers are a summer produce to help us stay cool and hydrated. Shop for in-season produce at Natural Grocers, Swanson’s Health Products, Prairie Roots Coop (coming soon) and The Red River Market (July-October). in-season produce for spring • Collard Greens • Garlic • Radishes • Spinach • Strawberries • Asparagus • Lettuce • Rhubarb • Apricots • Broccoli invigorate the body Stretching is extremely rejuvenating moving into the spring, especially after months of being cooped up inside. Here are some of the best stretches to welcome refreshing space into the body. Hindi Squat Take the feet just outside of the hips (this will vary depending on your hip mobility), and let the hips sink down toward the floor while keeping the heels flat on the ground. If this is too challenging and you find yourself struggling to balance, set your tailbone against a wall and perform the pose. Hindi Squat is perfect for opening up the hips after sitting inside during the winter months. defy gravity Winter can be a stressful season, given it is host to the holidays, colder temps and minimal sunshine, which limits our bodies production of vitamin D. A float tank is the perfect fix for some of the emotional and physical things we experience during the winter months, such as seasonal depression and low energy. Seated Spinal Twist Comfortably take a seat on your sit bones, lengthen one leg out front and cross the opposite foot over the lengthened thigh. Twisting from the belly button, twist toward your bent leg and hook your arm behind the knee. Switch to invigorate the other side as well. Twists energize the body and help to detoxify your organs– perfect for spring cleaning. FOR MORE INFORMATION Child’s Pose Begin with your knees apart (this will also depend on mobility), bring the feet together, let the head rest on the forehead and extend your arms overhead. Child’s Pose is the perfect pose for encouraging the body’s natural circulation. It also helps to alleviate stress. I like to gently move my head back and forth on my mat to give myself a small massage. Facebook: Kylee Seifert Wellness Coaching A float tank is a large tank filled with water close to the temperature of your body and high levels of Epsom salts, which is the magic floating ingredient. While in the tank, all sensories are cut off and you are left with stillness, silence and a state of complete peace. Float tanks have been said to stimulate the parasympathetic nervous system, which helps minimize and control stress, regulate the digestive system and re-energize the body and mind, among many other benefits. Where to float? FM Integrative is now home to Fargo-Moorhead’s healing float tanks. kyleeseifert.com Instagram: @kyleeseifert_wellness 67 TOPJOBS in our community Management TECHNICAL SUPPORT LEADER Fargo Pedigree Technologies is currently recruiting for an enthusiastic, high-energy, experienced technical support leader to provide guidance and oversight to its technical support team. OPERATIONS SUPERVISOR Fargo Ensure all terminal operations work is performed according to approved company procedures, standards and specifications; supervise all activities of terminal workers; and support personnel engaged in loading and unloading activities. Management SENIOR FINANCIAL REPORTING ANALYST West Fargo A team-based role, candidate must be able to perform accounting-policy review, participate in month-end close, and in the development and implementation of various policies and procedures related to IFRS reporting compliance while meeting various more info at SPOTLIGHTMEDIAFARGO.COM reporting requirements. ENGINEERING ASSISTANT West Fargo Partner with and provide support to engineering and environmental staff on current and future projects, perform administrative tasks of a technical nature related to specific projects, draft specific written report sections, and track project status and related contracts. WAREHOUSE SUPERVISOR Fargo Seeking an experienced warehouse supervisor to oversee all aspects of warehouse function. Requires a minimum of five years of supervisory experience in a warehouse capacity. Oversee all functions of receiving, shipping, warehouse organization and cleanliness, and customer service. Administrative ADMINISTRATIVE ASSISTANT Fargo Roers Property Management is seeking an administrative assistant to support its commercial and residential property management teams, tenants and vendors. This is not your typical administrative assistant position Digital Strategy Intern (Paid) Human Resources Spotlight Media TREASURY MANAGER Fargo The treasury manager analyzes and monitors the daily cash management function, treasury operations and treasury internal controls, and supervises cashmanagement personnel. HEAD OF HR & RECRUITING Fargo Lead efforts to grow their team past the 50 full-time employee mark while maintaining excellence in their environment and people management. Help develop, facilitate, and implement recruiting strategies that identify, attract, and secure top talent who fit CoSchedule’s culture and values. gofargojobs.com General KITCHEN & BATH DESIGNER & DESIGNER ASSISTANT Fargo Seeking both a designer and a design assistant. A qualified candidate for the kitchen & bath designer must have three years of experience in kitchen and bath design, with a working knowledge of the industry and products. Both candidates must be proficient with 20/20 Design software. Engineering SENIOR TEST ENGINEER Fargo Seeking a senior test engineer with a passion for test development. You must be a self-starter and ready to work independently and with the engineering team to ensure a quality product is provided to customers. OPERATIONS LEAD AVIATION ENGINEER & PROJECT MANAGER Responsible for day-to-day operations of a multifunctional research site. This individual is critical to research implementation and will have the opportunity to work with cutting-edge research equipment and superior genetic material and will help drive large-yield testing programs. Responsible for leading and managing the design and construction management for airport projects, including extension and reconstruction of runways; taxiways and aprons; fuel systems; and vertical infrastructure, including hangars, AD buildings, NAVAIDS and more. Fargo Fargo Marketing/Advertising CREATIVE DIRECTOR Fargo Manage an in-house creative team of writers, editors and designers; provide day-to-day leadership of the in-house team and oversee all creative aspects—art and copy—of integrated marketing projects from initial concept to production. SPORTS SOCIAL MEDIA SPECIALIST Fargo This role should be passionate about sports and athletics and will be responsible for developing social media and digital content strategies for SCHEELS pertaining to current sporting events, seasonal sports, and product trends and launches, which will drive engagement with their audience. Restaurant & Food ASSISTANT RESTAURANT MANAGER MARKETING COORDINATOR & WEB SPECIALIST Fargo The position of marketing coordinator will design, develop and implement digital and print communications for campaigns, advertising, website, social media and events. Fargo The assistant manager is responsible for a variety of areas, including achieving company objectives in sales, service, quality, appearance of facility, and sanitation and cleanliness through training of employees and creating a positive, productive working environment. MAY EVENT CALENDAR STAY UP TO DATE WITH WHAT’S GOING ON IN THE AREA. 1 MILLION CUPS CARRIE'S TWISTED ART Join the vibrant entrepreneurial community of Fargo-Moorhead and Emerging Prairie by participating in an event filled with guest speakers, plenty of coffee, ideas and excellent networking opportunities. These public classes are a great place to learn painting techniques of all different types while working with a variety of materials. With a fun learning atmosphere, you can create many things your heart desires at the cost of just $30 per person each class. Call 701-540-8712 to register, seating is limited. Every Wednesday from 9:15-10:15 a.m. 1millioncups.com/fargo The Stage at Island Park 333 4th St. S, Fargo Every Thursday from 7 9 p.m. carriestwistedart.com Carrie's Twisted Art Studios 300 Main Ave. Suite 110, Fargo TRANS MENTOR PROGRAM Every Saturday from noon-4 p.m. JOURNEYING THROUGH GRIEF May 4, 11 and 18 from 6-8 p.m. Journeying Through Grief is a threesession grief class for adults. The sessions focus on understanding the grief process, common grief reactions, taking care of yourself while grieving and embracing memories. This group is free and open to the public. Call 800-237-4629 or email bereavement@hrrv.org to register. FM REDHAWKS VS. ST. PAUL (HOME EXHIBITION) hrrv.org Hospice of the Red River Valley Monday, May 8 at 6 p.m. and Tuesday, May 9 at 11 a.m. 1701 38th St. S, Fargo fmredhawks.com Newman Outdoor Field 1515 15th Ave. N, Fargo WHAT DOES IT MEAN? SPORTS FAMILY COMMUNITY FOOD & DRINK A&E 73 FMCT'S "BILLY ELLIOT THE MUSICAL" "THE ODYSSEY" This Tony Award-winning Broadway hit is a Fargo-Moorhead Community Theatre main stage production about Billy, who recently lost his mother and wants to trade in his boxing gloves for a set of ballet slippers. Set during the mining strikes that took place in England under the politics of Margaret Thatcher, you'll follow Billy as he studies dance in secret with his sights set on the Royal Ballet School. NDSU's dramatic adaptation of Homer’s legendary, acclaimed playwright Mary Zimmerman brings the story of Odysseus’s 10-year journey to life. May 5, 6, 11, 12 and 13 at 7:30 p.m.; May 6, 7 and 14 at 2 p.m. fmct.org The Stage at Island Park 333 4th St. S, Fargo AIMEE KLEIN'S SKITS & TOMFOOLERY CO. PRESENT: "THE TRAVELING FAKE NEWS SHOW" May 4-6 at 7:30 p.m. What does one do in a world of "altnews"? Write a show about it! This local company is bringing you their third original sketch comedy show that includes skits, music and plenty of commercials. APT, a creative incubator 225 4th Ave. N, Fargo May 4-6 at 7:30 p.m. ndsu.edu/performingarts NDSU - Askanase Auditorium 1340 Administration Ave., Fargo NDSU BASEBALL VS. ORAL ROBERTS Friday, May 5 at 6:30 p.m.; Saturday and Sunday May 6 and 7 at 1 p.m. gobison.com Newman Outdoor Field 1515 15th Ave. N, Fargo CONCORDIA BASEBALL VS. ST. JOHN'S (MINN.) Saturday, May 6 at 1 and 3 p.m. gocobbers.com Concordia College - Jake Christiansen Stadium 901 8th St. S, Moorhead 13TH ANNUAL FARGO MARATHON May 15-20 Make a run for it as Fargo celebrates the 2017 SCHEELS Fargo Marathon over six days of events and races. Get your kids registered for the kids' race or run the relay, 5K, 10K, half marathon or full marathon. You and your pups can also run a race in the Furgo Dog Run, or you can participate in the cycling race if you prefer biking over running. If you're not participating, make your way to one of the routes and cheer on the community or stop by the Fargodome concourse to check out various vendor booths and keynote speakers. Race Schedules: MONDAY, MAY 15 • 6:30 p.m. - Cyclothon CELEBRATIONS TUESDAY, MAY 16 • 6:30 p.m. - Furgo Dog Run THURSDAY, MAY 18 • 5:30 p.m. - Youth Run participant line-up • 6:30 p.m. - Half-Mile Youth Run start • 7:00 p.m. - One-Mile Youth Run start FRIDAY, MAY 19 • 5:30 p.m. - 5K Run/Walk participant lineup and starting line announcements • 6:30 p.m. 5K Run/Walk start SATURDAY, MAY 20 • Fargodome opens for 10K, Half, Full and Relay participants • 7 a.m. - Full Marathon and Relay start • 7:15 a.m. - Half Marathon start • 7:30 a.m. - 10K start • Saturday, May 20 from 2-8 p.m. 27th Mile Downtown Fargo Pub Crawl, 6-11 p.m. outdoor live band concert downtown on NP Avenue *You can find information about registration/ packet pickup times, keynote speakers, expo happenings and more at the Fargo Marathon's website below. fargomarathon.com Fargodome and various locations 19TH ANNUAL KITE DAY CORKS & CANVAS "ROCKING TO THE OLDIES" Come and show off your kite flying skills at this free community event. Prizes will be awarded following the competition. For more information, call 701-499-6088.. This Silver Follies production will take you on a cruise back to the '40s and '50s with this swinging musical revue, which will feature hits that are sure to get you moving in your seat. Saturday, May 6 from 12:30-3 p.m. fargoparks.com Lindenwood Park 1712 5th St. S, Fargo DIAMOND IN THE RUFF SILENT AUCTION & RAFFLE Saturday, May 6 from 6-10 p.m. Diamond in the Ruff Pet Rescue is proud to hold its annual silent auction and raffle. Activities for the evening include a dinner, silent auction, raffle, door prizes, drinks, wine pull music and more. There will be a cash bar and ATM on site. Tickets should be purchased in advance. Visit Diamond in the Ruff's Facebook page to find the event and ticket links. facebook.com/DiamondInTheRuffPetRescue Red River Valley Fairgrounds (Hartl Ag Building) 1805 Main Ave. West, West Fargo Thursday, May 11 from 5-9 p.m. downtownfargo.com Downtown Fargo - Various Locations NDSU BASEBALL VS. ORAL ROBERTS Friday, May 12 at 6:30 p.m.; Saturday and Sunday May 13 and 14 at 1 p.m. gobison.com Newman Outdoor Field 1515 15th Ave. N, Fargo SUMMER GRIND Sunday, May 21 at 5 p.m. Beginner, intermediate and advanced skaters can demonstrate their individual skills during various exhibitions. Don't forget to wear your helmet. This event is free and registration starts at 4:30 p.m. May 18-21 fmct.org The Stage at Island Park 333 4th St. S, Fargo BUSINESS STARTUP SEMINAR Monday, May 22 from 5:30-6:30 p.m. Ted Stoa, a former KFC franchisee and financial-services business owner, is leading a free, hour-long seminar on starting a business. Stoa will help participants clarify their vision and mission, find the right business model, analyze the competition and develop a marketing plan. To register, contact Naomi Mitzelat at 701-451-4920 or NMitzel@TheVillageFamily.org thevillagefamily.org/events Village Family Service Center 1201 25th St. S, Fargo fargoparks.com Dike West 310 4th St. S, Fargo 75 WISH FAST VOL. 4: SUPERHERO 3, 5 & 10K WALK/RUN Saturday, May 6 from 8-11 a.m. Get ready to assemble with other heroes. Come dressed as your favorite hero and save the day from dastardly villains scattered throughout Lindenwood Park. Beat all the villains and help grant wishes faster for Make-A-Wish North Dakota. There will also be tons of great prizes. facebook.com/WishFast Lindenwood Park 1712 5th St. S, Fargo THE ART OF BUILDING AND MAINTAINING AUTHENTIC RELATIONSHIPS Tuesday, May 23 from 3:30-5 p.m. (Social 5-6 p.m.) Building strong relationships takes an investment of time, mutual respect and genuine interest. Building positive workplace relationships is essential for a successful career and it's rewarding on a personal level. An authentic relationship is based on respect and mutual trust and in the workplace, these qualities are essential for effective teamwork and collaboration. Come to this FMWF Chamber Women Connect session to hear from Tonya Stende, President of Dale Carnegie Business Group of ND; and Kristi Huber, President of United Way of Cass-Clay, and learn how to keep your interactions with others impactful and engaging. Cost is $25 in advance or $30 at the door for Chamber members and $35 in advance or $40 at the door for non-members. fmwfchamber.com Sanctuary Events Center 670 4th Ave. N, Fargo FMWF CHAMBER'S CORPORATE CUP Thursday, May 25 from 3:15-8 p.m. The Chamber's annual Corporate Cup is a series of competitive and recreational events that promote physical health and friendly competition within the local business community. Teams will battle for points in activities such as volleyball, an obstacle course, dodgeball, tug-of-war and much more. The event is open to all employees, companies and fitness levels and participation is open to all Chamber member businesses. fmwfchamber.com Minnesota State University Moorhead (MSUM) 1104 7th Ave. S, Moorhead THE CITY 94.5 PRESENTS: THE SHINS Sunday, May 21 at 7 p.m. The Shins are an American band formed in 1996. They have had multiple GRAMMY nominations and performed on Saturday Night Live. They are most known for their highest charting single, "Simple Song." The band recently released their fifth album in March and is supporting the album through this world tour. All ages are welcome. Tickets are $27. Doors open at 5 p.m. jadepresents.com Bluestem Amphitheater 801 50th Ave. S, Moorhead POST-TRAUMATIC FUNK SYNDROME'S TRIBUTE TO CHICAGO Friday, May 26 at 8 p.m. Fargo's most popular classic rock horn band–with six horns, keyboards, bass, drums, guitar, male and female vocals–will perform classic hits by the band Chicago and more. The band typically performs hits from artists such as the Blues Brothers, Genesis, Stevie Wonder, Phil Collins, James Brown, Earth Wind and Fire, Stevie Ray Vaughn, Billy Idol and much more. Doors open at 7 p.m. with a show time of 8 p.m. jadepresents.com Sanctuary Events Center 670 4th Ave. N, Fargo FM REDHAWKS VS. SIOUX CITY Monday, May 29 at 6 p.m.; Tuesday and Wednesday, May 30 and 31 at 7:02 p.m. fmredhawks.com Newman Outdoor Field 1515 15th Ave. N, Fargo "RENT" Tuesday, May 30 at 7:30 p.m. "Rent" is a Pulitzer Prize and Tony Award-winning show, returning to the stage for its 20th anniversary tour. The show follows seven artists following their dreams through struggles and fear. It centers around themes of hope, friendship and creativity, reminding the audience to measure life in love. Doors open at 6:30 p.m. Tickets are $61.50, $49 and $36.50. "Rent" contains adult material. fargodome.com Fargodome 1800 University Drive N, Fargo DOWN THE ROAD HAPPY HARRY'S RIBFEST June 7-10 from 11 a.m.-11 p.m. happyharrysribfest.com Fargodome 1800 University Drive N, Fargo LYNYRD SKYNYRD Friday, June 9 at 7:30 p.m. scheelsarena.com SCHEELS Arena 2017 DRONE FOCUS CONFERENCE Wednesday, May 31 at 8 a.m.-Thursday, June 1 at noon Curious about the world of autonomous vehicles and UAS? Looking to connect with other professionals in the industry? Join Emerging Prairie for the 3rd annual Drone Focus Conference. This conference is designed to serve as a platform for building your business, your knowledge and to simply get you in a room to network with fellow enthusiasts and learn more about what’s going on in our region. You’ll get to hear from industry professionals and have opportunities to interact with them, as this conference is all about connection. emergingprairie.com/dronefocusconference Fargo Civic Center 207 4th St. N, Fargo TONY BENNETT Thursday, June 1 at 7 p.m. American big band and traditional pop singer Tony Bennett has been on the front lines of every major issue impacting this country’s modern history. He has performed for eleven U.S. Presidents and is a World War II veteran and marched side-by-side with Dr. Martin Luther King in Selma to support civil rights. Throughout his life, Bennett has been a dedicated pacifist and proactive humanitarian selflessly supporting many causes whose goals benefit the lives of millions. His love for his country has earned him the recognition of a national treasure. jadepresents.com Bluestem Center for the Arts 801 50th Ave. S, Moorhead STEP UP FOR NF WALK Saturday, June 3 at 8 a.m. Neurofibromatosis is a progressive and unpredictable disorder that attacks any and/or every function of the body, and there is no cure. This walk will help raise funds, support the local NF community and enable NF Upper Midwest to host informational forums on relevant topics, sponsor kids to go to NF camps, award grants, offer financial assistance and more. nfuppermidwest.org Lindenwood Park (Main Shelter) 1712 5th St. S, Fargo 5225 31st Ave. S, Fargo 2017 RED RIVER VALLEY FAIR July 11-16 redrivervalleyfair.com Red River Valley Fairgrounds 1805 Main Ave. West, West Fargo 42ND ANNUAL DOWNTOWN FARGO STREET FAIR July 13-15 downtownfargo.com Downtown Fargo FARGO MONTHLY'S BURGERS, BBQ AND BEER FESTIVAL Thursday, June 15 from 5-10 p.m. burgerfestfargo.com Moorhead Center Mall - Parking Ramp TROLLWOOD PERFORMING ART SCHOOL'S MAINSTAGE MUSICAL: "BEAUTY & THE BEAST" July 14, 15, 18-22, 25-29 trollwood.org Bluestem Center for the Arts 801 50th Ave. S, Moorhead EVERCLEAR "SO MUCH FOR THE AFTERGLOW" 20TH ANNIVERSARY TOUR WITH VERTICAL HORIZON AND FASTBALL Saturday, June 17 at 6 p.m. jadepresents.com Bluestem Center for the Arts 801 50th Ave. SW, Moorhead GHOST - "THE POPESTAR TOUR" Saturday, June 17 at 8 p.m. jadepresents.com Fargo Civic Center 207 4th St. N, Fargo GOO GOO DOLLS "LONG WAY HOME SUMMER TOUR" WITH PHILLIP PHILLIPS Thursday, July 20 at 7:30 p.m. scheelsarena.com SCHEELS Arena 5225 31st Ave. S, Fargo BRUNO MARS "24K MAGIC WORLD TOUR" Friday, August 4 at 8 p.m. fargodome.com Fargodome 1800 University Drive S, Fargo LISTEN TO THE MUSIC STAY ON THE SCENE WITH OUR GUIDE TO FARGO-MOORHEAD’S LOCAL MUSIC. MAY 1ST - 6TH MONDAY, MAY 1 Jon Walters - Junkyard Brewing Company Open Mic Night with CMPTRDSTR Front Street Taproom TUESDAY, MAY 2 Beach Slag with GALS and Crab Legs - The Aquarium The Cropdusters - Junkyard Brewing Company Lucas Hranicka (Patio Party) - Shotgun Sally's WEDNESDAY, MAY 3 Ditching Delmer - Bar Nine Warren Christensen - Junkyard Brewing Company THURSDAY, MAY 4 Sam Outlaw with Michaela Anne - The Aquarium Mick Klein and Karli Moch - Blvd Pub Warren Christensen - Front Street Taproom The Bizness (formerly The Blue Band) - HoDo Lounge Anthony Chaput - Junkyard Brewing Company The Cropdusters - Proof Chas Collins - The Windbreak FRIDAY, MAY 5 The Human Element "Forward Motion" album release - The Aquarium davis? - Dempsey's Lacey Guck - Front Street Taproom Lonesome Dan Kase - Junkyard Brewing Company Downtown Sound - Pickled Parrot Twice as Hard - Rick's Bar Dakota Dirt - Speck's Bar October Road - Shotgun Sally's Road Trip Radio - VFW: Downtown Skyline - The Windbreak SATURDAY, MAY 6 Crab Legs, Pisstory, Polly the Panelist - The Aquarium Deb Jenkins Band - Dempsey's Dose Amigos - Front Street Taproom Maiden Minneapolis (tribute to Iron Maiden) - Garage Bar Low Standards - JC Chumley's Eddie Danger - Junkyard Brewing Company Downtown Sound - Pickled Parrot Twice as Hard - Rick's Bar Dakota Dirt - Speck's Bar High Five - Sidestreet Rhyme or Reason - Shotgun Sally's Road Trip Radio - VFW: Downtown 32 Below - The Windbreak MAY 7TH - 13TH SUNDAY, MAY 7 Real Dom and Salad - The Aquarium 80 | MAY 2017 | FARGOMONTHLY.COM 5th Annual Bar Nine Acoustic Fest Bar Nine Beer & Hymns with Fargo Faith United Methodist Church - Junkyard Brewing Company Open Mic Night with Jam Band - The Windbreak MONDAY, MAY 8 Zach Thomas - Flatland Brewery Open Mic Night with CMPTRDSTR Front Street Taproom Jessica Vines & Connor Lee - Junkyard Brewing Company TUESDAY, MAY 9 Big Eyes and Shovels, Pisstory, Still, Freddy Glove - The Aquarium Snoozy Moon - Garage Bar Friends & Neighbors Bluegrass Band - Junkyard Brewing Company The Vinegar Strokes (Patio Party) Shotgun Sally's WEDNESDAY, MAY 10 Jan Severson - Junkyard Brewing Company The Jeffertons with What Kingswood Needs, Triple Deke, Rounding Third The Red Raven THURSDAY, MAY 11 Matty J - Front Street Taproom Ian Alexy and The Deserters - HoDo Lounge Tom Peckskamp - Junkyard Brewing Company Anthony Chaput - Proof Redline - The Windbreak FRIDAY, MAY 12 Volumes with Fire From The Gods, Glass Houses, Sequences (early show) - The Aquarium Earth Rhythms pre-party with Trebellion, Trufeelz, TATR, Jordash, Darwins Theory (late show) - The Aquarium Poitin - Dempsey's Brothers Bertrand - Front Street Taproom Nathan Pitcher - Junkyard Brewing Company FM All Stars - Pickled Parrot Double Forte - Rick's Bar Social Disorder - Speck's Bar Unleashed - Shotgun Sally's Front Fenders - VFW: Downtown Redline - The Windbreak SATURDAY, MAY 13 Jaedyn James and the Hunger Dempsey's Dan Christianson - Front Street Taproom Mad Alice (tribute to Alice In Chains and Mad Season) - Garage Bar DJ Morplay - Junkyard Brewing Company FM All-Stars - Pickled Parrot Double Forte - Rick's Bar Social Disorder - Speck's Bar Deb Jenkins Band - Sidestreet 8th Hour - Shotgun Sally's Front Fenders - VFW: Downtown Some Sh*tty Cover Band - The Windbreak MAY 14TH - 20TH SUNDAY, MAY 14 Beer & Hymns with Good Shepherd Band - Junkyard Brewing Company Open Mic Night with Jam Band The Windbreak MONDAY, MAY 15 Open Mic Night with CMPTRDSTR Front Street Taproom Sam Larson - Junkyard Brewing Company TUESDAY, MAY 16 The Cropdusters - Junkyard Brewing Company Mick Klein (Patio Party) - Shotgun Sally's WEDNESDAY, MAY 17 The Vinegar Strokes - Bar Nine Pat Lenertz - Junkyard Brewing Company THURSDAY, MAY 18 The Cropdusters - Front Street Taproom Dead Horse Trauma with Anomic and Shotgun Facelift - Garage Bar Reina del Cid - HoDo Lounge The Lollygaggers - Junkyard Brewing Company Steve Marquart - Proof The Roosters - The Windbreak FRIDAY, MAY 19 Samothrace with He Whose Ox is Gored - The Aquarium Heavy is the Head - Dempsey's Eric Jacobson - Front Street Taproom Young Medicine - Garage Bar Johnny Azari - Junkyard Brewing Company Skyline - Pickled Parrot Pretty Tricky - Rick's Bar Mick $ Rich (bike night kickoff party) - Speck's Bar Pasadena '68, Dakota Shakedown, Michael Pink - Sidestreet The Steele River Band - Shotgun Sally's Thunder Ridge - VFW: Downtown Pop Rocks - The Windbreak SATURDAY, MAY 20 PhaseOne - The Aquarium Reina del Cid - Dempsey's Jon Walters - Front Street Taproom Mix Theory - Garage Bar Johnny Azari - Junkyard Brewing Company Skyline - Pickled Parrot Pretty Tricky - Rick's Bar Mick $ Rich (bike night kickoff party) - Speck's Bar The Steele River Band - Shotgun Sally's Thunder Ridge - VFW: Downtown Dirty Word - The Windbreak MAY 21ST - 27TH SUNDAY, MAY 21 Open Mic Night with Jam Band The Windbreak Beer & Hymns with Kwaician Junkyard Brewing Company Spikefest - Rick's Bar MONDAY, MAY 22 Open Mic Night with CMPTRDSTR Front Street Taproom D Mills - Junkyard Brewing Company TUESDAY, MAY 23 Seth Holden's Birthday featuring The Newlyweds and The Human Element The Aquarium The Cropdusters - Junkyard Brewing Company Lars and Joe Pony Show (Patio Party) - Shotgun Sally's WEDNESDAY, MAY 24 Lars and Joe Pony Show - Bar Nine Gina Powers Band - Dempsey's Pat Lenertz - Junkyard Brewing Company THURSDAY, MAY 25 Lung with Velveteen and Kwaician The Aquarium Nick Wood - Front Street Taproom A Tribute to Ryan Adams - HoDo Lounge The Vinegar Strokes - JC Chumley's Tristan Larson - Junkyard Brewing Company Guys & Dahls - Proof October Road - The Windbreak FRIDAY, MAY 26 Radio Free Fargo 95.9 presents Locals On The 8 Fest - The Aquarium Rabbits on the Run - Dempsey's Tucker'd Out - Front Street Taproom Matty J - Junkyard Brewing Company Uptown Live - Pickled Parrot The Roosters - Shotgun Sally's The Groovetones - VFW: Downtown October Road - The Windbreak SATURDAY, MAY 27 Darkrad/DJ JanaDark Industrial Dance Party - The Aquarium Confusion - Dempsey's Chris Holm - Junkyard Brewing Company Uptown Live - Pickled Parrot Smoking Gun - Speck's Bar Downtown Sound - Shotgun Sally's The Groovetones - VFW: Downtown Rhyme or Reason - The Windbreak MAY 28TH - 31ST SUNDAY, MAY 28 Beer & Hymns with Ambience Junkyard Brewing Company 32 Below - Shotgun Sally's Smoking Gun - Speck's Bar MONDAY, MAY 29 Open Mic Night with CMPTRDSTR Front Street Taproom Dan Christianson - Junkyard Brewing Company TUESDAY, MAY 30 The Cropdusters - Junkyard Brewing Company Zach Thomas (Patio Party) - Shotgun Sally's WEDNESDAY, MAY 31 Shaun Mitzel - Bar Nine Tucker'd Out - Junkyard Brewing Company LOCAL MUSIC VENUES THE AQUARIUM GARAGE BAR RICK'S BAR BAR NINE THE HODO LOUNGE SHOTGUN SALLY’S BLVD PUB JC CHUMLEY’S SIDESTREET GRILLE & PUB DEMPSEY’S JUNKYARD BREWING COMPANY SPECK’S BAR FLATLAND BREWERY PICKLED PARROT VFW: DOWNTOWN FRONT STREET TAPROOM PROOF ARTISAN DISTILLERS THE WINDBREAK 226 Broadway N, Fargo (Above Dempsey's) 1405 Prairie Parkway, West Fargo 3147 Blustem Drive, West Fargo 226 Broadway N, Fargo 3140 Bluestem Drive, West Fargo 614 Main Ave., Fargo 3108 9th St. S, Moorhead 101 Broadway N, Fargo 1608 Main Ave., Moorhead 1416 1st Ave. N, Moorhead 505 3rd Ave. N, Fargo 414 4th Ave. N, Fargo THE RED RAVEN 916 Main Ave., Fargo 2721 Main Ave., Fargo 1515 42nd St. S, Fargo 404 4th Ave. N, Fargo 2611 Main Ave., Fargo 202 Broadway N, Fargo 3150 39th St. S, Fargo TRIVIA TEST YOUR KNOWLEDGE WITH GENERAL OR THEMED TRIVIA AT SOME OF YOUR FAVORITE AREA BARS AND RESTAURANTS. MONDAYS TUESDAYS WEDNESDAYS THURSDAYS Three Lyons Pub Fargo Billiards and Gastropub Drekker Brewing Company Hennessy's Irish Pub 8 p.m. 6 p.m. 675 13th Ave. E, West Fargo 8 p.m. 3234 43rd St. S, Fargo 7:30 p.m. 8 p.m. Rhombus Guys Pizza 606 Main Ave., Fargo 8:30 p.m. Town Hall Bar 103 Main Ave. W, West Fargo 2nd - "The Office" trivia 9th - "Labyrinth" trivia 16th - Baseball trivia 23rd - "Dumb & Dumber" trivia 30th - Disney trivia 9 p.m. JC Chumley's 1608 Main Ave., Moorhead Sidestreet Grille & Pub 404 4th Ave. N, Fargo 630 1st Ave. N, Fargo Work Zone 701 Main Ave. E, West Fargo 7 p.m. Herd & Horns 1414 12th Ave. N, Fargo 7 p.m. Fargo Brewing Ale House 4445 17th Ave. S, Fargo 8 p.m. 2nd - "Hamilton" The Musical Trivia 9th - "Labyrinth" trivia 16th - Baseball trivia 23rd - "Dumb & Dumber" trivia 30th - Disney trivia 8 p.m. Bomb Shelter 4323 45th St. S, Fargo OB Sports Zone 22 Broadway N, Fargo 8:30 p.m. Dave's Southside Tap 803 Belsly Blvd., Moorhead 7 p.m. The Silver Dollar Bar & The Flying Pig Grill 221 Sheyenne St., West Fargo 7 p.m. Fargo Brewing Company Vic's Lounge 420 Center Ave., Moorhead 7 p.m. Tailgators Sports Cafe 1322 Main Ave., Fargo 6:30 p.m. 325 10th St. N, Fargo 7 p.m. FRIDAYS Three Lyons Pub 675 13th Ave. E, West Fargo 8 p.m. The Bowler 2630 University Drive S, Fargo 8 p.m. Pickled Parrot West 1410 9th St. E, West Fargo 7 p.m. 610 University Drive N, Fargo 7 p.m. Labby's Grill & Bar 1100 19th Ave. N, Fargo 9 p.m. VFW: Downtown Fargo 202 Broadway N, Fargo Red Hen Taphouse 1710 Center Ave. E, Dilworth 7 p.m. 7 p.m. Flatland Brewery 3140 Bluestem Drive #105, West Fargo 7 p.m. Pounds 612 1st Ave. N, Fargo 8 p.m. Pickled Parrot West 1410 9th St. E, West Fargo 7 p.m. Hooligan's Bar & Grill 3330 Sheyenne St., West Fargo Front Street Taproom 614 Main Ave., Fargo 7 p.m. 8:30 p.m. 3rd - "Seinfeld" trivia 10th - "House MD" trivia 17th - "Law & Order: SVU" trivia 24th - "Titanic" trivia 31st - "Futurama" trivia Pepper's Sports Cafe 2510 University Drive S, Fargo 8 p.m. 83 DRINKSPECIALS FARGO Acapulco 1150 36th St. S, 3:30-5:30pm half 3:30-5:30pm half 3:30-5:30pm half 3:30-5:30pm half 3:30-5:30pm half 3:30-5:30pm half off Margaritas, off Margaritas, off Margaritas, off Margaritas, off Margaritas, off Margaritas, $3 Sangrias, $3 $3 Sangrias, $3 $3 Sangrias, $3 $3 Sangrias, $3 $3 Sangrias, $3 $3 Sangrias, $3 Barbacoa bottles of beer and bottles of beer and bottles of beer and bottles of beer and bottles of beer and bottles of beer and 3241 42nd St. S, $3 off all glasses $3 off all glasses $3 off all glasses $3 off all glasses $3 off all glasses $3 off all glasses Fargo of wine, half off of wine, half off of wine, half off of wine, half off of wine, half off of wine, half off everything behind everything behind everything behind everything behind everything behind everything behind the bar after 9pm the bar after 9pm the bar after 9pm the bar after 9pm the bar after 9pm the bar after 9pm 3:30-5:30pm half off Margaritas, $3 Sangrias, $3 bottles of beer and $3 off all glasses of wine, half off everything behind the bar after 9pm Mug Night 8-11pm: $3 mug, $2 refills, $5 refills 11pmclose 50¢ taps, $1 Captain Morgan and teas 8pmmidnight 2-or-1 domestic bottles, Jack and Jack Honey 8pm-midnight $2 tall taps $2 Captain Morgan $2 bomb shots 8-11pm $2 tall taps $2 Captain Morgan $2 bomb shots 8-11pm The Bowler 2630 University Drive S, Fargo (Inside the Fargo Inn & Suites) Happy Hour 4-7pm: drinks as low as 50¢, $2 domestic bottles 9-11pm Happy Hour 4-7pm: drinks as low as 50¢, $3 Bulliet Bourbon & Rye and $10 buckets of domestic beer 9-11pm Happy Hour 4-7pm: drinks as low as 50¢, pull tab Happy Hour replay 9-11pm Happy Hour 4-7pm: drinks as low as 50¢, $3 Captain Morgan and Seagrams 7 9-11pm Happy Hour 4-7pm: drinks as low as 50¢, $3 Windsor and Ketel One Vodka 9-11pm Happy Hour 4-7pm: drinks as low as 50¢, $3.50 Crown Royal/ Crown Royal Apple and Ciroc 9-11pm Happy Hour 4-7pm: drinks as low as 50¢, $3.50 domestic pitcher and $3 Tanqueray 9-11pmondays: $5.95 New Mug & $3.95 Refills $1 off taps and wells 8pm-close Big Mug Wednesdays: $5.95 New Mug & $3.95 Refills, $2.95 Morgans 50 cent Busch Light taps 8pm-close Domestic beer and a shot For $7, Old School Teas and Stumplifters $2.95 $2.95 Bloody Marys and Caesars 8amnoon, $3.25 Jack Daniel’s, $2.95 PBR pounders Sunday Funday: $1 off drinks in your Chub's sweatshirt Dempsey’s 226 Broadway N, Fargo Happy Hour drink specials 4pm-close The Bismarck Tavern * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. The Box 1025 38th St. SW, Fargo 85 D’Woods Lounge 3333 13th Ave. S, Fargo Doolittles Woodfire Grill 2112 25th St. S, Fargo Empire 424 Broadway N, Fargo MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY $2.75 domestic bottles, $3 Bacardi $2.75 domestic bottles, $1 off Martinis $3.50 Stoli and domestic taps $3.50 Crown Royal and taps $3.75 teas, $3 Windsor $3 Smirnoff and Captain Morgan Half off all bottles of wine 4-11pm, Happy Hour 3-6pm and 9pm-close: $1 off all tap and bottled beer, cocktails and wine by the glass $2 off Beer flights 3-9 pm, Happy Hour 3-6pm and 9pmclose: $1 off all tap and bottled beer, cocktails and wine by the glass $2 off Crafted cocktails 3-9pm, Happy Hour 3-6pm and 9pmclose: $1 off all tap and bottled beer, cocktails and wine by the glass $3 off wine flights 3-9pm, Happy Hour 3-6pm and 9pmclose: $1 off all from 4-6pm $4 pints from 4-6pm $4 pints from 4-6pm $4 pints from 4-6pm $4 Bloody Marys 2-6pm, $3.50 Chuck Norris, $3.50 rum all day, $2 wells and domestic bottles 8-10pm Happy Hour 4-7pm All specials from the week apply (excludes $2 wells and domestics) $5 build-yourown Bloody Mary or Mimosa bar 11am-4pm $5 build-yourown Bloody Mary or Mimosa bar 11am-4pm, all day Happy Hour, half price tap beer all day $2 Green Cup Fills $1 PBR Pounders & $2 Green Cup fills (22oz. of beer in a Green Golf Addiction Cup) Fargo Brewing Company 610 University Drive N, Fargo $15 bucket of beers (any 5 $2.50 tap beers beers), $4.50 all day (use Long Island Teas mugs), Happy and Margaritas, Hour 4-7pm: $1 Happy Hour off all taps, wells 4-7pm: $1 off all and domestic taps, wells and bottles domestic bottles $3 select whiskey, $3 import and domestic microbrew bottles all day, Happy Hour 4-7pm Happy Hour all day: $1 off all taps, wells and domestic bottles $3.50 Stoli, Goldschlager and Icehole, $2 wells and domestic bottles 8-10pm, Happy Hour 4-7pm Happy Hour 4-6pm and 9pm-midnight: $1 off spirits, wine and beer Happy Hour 4-6pm and 9pm-midnight: $1 off spirits, wine and beer and half price wine glasses and bottles Happy Hour 4-6pm and 9pm-midnight: Herd and Horns 1414 12th Ave. N, Fargo All day Happy Hour: $2 off appetizers and $1 off drinks $3 Busch Light and PBR pounders, $3 Bud and Bud Light 16oz. drafts from 7pm-close Mug Night 7pm-close: $5.75 mugs with $3.75 domestic tap fills, $2 upcharge for craft Tea Night: $3.50 16oz. teas Happy Hour 3-6pm: $1 off pints Happy Hour 3-6pm: $1 off pints Happy Hour 3-6pm: $1 off pints, Super Awesome Funtime Game Night from 7-9pm Happy Hour 3-6pm: $1 off pints $3.95 32oz. mugs 8pm-close F&F Poor Boy pounders $2.95/$3.25 $1 off all bottles and drinks 9pmclose $3.95 Mimosas, Screwdrivers & Bloody Marys 11am-3pm, $1 off bottles & drinks 9pm-close Fort Noks Bar of Gold 52 Broadway N, Fargo * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. Frank’s Lounge 2640 52nd Ave. S, Fargo Front Street Taproom 614 Main Ave., Fargo Golf Addiction 4474 23rd Ave. S, Fargo Kilstone Brewing 764 34th St. N, Fargo Labby’s Grill & Bar $12.50 buckets of beer all day 1100 19th Ave. N, Fargo 86 | MAY 2017 | FARGOMONTHLY.COM $3.50 jumbo teas, $5.25 top shelf all day SUNDAY Bottomless Mimosas noon-5pm for $7.99 NFL Special: $15.50 bucket of pounders MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY Lucky’s 13 Pub 4301 17th Ave. S, Fargo $2.25 short domestic beers $3 Coronas, Corona Lights and Dos Equis Ambar 3pmclose $3.50 tall domestic taps 3pm-close Half price bottles of wine, $2.50 PBR and Hamms Pounders 3pmclose Happy Hour 3-6pm 9am-4pm $3 Mimosas and $6.75 BLT Bloody Marys Happy Hour all day, $1.25 off all drinks and $3 Mimosas Luna Fargo 1545 University Drive S, Fargo ½ price tap beers, wine by the glass & cheese plates Mezzaluna 309 Roberts St. N, Fargo bottle of glass of wine and get the 2nd for a penny Bucket Special 4pm-close: Barcardi White, Limón or Black Razz $3 UV Vodka $3 Bloody Marys and Caesars with UV Vodka until 4pm Pay The Day Taps 8-10pm College Night $2.75 select drinks 9-11pm $1 you-call-its 7-9pm O’Kelly’s 3800 Main Ave., Fargo Old Broadway City Club 22 Broadway N, Fargo * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. Old Broadway Grill 22 Broadway N, Fargo OB Sport Zone 22 Broadway N, Fargo $2.95 Bloody Marys, Mimosas, Skip-N-Go Naked 11am-2pm Wine Club Night from 4-10pm $5.95 domestic pitchers 6-10pm, Happy Hour 3-6pm: 2-for-1 drinks Happy Hour 3-6pm: 2-for-1 drinks Pickled Parrot 505 3rd Ave. N, Fargo Happy Hour 3-6pm: 2-for-1 drinks Happy Hour 3-6pm with 2-for-1 drinks, College Night: $2.75 select drinks 9-11pm $2.95 Bloody Marys/Mimosas & select drinks 11am-2 pm, College Night $2.75 select drinks 9-11pm $2 wells & domestic taps 7-11pm, $3 Captain Morgan, $5 domestic jars $2 wells and domestic taps 7-11pm, $3 domestic bottles and Ice Hole, $8 well jars $2 well drinks& domestic taps 7-10pm, $3 Fireball, $4 Crown Royal, $5 jars $2 wells & domestic taps 7-10pm, $4 Jack Daniel's, Long Islands & Chuck Norris, $5 jars Happy Hour 3-6pm and 6-10pm: 2-for-1 drinks Pounds 6 12 1st Ave. N, Fargo Radisson (Lobby Bar) 201 5th St. N. Fargo Martini Monday: $2 off all martinis Top Shelf Tuesday: $2 off all top shelf liquors Wine Wednesday: $2 off all glasses of wine and half price bottles Tap Thursday: $3 crafts and imports, $2 domestics and $1 off taps Rhombus Guys 606 Main Ave., Fargo Happy Hour 3-6pm and 10pm-close: -close $4 pints of Rhombus beer starting at 9pm, Happy Hour 3-6pm and 10pm-close $3 Deep Eddy Vodka starting at 8pm, Happy Hour 3-6pm and 10pm-close $4 craft beer pints and 2-for-1 wells starting at 9pm Porter Creek Hardwood Grill 1 555 44th St. S, Fargo 88 | MAY 2017 | FARGOMONTHLY.COM Happy Hour all day Happy Hour 3-6pm and 9pm-close: $1 off cocktails, beer and wine Bloody Mary Bar 11am-4 pm, $5 well vodka, $6 premium vodka, $3 youcall-its for service industry all day * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY $3.35 tall domestic taps all day $2.75 well drinks 4:30pm-close Rooter’s Bar 107 Broadway N, Fargo $2 12oz. dometic The Round Up Saloon 4501 Urban Plains Drive, Fargo Jameson, Absolut and Deep Eddy drinks 4pmclose $3 tall domestics and $5 tall crafts 6pm-midnight, $2 off Patron 9pm-close Half price bottles of wine 4pm-close Mug & Game Night 9pm-midnight: $5 entry with $2 refills on wells and domestic taps, requests from DJ Bingham $3 you-call-its on wells and domestic bottles 9-11pm $7 Bottomless Brunch Barrels 11am-2pm $7 Bottomless Brunch Barrels 11am-2pm, Industry Night: $3 top shelf, $2 calls, $1 wells Sickie's Garage 3431 Fiechtner Drive S, Fargo $2 Sailer Jerry and Absolut, $3 Jack Daniel's and Redbull shots, Happy Hour 3-6pm and 9-11pm: $2.50 domestic taps and wells Big 98.7 Happy Hour 4-6pm with 98¢ domestic taps, Q105 $1.05 drink tickets 7-9pm, $2 Sailer Jerry and Absolut, $3 Jack Daniel's and Redbull shots Rock 701 $1.07 drink tickets 5-7pm, $2 Sailer Jerry and Absolut, $3 Jack Daniel's and Redbull shots $2 Sailer Jerry and Absolut, $3 Jack Daniel's and Redbull shots, Happy Hour 3-6pm and 9-11pm: $2.50 domestic taps and wells $2 Sailer Jerry and Absolut, $3 Jack Daniel's and Redbull shots, Happy Hour 3-6pm and 9-11pm: $2.50 domestic taps and wells Happy Hour 3-6pm: $2.50 domestic taps and wells Happy Hour 3-6pm and 9-11pm: $2.50 domestic taps and wells Slammer’s Sports Bar & Grill 707 28th Ave. N, Fargo domestic bottles and Captain Morgans 6-10pm: $8 domestic pitchers, $2.50 Schnapps shot, $2.75 well drinks 6-10pm: $3.50 import bottles and Gator Teas, $2.50 Schnapps shots 6-10pm: $3 Bacardi, $3 Chuck Norris and Jag Bombs, $2.75 Windsor Noon-10pm: $3.25 domestic pints and bottles, $3.25 Wonder Woman shots, $3.99 Bloody Marys, $1 off whiskey Noon-10pm: $3.25 domestic pints and bottles, $3.25 Wonder Woman shots, $3.99 Bloody Marys, $1 off whiskey $2 off everything 3-6pm, all drinks half price after 9pm All drinks half price after 9pm Twist 220 Broadway N, Fargo 91 MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY $3 Captain Morgan $6 domestic pitchers $3 Windsor $3 domestic pounders and bottles $3 teas Happy Hour 11am-5pm Happy Hour all day Vinyl Taco 520 1st Ave. N, Fargo $2 off jumbo 32oz. Margaritas $2 PBR pounders, $1 off Almond-Ritas $1 off Padre’s Root Beer Float $2 off all tequila shots $1 off Cadillac Margaritas, $2 Margaritas 9pm-close $1 off Lavender Lemonades, $1 off Sangria, $2 Margaritas 9pm-close The Windbreak 3150 39th St. S, Fargo $1 off drinks 4-7pm and 9-11pm, 32oz. Captain Morgan pitchers for $10 all day $1 off drinks 4-7pm and 9-11pm, 32oz Captain Morgan pitchers for $10 all day $1 off drinks 4-7pm and 9-11pm, 32oz Captain Morgan pitchers for $10 all day Ladies Night: Ladies drink free 9pm-midnight, Guys $2.50 from 9-11pm, $2 select bomb shots 9-11pm $2 drinks 4-7pm and 9-11pm, $2 select bombs shots 9-11pm VFW: Downtown 202 Broadway N, Fargo $1 off drinks 4-7pm, 2-for-1s 9pm-midnight WEST FARGO * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. Bar Nine 1405 Prairie Pkwy., West Fargo $3.50 tall domestics, Stoli and Jack Daniel's $1 off all taps and bottled beers Mug Night: $5 purchase and $4 refills on domestics and wells Blarney Stone 1910 9th St. E, West Fargo Happy Hour 3-6pm and 9pm-close, $1 off drafts, $1 off bar pours, $1 off house wines VIP Day: Mug club members get an extra $1 off discounted beer, Happy Hour 3-6pm and 9pm-close Irish Trash Can Wednesday: $4.50 Irish Trash Cans 5pmmidnight VIP Day: Mug club members get an extra $1 off discounted beer, Happy Hour 3-6pm and 9pm-close Happy Hour 3-6pm and 9pm-close, $1 off drafts, $1 off bar pours, $1 off house wines Free trip through the Bloody Mary bar or free mimosa with purchase of breakfast entrée, Happy Hour 9pm-close Happy Hour all day, VIP Day, free trip through the Bloody Mary bar or free Mimosa with purchase of breakfast entrée Blvd Pub 3147 Bluestem Drive, West Fargo Tall beers for the price of a short 6pm-midnight, Happy Hour 3-6pm: $1 off tall beers, well drinks, Captain Morgan, Bacardi and glasses of wine 2-for-1 domestic $2.95 Long Island pints, wells and Teas (all flavors) Captain Morgan 6pm-close, Happy 6pm-close, Happy Hour 3-6pm: $1 Hour 3-6pm: $1 off tall beers, well off tall beers, well drinks, Captain drinks, Captain Morgan, Bacardi Morgan, Bacardi and glasses of and glasses of wine wine Ladies Night: Half off bottles of wine 6pmmidnight, $2 wells, $3 calls, $4 talls 8pmmidnight, Happy Hour 3-6pm $2 wells, $3 calls, $4 tall beers 10pm-1am, Happy Hour 3-6pm: $1 off tall beers, well drinks, Captain Morgan, Bacardi and glasses of wine $1.95 wells, calls and pints 10-11pm, $2.95 wells, calls and pints 11pm1am, $3 Bloody Marys, Caesars and Mimosas 9am-noon $3.50 22oz. domestic beers Hooligans 3330 Sheyenne St, West Fargo $2.50 domestic bottles all day $3 Captain Morgan, domestic bottles, Bloody Marys and Caesars all day Pickled Parrot West 1410 9th St. E, West Fargo Pub West 3140 Bluestem Drive, West Fargo $3.50 tall domestic beer, $4.50 tall craft beer Rookies 715 13th Ave. E, West Fargo Silver Dollar Flying Pig 221 Sheyenne St, West Fargo Happy Hour 4:30-6:30pm Happy Hour Speedway 4-7pm: $3 25oz. Steakhouse domestic beers; $2 16oz domestic 680 Main Ave. beers, rail drinks W, West Fargo and domestic bottles 92 | MAY 2017 | FARGOMONTHLY.COM $3 domestic talls all day $3.50 well Margaritas, $3 Corona and Dos Equis $2.50 Morgans and Bacardi all day $3 well drinks 7pm-close $3 bomb shots 8pm-midnight $5 Martinis, $3 Jack Daniel's, $5 domestic jars, open-close: $3 Fireball, Ice Hole and PBR pounders Ladies Night open-close: 2-for-1 glasses of wine, $2 wells & domestic pints, $3 Crown Royal, $3 domestic bottles, $3 Fireball, Ice Hole and PBR pounders 2-for-1 rum drinks, $4 Parrot Punch, $7 craft jars, open-close: $3 Fireball, Ice Hole and PBR pounders $4 Jameson and Water Moccasins, $6 domestic jars, open-close: $3 Fireball, Ice Hole and PBR pounders $3 Tito's Vodka and Bacardi, $4 craft bottles and WuTangs, open-close: $3 Fireball, Ice Hole and PBR pounders $3 Jag and Jack Daniel's, $7.50 Miller Lite Pitchers $3 Windsor, Canadian Club, Jack Daniel's, $14 bucket of domestic beers $3 Captain Morgan, Bacardi and domestic bottles $3.50 bomb shots and Tito’s Vodka Bloody Mary and Caesar specials all day, $3 Fireball and Tuaca $7.50 Coors Light pitchers, $3.50 Crown Royal, Bloody Mary and Caesar specials all day Happy Hour 4:30-6:30pm Happy Hour 4:30-6:30pm Happy Hour 4:30-6:30pm Happy Hour 4:30-6:30pm Happy Hour 4:30-6:30pm Happy Hour 4:30-6:30pm Spicy Pie 745 31st Ave. E. Ste. 110, West Fargo MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY $3.50 Jameson and $1 off bottled beer 8pm-close $5 teas and $6 Patron margaritas 8pm-close, $3.50 Bloody Marys, Caesars and Mimosas until 6pm Happy Hour all day Mug Night: $2 32oz. mug, fill for the price of a pint 7pm-close $3 off all pitchers 7 pmclose Tall beers for the price of short 7pm-close Half price bottles of wine, $5 classic and $8 top-shelf martinis 7pm-close Town Hall Bar 103 Main Ave. W, West Fargo $3 Captain Morgan, $3.50 Crown Royal & Washington Apples 7-11pm $3 32oz. domestic Mongo Mugs, Ladies night $1 off drinks, $3 shots from 7-11pm Happy Hour 3-7pm, Windsor $3, Wu Tang shots $3 7-11pm $3 Cristal & Limon, domestic pitchers $6 7-11pm VFW: West Fargo 308 Sheyenne St., West Fargo $2.50 regular domestic beers and Windsor 12 inch pizza and a pitcher of beer for $11 $3 Barcardi, $4 domestic mug fills 8pmmidnight, Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells $2 Tuesday: $2 domestic wells 5pm-midnight, Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells $4 domestic mug fills 8pmmidnight, Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells $3.50 import pints 8pmmidnight, Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells $3.50 Fireball 5pm-midnight, $3 domestic bottles and Captain Morgan 8pm-10pm, Happy Hour 4-6:30pm $5 endless Mimosas 11am4pm 1-7pm, $4 scratch teas Happy Hour 1pm-midnight Happy Hour 1-7pm, $5 all-you-candrink for ladies 9pm-midnight, $3 pounders (all day) $2 Captain Morgan & $3 bomb shots 9pmmidnight Happy Hour 1-7pm, $3 perfect pint of Guinness and Irish car bombs 9pm-midnight Happy Hour 1-7 pm, 11am-2pm: $10 all-youcan) Three Lyons Pub 675 13th Ave. E, West Fargopmmidnight 2-for-1s 4-6pm $5.25 pitchers of Budweiser, Mich, Amber Boch, Bud Light, Miller Light and Foster, drink specials 4-6pm Vic’s Bar & Grill 427 Center Ave, Moorhead $2.75 Captain Morgan 2-for-1s 8-11pm $2.75 whiskeys Ladies night 8-10pm $5 pitchers Late night Happy Hour 9pm-midnight $5 pitchers all day Bloody Mary special .50 Bloody Marys and Mimosas all day 2-for-1s all day, $4 Crown Royal REGIONAL Holiday Beach Bar & Grill (Holiday Inn On The Lake) 1155 Hwy. 10 E, Detroit Lakes, Minn. 93 Fargo Monthly's Flavor Awards 2017: We had the people of Fargo-Moorhead nominate and vote for their favorite local dishes, drinks and establ... Published on Apr 26, 2017 Fargo Monthly's Flavor Awards 2017: We had the people of Fargo-Moorhead nominate and vote for their favorite local dishes, drinks and establ...
https://issuu.com/fmspotlight/docs/fm_may17
CC-MAIN-2020-29
refinedweb
12,972
61.67
HASH(3) BSD Programmer's Manual HASH(3) hash - hash database access method #include <sys/types.h> #include <db.h>; u_int32_t (*hash)(const void *, size_t); int lorder; } HASHINFO; The elements of this structure are as follows: bsize bsize defines the hash table bucket size, and is, by de- fault, the block size of the underlying filesystem. It may be preferable to increase the page size for disk-resident tables and tables with large data items. ffactor ffactor indicates a desired density within the hash table. It is an approximation of the number of keys allowed to ac- cumulate in any one bucket, determining when the hash table grows or shrinks. The default value is the same as bsize. nelem nelem is an estimate of the final size of the hash table. If not set or set too low, hash tables will expand grace- fully as keys are entered, although a slight performance degradation may be noticed. The default value is 1. cachesize A suggested maximum size, in bytes, of the memory cache. This value is only advisory, and the access method will al- locate more memory rather than fail. hash hash is a user defined hash function. Since no hash func- tion metada- ta.. Backward compatible interfaces to the routines described in dbm(3) and ndbm(3) are provided, although these interfaces are not compatible with previous file formats. The hash access method routines may fail and set errno for any of the er- rors specified for the library routine dbopen(3). btree(3), dbopen(3), mpool(3), recno(3) Per-Ake Larson, "Dynamic Hash Tables", Communications of the ACM, April 1988. Margo Seltzer, "A New Hash Package for UNIX", USENIX Proceedings, Winter 1991. Only big and little endian byte order is supported. MirOS BSD #10-current Aug.
http://www.mirbsd.org/htman/i386/man3/hash.htm
CC-MAIN-2015-06
refinedweb
298
65.62
Gigs_ wrote: > sorry i think that i express wrong. having problem with english > > > what i mean is how python knows to add all thing at the end of recursion > > >>> def f(l): > if l == []: > return [] > else: > return f(l[1:]) + l[:1] > > > f([1,2,3]) > > recursion1 f([2,3]) + [1] > > recursion2 f([3]) + [2] or [2, 1]? > > recursion3 f([]) + [3] or [3, 2, 1] > > > i dont get all this > > >>> def f(l): > if l == []: > print l > return [] > else: > return f(l[1:]) + l[:1] > > >>> f([1,2,3]) > [] > [3, 2, 1] # how this come here? how python save variables from each recursion? > > > sorry again for first post > I think the thing you are missing is that the recursive call f(l[1:]) in the return statement causes the current call to be suspended until the recursive call is complete. The new call has its own value for l, which is the caller's l[1:]. Each new call creates a completely new namespace. A less complicated function might make it a little more obvious. def factorial(n): print "n =", n if n=0: return 1 else: return n * factorial(n-1) Try running that with a few different arguments to show you how the recursion works. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd Skype: holdenweb Sorry, the dog ate my .sigline
https://mail.python.org/pipermail/python-list/2007-September/441835.html
CC-MAIN-2014-15
refinedweb
231
76.05
I purchased a book that I am trying to follow along with, however it is a bit dated. I know that Blender2.56 is built entirely on python3.1. Here is the script I am trying to run in the blender python console: I don't know if this code is correct in terms of the syntax, however, I am getting this as an error: Code: Select all import Blender from Blender import Scene, Text3d, Window hello = Text3d.New("HelloWorld") hello.setText("Hello World") scn = Scene.GetCurrent() ob = scn.objects.new(hello) Window.RedrawAll() in the user info column, which leads me to believe that either my PYTHONPATH or PATH is not accurate. Code: Select all Traceback (most recent call last): File "Text.002.py", line 3, in <module> ImportError: No module named Blender location:<unknown location>:-1 Python script fail, look in the console for now... Any help on this would be greatly appreciated. I am very eager to start coding, however I know its good that I am going through this so I know what goes on under the hood!! Best Regards, thru2trot
https://www.blender.org/forum/viewtopic.php?t=18931
CC-MAIN-2020-29
refinedweb
185
74.08
In this lab, you will practice on: If you during the week, you are welcome to go to CL119 during Office Hours posted for lab instructors. A string may be defined without an initializing value, in which case its initial value is an empty string (zero length, no characters): string str1; A string object may also be initialized with * a string expression: string str2 = str1; string str3 = str1 + str2; * a character string literal: string str4 = "Hello there"; string str5 ("Goodbye"); // Alternate form * a substring of another string object: string str8 = "ABCDEFGHIJKL"; // Initialize str9 as "CDEFG" // Starts at character 2 ('C') // with a length of 5 // (or the rest of the string, if shorter) string str9 (str8,2,5); Both of these functions return the length (number of characters) of the string. The size_type return type is an unsigned integral type. We must use the qualified name as in string::size_type because the definition of size_type is otherwise hidden inside the definition of the string type. string str = "Hello"; string::size_type len; len = str.length(); // len == 5 len = str.size(); // len == 5 or you can just use cout << str.length() << endl; size_type find (str, size_type pos); Search for the first occurrence of the substring str in the current string, starting at position pos. If found, return the position of the first character. If not, return a special value (called string::npos). string str16 = "abcdefghi"; string str17 = "def"; string::size_type pos = str16.find (str17,0); cout << pos << endl; // return 3 pos = str16.find ("AB",0); if (pos== string::npos) cout << "Not found " << endl; string substr (size_type pos, size_type n); Returns a substring of the current string, starting at position pos and of length n: string str18 = "abcdefghi" string str19 = str18.substr (6,2); cout << str19 << endl; // return "gh" A number of C++ operators also work with strings. Here is the syntax template for an input statement cin >> Variable >> Variable ...;When you enter input data at the keyboard, you must be sure that each data value is appropriate for the data type of the variable in the input statement. The >> operator skips any leading white space characters when it is looking for the next input value in the stream. Whitespace characters are blanks and certain nonprintable characters such as the character that marks the end of a line (new line character). After skipping any whitespace characters, >> operator proceeds to extract the desired data value from the input stream. If the data value is int or float, input of the number stops at the first character that is inappropriate for the data type, such as a whitespace character. If the data value is a char value, input stops as soon as a character is input. But the get function from istream data type works a little differently. It inputs the next character in the stream regardless of what it is, even if it is a whitespace character or new line character. Now look at the following two examples. Compile and run them with the same set of the input data. e.g. (a b c d or a 2bc). Examine the results carefully. // Program CharRead prompts for and reads four characters // from the keyboard and then prints them. #include <iostream> using namespace std; int main () { char char1; char char2; char char3; char char4; cout << "Input four characters. Press Return." << endl; cin >> char1 >> char2 >> char3 >> char4; cout << char1 << char2 << char3 << char4; return 0; } // Program Char2Rd prompts for and reads four characters // from the keyboard and then prints them. *) #include <iostream> using namespace std; int main () { char char1; char char2; char char3; char char4; cout << "Input four characters. Press Return." << endl; cin.get(char1); cin.get(char2); cin.get(char3); cin.get(char4); cout << char1 << char2 << char3 << char4; return 0; }Now the last thing to emphasize. For a string variable, say inputStr, the statement cin >> inputStr;skips leading whitespace and it stops as soon as it encounters a whitespace character. The statement getline(cin, inputStr);does not skip the leading whitespace character(s). It stops when a new line character '\n' is encountered. getline is a function from C++ standard library. Back to Highlights Here is an example program that reads four floating point data values from a file and writes to another file in the reverse order. // Program IODemo demonstrates how to use files #include <iostream> #include <fstream> using namespace std; int main() { cout << fixed << showpoint; //sets all printout in decimal format with decimal points appearing float val1, val2, val3, val4; // declares 4 variables ifstream inData; // declares input stream ofstream outData; // declares output stream inData.open("Data.In"); // binds program variable inData to file "Data.In" outData.open("Data.Out"); // binds program variable outData to file "Data.Out" inData >> val1 >> val2 >> val3 >> val4; // inputs 4 values outData << val4 << endl; outData << val3 << endl; outData << val2 << endl; outData << val1 << endl; // outputs 4 values return 0; }Each file in your program has both an internal name and an external name. The internal name is what you call it in your program; the external name is the name the operating system knows it by. Somehow, these two names must be associated with one another. This association is called binding and is done in function open. Notice that inData and outData are identifiers in the program; "Data.In" and "Data.Out" are character strings. Data.In is the name that was used when the input data file was created; Data.Out is the name of the file where the answers are stored. You will need to use the pico or vi text editor to create the input data file according the requirement of the data type and format in your program. The input data file must exist and contain correct data. Otherwise, the input will fail. For example, in the preceding IODemo program, the input file should look like this: 5.5 6.6 7.7 8.8You may run the program and experience how File I/O works. Back to Highlights
http://www.cs.uregina.ca/Links/class-info/110/expressions/index-053.html
CC-MAIN-2018-22
refinedweb
992
70.94
The problem is that sometimes 3rd party modules have logging turned on. For example, I run into that when using Selenium for testing. If you do not want to see any logger output, you can put this at the top of your module: import logging logging.disable(logging.CRITICAL) That works fine, until you want to turn on logging for the module you are working on. Here is code that turns off all other loggers. The last line sends a logger message for this module to the console. import logging for logger_name in logging.Logger.manager.loggerDict.keys(): logging.getLogger(logger_name).setLevel(logging.CRITICAL) logging.debug('hello from my module') Advertisements
https://snakeycode.wordpress.com/2016/11/09/logging-a-single-module-in-python/
CC-MAIN-2017-43
refinedweb
111
50.73
I was working on an old assignment (2010) for fun. Also because I was really stuck on it the first time and as of this year, programming has now clicked. Because of this, I have been doing little coding exercises and have been revisiting old assignments to see if I could easily write out the code. I have most of it down, but there is a little glitch. from graphics import * from math import * import random W = 300 H = 300 ballList = [] squareList = [] #---------------------------------------------------------------- def simul(win, ballList): for step in range( 200 ): for i in range(len(ballList)): c, dx, dy = ballList[i] x = c.getCenter().getX() y = c.getCenter().getY() r = c.getRadius() if (x <= 0 + r ) or (x >= W - r): dx = -dx if (y <= 0 + r) or(y >= H - r): dy = -dy # stop the ball's movement if isInSquare(x, y, r): dx = 0 dy = 0 # make it bounce off the black box's bounds if hitBlackBox(x, y, r): dx = -dx dy = -dy (boolVal, ball1, ball2) = hasCollided(ballList) # create a tuple if boolVal == True: # change the dx and dy of each ball that satisfies condition # then reverse the dx, dy of collided balls c1, dx1, dy1 = ball1 c2, dx2, dy2 = ball2 # replace old ballList values with current ballList values for list in ballList: if ball1[0] in list: dx1 = -dx1 dy1 = -dy1 list.pop(1) list.insert(1, dx1) list.pop(2) list.insert(2, dy1) if ball2[0] in list: dx2 = -dx2 dy2 = -dy2 list.pop(1) list.insert(1, dx2) list.pop(2) list.insert(2, dy2) c1.move(dx1, dy1) c2.move(dx2, dy2) # boolVal = False # need something of the sort else: c.move(dx, dy) ballList[ i ] = [ c, dx, dy ] # update ball values if allInBoxes(ballList): end(win) def allInBoxes(ballList): counter = 0 for i in range(len(ballList)): c, dx, dy = ballList[i] if (dy == dx == 0): counter += 1 if counter == len(ballList): return True return False def hasCollided(ballList): for i in range(len(ballList)-1): for j in range(i+1, len(ballList)): c1 = ballList[i][0] c2 = ballList[j][0] # get the dx1-2, dy1-2 vals dx1 = ballList[i][1] dy1 = ballList[i][2] dx2 = ballList[j][1] dy2 = ballList[j][2] # get radius of i and j balls r1 = c1.getRadius() r2 = c2.getRadius() # now get the points P1 = Point(c1.getCenter().getX(), c1.getCenter().getY()) P2 = Point(c2.getCenter().getX(), c2.getCenter().getY()) #print "(", P1.getX(), ",",P1.getY(),")", "(" , P2.getX() , ",",P2.getY(),")", "This is P1, P2" dist = distance(P1, P2) if((r1 + r2) >= dist >= 0): ## if dist < (r1 + r2): ## largeDist = False ## while largeDist == False: ## if dist < (r1 + r2): ## if(dx1 < 0 and dx2 < 0) and (dy1 < 0 and dy2 < 0) or\ ## (dx1 > 0 and dx2 > 0) and (dy1 > 0 and dy2 > 0): ## #dist < (r1 + r2) ## # keep pushing by -dx1-2, -dy1-2 values ## c1.move(-dx1, -dy1) ## c2.move(dx2, dy2) ## P1 = Point(c1.getCenter().getX(), c1.getCenter().getY()) ## P2 = Point(c2.getCenter().getX(), c2.getCenter().getY()) ## dist = distance(P1, P2) ## else: ## largeDist = True return True, ballList[i], ballList[j] return False, 0, 0 def distance(P1, P2): return sqrt( pow( P1.getX() - P2.getX(), 2 ) + pow( P1.getY() - P2.getY(), 2 )) def isInSquare(x, y, r): for i in range(len(squareList)-1): # exclude black box sP1 = squareList[i].getP1() # (bOriginX, bOriginY) sP2 = squareList[i].getP2() # (bW, bH) if (sP2.getX() - r >= x >= sP1.getX() + r) and (sP2.getY() - r >= y >= sP1.getY() + r): return True def hitBlackBox(x, y, r): # get last box blackBox = squareList[-1] sP1 = blackBox.getP1() # (bOriginX, bOriginY) | square P1 sP2 = blackBox.getP2() # (bW, bH) | square P2 if (sP2.getX() + r >= x >= sP1.getX() - r) and (sP2.getY() + r >= y >= sP1.getY() - r): return True def drawSquare(win): for i in range(4): # create 3 white boxes with random coords bOriginX = random.randrange(0, W-50, 51) bOriginY = random.randrange(0, H-100, 51) bW = bOriginX + 50 # you have to include origin + width therefore 100-50 = 50 sBoxW bH = bOriginY + 50 square = Rectangle(Point(bOriginX, bOriginY), Point(bW, bH)) square.draw(win) square.setFill("white") squareList.append(square) squareList[-1].setFill("black") # Fill last square drawn with black # this commented portion can work too, remove the previous line, set loop range(3) ## blackSquare = Rectangle(Point(H-50,W-50), Point((W-50)+50, (H-50)+ 50)) ## blackSquare.draw(win) ## blackSquare.setFill("black") ## squareList.append(blackSquare) # ------------------------------------------- def end(win): waitForClick( win, "Click to End" ) win.close() #---------------------------------------------------------------- def waitForClick( win, message ): """ waitForClick: stops the GUI and displays a message. Returns when the user clicks the window. The message is erased.""" # wait for user to click mouse to start startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message ) startMsg.draw( win ) # display message win.getMouse() # wait startMsg.undraw() # erase #---------------------------------------------------------------- def main(): win = GraphWin( "moving ball", W, H ) #--- define a ball position and velocity --- drawSquare(win) ballColor = ["red", "blue", "pink", "purple", "green"] for i in range(2): c = Circle( Point( random.randrange( 16, W-15, 20 ), random.randrange( H/3, 2*H/3, 20 ) ), 15 ) c.setFill(ballColor[i%len(ballColor)]) c.draw(win) ballList.append([c, 5 - random.randrange(10), 5 - random.randrange(10)]) for i in range(len(ballList)): # loop: no ball should be 0 dx and 0 dy if ballList[i][1] == ballList[i][2] == 0: ballList[i][1] == 1 waitForClick( win, "Click to Start" ) simul(win, ballList) end(win) main() Graphics Module Link Here The program loads some balls of varying colors. The program waits for the user to click to start, the balls bounce off the edge of the screen, each other, and a black box. There are 4 boxes on the screen loaded at random positions. Three of them stop the ball's movement if the ball is inside of the bounds of the box. The last one (black box) acts as an obstacle and the ball bounces off the black box upon collision. The program ends at the end of loop or if all balls are in a white box. I am having problems with the collision detection function called hasCollided(). If the balls load on top of each other or manage to get that way, they jiggle back and fourth and the program spends the rest of the iterations trying to get them to push away from each other. I noticed this happens if the balls overlap with each other because the dx, dy increment values are too small to effectively push them away on the first iteration. The program spends all of it's time trying to get them unstuck but it moves the balls back by -dx1, -dy1 and -dx2, -dy2 then back to dx1, dy1, dx2, dy2 creating the jiggle. I tried to create a while loop inside of hasCollided() for the condition of the balls either as being originally drawn to overlap or if they overlap naturally due based on how much they collide by. It didn't work out. See commented section. I realized my thinking isn't 100% right on the collision for both the black box (hitBlackBox()) and the ball collision function (hasCollided()) because the balls cannot get unstuck in situations where the ball overlaps with the object it must oppose. Can someone explain to me what I should have done instead? This post has been edited by Hikaroshi: 01 September 2013 - 02:07 PM
http://www.dreamincode.net/forums/topic/328094-stuck-on-ball-collision/
CC-MAIN-2016-07
refinedweb
1,225
73.68
Instrumenting the AST The following is a rough retelling of my presentation for the Testing in Python BoF at PyCon 2010, including removing some in-jokes relevant only for that session. On the other hand, I expanded it to include working code. This means you, yes you, could work on this. It's not for the faint of heart. Have fun! And let me know what you think. The AST module Code coverage is a good thing. I want to do branch coverage. Last year Ned Batchelder added branch coverage support to coverage.py, which works by analyzing the byte code. I want to see if there's a better solution through an entirely different approach. Let me introduce you to Python's "ast" module. >>> import astIt's an interface to Python's internal Python parser so program can convert string containing Python code into an abstract syntax tree (AST). >>> ast.parse("for i in range(10): print i") <_ast.Module object at 0x1004d06d0> >>>The ast module contains some code to display the contents of the AST as a string. >>> ast.dump(ast.parse("for i in range(10): print i")) "Module(body=[For(target=Name(id='i', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()), args=[Num(n=10)], keywords=[], starargs=None, kwargs=None), body=[Print(dest=None, values=[Name(id='i', ctx=Load())], nl=True)], orelse=[])])"I've reformatted it to fit my slides as otherwise it's a long string. I can also ask it to display the position information, which is the second True in the following. >>> ast.dump(ast.parse("for i in range(10): print i"), True, True) "Module(body=[For(target=Name(id='i', ctx=Store(), lineno=1, col_offset=4), iter=Call(func=Name( id='range', ctx=Load(), lineno=1, col_offset=9), args=[Num(n=10, lineno=1, col_offset=15)], keywords=[], starargs=None, kwargs=None, lineno=1, col_offset=9), body=[Print(dest=None, values=[Name(id='i', ctx=Load(), lineno=1, col_offset=26)], nl=True, lineno=1, col_offset=20)], orelse=[], lineno=1, col_offset=0)])" Programmatically building an AST You can use the ast module to build a tree directly, without parsing a string, then compile and execute that code. >>> from ast import * >>> tree = Module([Print(None, [Str("PyCon2010!")], True)]) >>> tree.lineno = 1 >>> tree.col_offset = 1 >>> fix_missing_locations(tree) <_ast.Module object at 0x1004dff50> >>> tree = fix_missing_locations(tree) >>> compile(tree, "<TiP>", "exec") <code object <module> at 0x1004d38a0, file "<TiP>", line 1> >>> exec compile(tree, "<TiP>", "exec") PyCon2010! >>>"ast.fix_missing_locations" is a helper function to assign missing position information the compiler needs when generating byte code. I end up using it and "ast.copy_location" a lot, which copies the location information from one node to another. The mystery of the wrong TypeError What's the bug with the following? try: raise TypeError("blah: %d" % "I said 'PyCon2010'!") except TypeError: passThe code correctly raises a TypeError, but it's the wrong TypeError. I've made this mistake a few times, which is why I try to remember to check the contents of the exception during my tests. Notice that unittest doesn't help here, since assertRaises only checks the exception type, and not the content. It is possible to check all of these manually. You could defer the calculation to a "check_mod()" function try: raise TypeError( check_mod("blah: %d", "I said 'PyCon2010'!")) except TypeError: passA check_mod function might look like def check_mod(left, right): try: return left % right except Exception, err: print "Could not interpolate: %s" % (err,) traceback.print_stack() raise Rewriting the AST for fun (and profit?) The ast module has some support code for creating a new parse tree based on transforming another parse tree. I can transform all "%" binary operations to call a function for the left and right sides. Here's a non-working but mostly complete version of how that might look. from ast import * class RewriteInterpolation(NodeTransformer): code = open(filename).read() tree = parse(code, filename) tree = RewriteInterpolation().visit(tree)What's missing is the code to define or import check_string. I'll leave that for later. For now, just get the idea that you can parse Python code to an AST, rewrite it in order to instrument certain parts, then execute the result. I ran something similar to this against the Python standard library and tests, in the hopes that I could find an bug. It took a lot of hands on fiddling, since some essential Python modules cannot be instrumented because the full path wasn't fully defined. I got it to work, and found no bugs. The closest was this code from difflib.py try:' or '' id = ''where the comment is needed because otherwise the reason isn't immediately obvious. While not a bug, it perhaps does show you that the test revealed something. (Oh, and it also showed the several hundred tests that the standard library does to test string interpolation failures.) (Well-known) Limitations in coverage.py Take a look at this program. I've used coverage.py to run the program and annotate the code to display the coverage and highlight the lines which weren't executed. You can see there are a other few problems which coverage did not test. Line 9 never executes "x=9" and the "raise TypeError" in line 17 is never reached, because of the string interpolation error in the parameter list. I've hacked together something over the last 30 hours to show that something better is possible. A different approachI want to generate coverage for this statement: x = 1I'll do that by parsing the code into the AST then rewriting the AST so it's equivalent to: from ast_report import register_module ast_enter, ast_leave, ast_reached = \ register_module('spam/testing.py', {0: (1, 0)}, {} ) # unique identifer -> (lineno, col_offset) if 1: ast_enter[0] += 1 x = 3 ast_leave[0] += 1 The "register_module" function is something I'll write in a bit. It will take a filename and two location dictionaries. The first dictionary is for statements like assignment which are supposed to go to completion. That is, code before it and after it are supposed to execute. (Compare this to 'return', which will never allow code after it to run. That's what the second dictionary is used for.) The key is a unique identifier associated with each statement with a coverage test, and the value is the lineno and col_offset pair which come from the AST. The ast_enter and ast_leave dictionaries here are default dicts (though that's an implementation point). The "0" is same unique identifier in the location dictionary, and can be used to say that the statment at line 1, column 1 (col_offset starts with 0), was reached and left. At this point someone in the audience astutely asked why I used an "if 1:" in the above. That's a limitation of how the ast.NodeTransformer works. It lets derived classes tranform a single term to a single other term, which means I need to transform a single statement (the assignment here) into a single other statement, and not three statements. I chose the "if 1:" because it's easy to write, it can contain an arbitrary number of sub-statements, and because Python's byte compiler knows how to optimize away the "if 1:" test. If you think about this approach, the run-time overhead is pretty low, but it's a lot more than simple assignment. I don't know how it affects real-world code. Remember, it's been 30 hours since I started this, and I'm at conference as well. Instrumenting the AST for code coverage The next step is to automate all of this: convert a .py file into an AST, instrument the code to add these coverage checks, implement the reporting mechanism as an atexit hook, and for good measure, add the "%" TypeError check. To see if this is effective, convert the AST to byte code and save it to a .pyc file. This calls for a horrible hack around a call to compileall.py. I've named the result "ast_compileall.py" # ast_compileall.py import __builtin__ from ast import * import compileall import sys import traceback import itertools class RewriteInterpolation(NodeTransformer): def __init__(self, filename): self.filename = filename self.enter_linenos = {} # id -> (lineno, col_offset) self.reach_linenos = {} # id -> (lineno, col_offset) self.counter = itertools.count() def visit_Module(self, module_node): # Need to import and call ast_report.register_module(). # These must occur after the "from __future__ import ..." statements. # Find where I can insert them. body_future = [] body_rest = [] for node in module_node.body: node = self.visit(node) if (not body_rest and isinstance(node, ImportFrom) and node.module == "__future__"): body_future.append(node) else: body_rest.append(node) # It's easier to let Python convert the code to an AST import_line = parse("from ast_report import register_module, check_string").body[0] print ("ast_enter, ast_leave, ast_reached = register_module(%r, %r, %r)" % (self.filename, self.enter_linenos, self.reach_linenos)) register_line = parse( "ast_enter, ast_leave, ast_reached = register_module(%r, %r, %r)" % (self.filename, self.enter_linenos, self.reach_linenos)).body[0] # Assign a reasonable seeming line number. lineno = 1 if body_future: lineno = body_future[0].lineno for new_node in (import_line, register_line): new_node.col_offset = 1 new_node.lineno = lineno new_body = body_future + [import_line, register_line] + body_rest return Module(body=new_body) # These are statements which should have an enter and leave # (In retrospect, this isn't always true, eg, for 'if') def track_enter_leave_lineno(self, node): node = self.generic_visit(node) id = next(self.counter) enter = parse("ast_enter[%d] += 1" % id).body[0] leave = parse("ast_leave[%d] += 1" % id).body[0] self.enter_linenos[id] = (node.lineno, node.col_offset) for new_node in (enter, leave): copy_location(new_node, node) # This is the code for "if 1: ..." n = Num(n=1) copy_location(n, node) if_node = If(test=n, body=[enter, node, leave], orelse=[]) copy_location(if_node, node) return if_node visit_FunctionDef = track_enter_leave_lineno visit_ClassDef = track_enter_leave_lineno visit_Assign = track_enter_leave_lineno visit_AugAssign = track_enter_leave_lineno visit_Delete = track_enter_leave_lineno visit_Print = track_enter_leave_lineno visit_For = track_enter_leave_lineno visit_While = track_enter_leave_lineno visit_If = track_enter_leave_lineno visit_With = track_enter_leave_lineno visit_TryExcept = track_enter_leave_lineno visit_TryFinally = track_enter_leave_lineno visit_Assert = track_enter_leave_lineno visit_Import = track_enter_leave_lineno visit_ImportFrom = track_enter_leave_lineno visit_Exec = track_enter_leave_lineno #Global visit_Expr = track_enter_leave_lineno visit_Pass = track_enter_leave_lineno # These statements can be reached, but they change # control flow and are never exited. def track_reached_lineno(self, node): node = self.generic_visit(node) id = next(self.counter) reach = parse("ast_reached[%d] += 1" % id).body[0] self.reach_linenos[id] = (node.lineno, node.col_offset) copy_location(reach, node) n = Num(n=1) copy_location(n, node) if_node = If(test=n, body=[reach, node], orelse=[]) copy_location(if_node, node) return if_node visit_Return = track_reached_lineno visit_Raise = track_reached_lineno visit_Break = track_reached_lineno visit_Continue = track_reached_lineno # Some code to instrument the run-time and check for '%' failures. old_compile = __builtin__.compile def compile(source, filename, mode, flags=0): # skipping a few parameters # My rewrite code uses ast.parse, which ends up calling this # function with this argument, so pass it back to the real compile. if flags == PyCF_ONLY_AST: return old_compile(source, filename, mode, flags) assert mode == "exec" #traceback.print_stack() code = open(filename).read() tree = parse(code, filename) tree = RewriteInterpolation(filename).visit(tree) code = old_compile(tree, filename, "exec") return code # Ugly hack so I can force compileall to use my compile function. __builtin__.compile = compile exit_status = int(not compileall.main()) sys.exit(exit_status)I placed this file in "spam/testing.py" def main(): def f(x): if x > 0: return x*x 1/0 for i in range(4, 9): if f(i) < 0: x=9 if i == 8: continue print "Here" if i == 10: continue try: raise TypeError("Hi! %d" % "sdfa") except TypeError: pass main()I then compiled all of the .py files in the 'spam' directory with python ast_compileall.py spamand I made sure the following was on my PYTHONPATH as "ast_report.py" # ast_report.py from collections import defaultdict import traceback import atexit import linecache loaded_modules = [] class FileInfo(object): def __init__(self, filename, enter_linenos, reach_linenos): self.filename = filename self.enter_linenos = enter_linenos self.reach_linenos = reach_linenos self.ast_enter = defaultdict(int) self.ast_leave = defaultdict(int) self.ast_reach = defaultdict(int) def register_module(filename, enter_linenos, reach_linenos): #print filename, enter_linenos, reach_linenos info = FileInfo(filename, enter_linenos, reach_linenos) loaded_modules.append(info) return info.ast_enter, info.ast_leave, info.ast_reach def check_string(left, right, lineno, col_offset): if not isinstance(left, basestring): return left % right try: return left % right except Exception, err: print "Could not interpolate: %s" % (err,) traceback.print_stack() raise # Basic coverage report def report_coverage(): for fileinfo in loaded_modules: # This will contain a list of all results as a 3-ple of # lineno, col_offset, "text message" report = [] # These should have both 'enter' and 'leave' counts. for id, (lineno, col_offset) in fileinfo.enter_linenos.items(): if id not in fileinfo.ast_enter: report.append( (lineno, col_offset, "not entered") ) elif id not in fileinfo.ast_leave: report.append( (lineno, col_offset, "enter %d but never left" % fileinfo.ast_enter[id]) ) else: delta = fileinfo.ast_leave[id] - fileinfo.ast_enter[id] report.append( (lineno, col_offset, "enter %d leave %d (diff %d)" % (fileinfo.ast_enter[id], fileinfo.ast_leave[id], delta)) ) # These only need to be 'reach'ed for id, (lineno, col_offset) in fileinfo.reach_linenos.items(): if id not in fileinfo.ast_reach: report.append( (lineno, col_offset, "not reached") ) else: report.append( (lineno, col_offset, "reach %d" % (fileinfo.ast_reach[id],)) ) # sort by line number, breaking ties by column offset report.sort() print "Coverage results for file", fileinfo.filename for lineno, col_offset, msg in report: print "%d:%d %s" % (lineno, col_offset+1, msg) print linecache.getline(fileinfo.filename, lineno).rstrip() # Dump the coverage results when Python exist. atexit.register(report_coverage)(While I used an atexit hook here, I did that because it was the fastest way to get to a proof-of-concept solution. Really I think this should be more like how coverage.py works, with a command-line script which sets up the run environment and reports the results at the end.) Try it out! This coverage code will only work on modules which were imported, where the .pyc file is used instead of the .py file. (But perhaps an import hook would be useful or at least interesting here?) What I do is import the module via the command-line % cd spam/ % python -c 'import testing' Could not interpolate: %d format: a number is required, not str File "<string>", line 1, in <module> File "spam/testing.py", line 21, in <module> main() File "spam/testing.py", line 785, in main File "ast_report.py", line 30, in check_string traceback.print_stack() Coverage results for file spam/testing.py 1:1 enter 1 leave 1 (diff 0) def main(): 3:3 enter 1 leave 1 (diff 0) def f(x): 4:5 enter 5 but never left if x > 0: 5:7 reach 5 return x*x 6:5 not entered 1/0 8:3 enter 1 leave 1 (diff 0) for i in range(4, 9): 9:5 enter 5 leave 5 (diff 0) if f(i) < 0: x=9 9:18 not entered if f(i) < 0: x=9 10:5 enter 5 leave 4 (diff -1) if i == 8: 11:8 reach 1 continue 12:8 not entered print "Here" 13:5 enter 4 leave 4 (diff 0) if i == 10: 14:8 not reached continue 16:3 enter 1 leave 1 (diff 0) try: 17:7 reach 1 raise TypeError("Hi! %d" % "sdfa") 19:7 enter 1 leave 1 (diff 0) pass 21:1 enter 1 leave 1 (diff 0) main() You can see that it reports the string interpolation without a problem, and if you look closely you'll see that it catches that the "if" on line 9 is executed while the "x=9" also on line 9 is never executed. There's also some problems. Line 4 reports that the code was entered 5 times and never left, but that's a bit of a false positive since it left through a return statement. I think now, after additional thought, that the better solution is to put the "leave" test on the first line of each possible branch. Pluses and minuses There are some great advantages to this approach. - I don't need to look at the stack frame to figure out where I am, or even use the sys.settrace() hook. - I get coverage testing of every statement on a line. - I can instrument a specific and limited set of Python files - Full branch coverage is possible. - I can add tests which are almost impossible to add otherwise (like "%d" % "asdf"; or what about checking if the RHS of an assert will actually work?) - What about instrumenting all "d.keys()" calls in Python 2.x code to check and report if a dict keys() result is ever used as something other than the iterator, like it would be in Python 3.x? There are some difficult problems as well. Consider: x = arg or default_arg or die(_("missing arg")) Branch reporting should say that 'arg' tested both True and False, that default_arg tested True and False and ... that the result of die() tested both True and False? And just how should someone visualize all this extra data? "See also" and ruminations I talked with Ned some after my presentation. He pointed out that the complex part of coverage.py, which he's worked on a lot during the last year, is to make the system configurable so it can be told which coverage to ignore. I know what he means. In the late 1990s I added the "#pragma: no cover" option to the early form of coverage.py, which exists (although not my actual code) to this day. If coverage works on a more fine-grained level, how do you suppress the false warnings so the true issues aren't hidden in the noise? Ned also pointed out Matthew J. Desmarais' work with Canopy instrument python code to generate robust coverage information. the goal is to provide modified condition/decision coverage metrics.I'm not the only one who has thought about instrumenting the AST, even in Python. (The Lisp community likely thought of this before I was born.) What I've hoped to do here is explain it well enough so that you can figure out how this approach works and come up with ways to extend it for the future.... or figure out why it fails. If you are doing that, do bear in mind my python4ply package. It contains a full grammar definition for Python using PLY, with support for the decrepit AST from the compiler module. Potentially you could use it to have Python 3 generate an AST for Python 2, or even vice versa, with a lot more work. Or, if you have both money and interest, perhaps you'll fund me? I am a consultant, after all. I mostly work in computational chemistry and my clients aren't interested in this sort of deep language analysis, so I only work on this during rare intervals. It's not only money, but access to people who want these sorts of capabilities and can give me feedback on what they want and how effective a solution is. Or, if you want to work on it yourself - feel free! I hereby release all of this code to the public domain, and disavow any copyright interest in the code expressed in this article. You don't even have to mention my name. Just develop good testing tools. I know there are a number of tools in the greater world of computing which can work on ASTs. I have no experience with them. Perhaps it's best to convert the Python AST to some other tree grammar where there is a tree manipulation language? When I'm feeling crazy I think "just convert the AST to XML then use XSLT to add the instrumentation, and convert the resulting XML back to an AST." How sane is that? And it would mean I would have to learn a lot more about XSLT. Or what about ANTLR's tree grammars? But then there's Manual Tree Walking Is Better Than Tree Grammars. It's a Brave New World. Thanks! I thank Armin Rigo, Brett Cannon, Grant Edwards, John Ehresman, Jeremy Hylton, Kurt Kaiser, Neal Norwitz, Neil Schemenauer, Nick Coghlan, Tim Peters, Martin von Löwis and everyone else who worked on the ast module. Without them this would be a much harder problem. Any comments? Andrew Dalke is an independent consultant focusing on software development for computational chemistry and biology. Need contract programming, help, or training? Contact me
http://www.dalkescientific.com/writings/diary/archive/2010/02/22/instrumenting_the_ast.html
CC-MAIN-2020-10
refinedweb
3,353
57.16
In this tutorial you’ll learn how to get date and time from an NTP server using the ESP8266 NodeMCU with Arduino IDE. Getting date and time is useful in data logging projects to timestamp readings. To get time from an NTP Server, the ESP8266 needs to have an Internet connection and you don’t need additional hardware (like an RTC clock). Before proceeding make sure you have the ESP8266 board installed in Arduino IDE: Recommended: Get Date and Time with ESP328266 is an NTP Client that requests time from an NTP Server (pool.ntp.org). Installing the NTPClient Library We’ll use the NTPClient library to get time. In your Arduino IDE, go to Sketch > Library > Manage Libraries. The Library Manager should open. Search for NTPClient and install the library by Fabrice Weinber as shown in the following image. NTPClient Library Time Functions The NTPClient Library comes with the following functions to return time: getDay() – returns an int number that corresponds to the the week day (0 to 6) starting on Sunday; getHours() – returns an int number with the current hour (0 to 23) in 24 hour format; getMinutes() – returns an int number with the current minutes (0 to 59); getSeconds() – returns an int number with the current second; getEpochTime() – returns an unsigned long with the epoch time (number of seconds that have elapsed since January 1, 1970 (midnight GMT); getFormattedTime() – returns a String with the time formatted like HH:MM:SS; This library doesn’t come with functions to return the date, but we’ll show you in the code how to get the date (day, month and year). ESP8266 NodeMCU Code The following code connects the ESP8266 to an NTP Server (pool.ntp.org) to request date and time. It displays the current date and time in several formats in the Serial Monitor. /*, "pool.ntp.org"); /"}; void setup() { // Initialize Serial Monitor Serial.begin(115200); // Connect to Wi-Fi Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // Initialize a NTPClient to get time timeClient.begin(); // Set offset time in seconds to adjust for your timezone, for example: // GMT +1 = 3600 // GMT +8 = 28800 // GMT -1 = -3600 // GMT 0 = 0 timeClient.setTimeOffset(0); } void loop() { timeClient.update(); time_t epochTime = timeClient.getEpochTime(); Serial.print("Epoch Time: "); Serial.println(epochTime); String formattedTime = timeClient.getFormattedTime(); Serial.print("Formatted Time: "); Serial.println(formattedTime); int currentHour = timeClient.getHours(); Serial.print("Hour: "); Serial.println(currentHour); int currentMinute = timeClient.getMinutes(); Serial.print("Minutes: "); Serial.println(currentMinute); int currentSecond = timeClient.getSeconds(); Serial.print("Seconds: "); Serial.println(currentSecond); String weekDay = weekDays[timeClient.getDay()]; Serial.print("Week Day: "); Serial.println(weekDay); //Get a time structure struct tm *ptm = gmtime ((time_t *)&epochTime); int monthDay = ptm->tm_mday; Serial.print("Month day: "); Serial.println(monthDay); int currentMonth = ptm->tm_mon+1; Serial.print("Month: "); Serial.println(currentMonth); String currentMonthName = months[currentMonth-1]; Serial.print("Month name: "); Serial.println(currentMonthName); int currentYear = ptm->tm_year+1900; Serial.print("Year: "); Serial.println(currentYear); //Print complete date: String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay); Serial.print("Current date: "); Serial.println(currentDate); Serial.println(""); delay(2000); } How the Code Works First, include the necessary libraries. #include <ESP8266WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> Insert your network credentials in the following variables so that the ESP8266 can connect to your router to have access to the internet to request date and time from the NTP server. const char *ssid = "REPLACE_WITH_YOUR_SSID"; const char *password = "REPLACE_WITH_YOUR_PASSWORD"; Define an NTP client to get date and time. WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); We’ll request the time from pool.ntp.org, which is a cluster of times servers that anyone can use to request the time. Next, we create two arrays to hold the days of the week and the month names. /"}; setup() In the setup(), initialize the Serial Monitor to display the information. Serial.begin(115200); Next, connect the ESP8266 to the internet. // Connect to Wi-Fi Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Initialize the NTPClient. timeClient.begin(); Set Timezone We live in Portugal, so we don’t need to adjust the time. timeClient.setTimeOffset(0); loop() In the loop(), call the update() function to get the current date and time from the NTP server. timeClient.update(); Get Time Then, we can use the functions provided by the library to get time. For example, to get the epoch time: unsigned long epochTime = timeClient.getEpochTime(); Serial.print("Epoch Time: "); Serial.println(epochTime); The getFormattedTime() function returns the time in HH:MM:SS format. String formattedTime = timeClient.getFormattedTime(); Serial.print("Formatted Time: "); Serial.println(formattedTime); You can get the hours, minutes or seconds separately using the getHours(), getMinutes() and getSeconds() functions as follows: int currentHour = timeClient.getHours(); Serial.print("Hour: "); Serial.println(currentHour); int currentMinute = timeClient.getMinutes(); Serial.print("Minutes: "); Serial.println(currentMinute); int currentSecond = timeClient.getSeconds(); Serial.print("Seconds: "); Serial.println(currentSecond); Get Date The getDay() function returns a number from 0 to 6, in which 0 corresponds to Sunday and 6 to Saturday. So, we can access the week day name from the array we’ve created previously as follows String weekDay = weekDays[timeClient.getDay()]; Serial.print("Week Day: "); Serial.println(weekDay); The NTP Client doesn’t come with functions to get the date. So, we need to create a time structure (struct tm) and then, access its elements to get information about the date. struct tm *ptm = gmtime ((time_t *)&epochTime); The time structure contains the following elements: -. The following lines get the day of the month as follows: int monthDay = ptm->tm_mday; Serial.print("Month day: "); Serial.println(monthDay); To get the other elements, you use a similar approach. For example, for the month: int currentMonth = ptm->tm_mon+1; Serial.print("Month: "); Serial.println(currentMonth); Because the tm_mday starts at 0, we add 1 to the month so that January corresponds to 1, February to 2, and so on. Then, we can get the name of the month using the months array we’ve created previously. The arrays numbering starts at 0, that’s why we subtract 1. String currentMonthName = months[currentMonth-1]; Serial.print("Month name: "); Serial.println(currentMonthName); To get the year, we need to add 1900 because the tm_year saves the number of years after 1900. int currentYear = ptm->tm_year+1900; Serial.print("Year: "); Serial.println(currentYear); Finally, we create a String called currentDate that holds the current date in the YYYY-MM-DD format. String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay); Serial.print("Current date: "); Serial.println(currentDate); Demonstration After inserting your network credentials and modifying the variables to adjust the time to your timezone, test the example. Upload the code your ESP8266 board. Make sure you have the right board and COM port selected. Open the Serial Monitor at a baud rate of 115200. The date and time should be displayed in several formats as shown below. Wrapping Up In this tutorial you’ve learned how to get date and time from an NTP server using the ESP8266. This is specially useful for data logging projects that have access to the internet. If you don’t have access to the internet, you can use an RTC module like the DS1307. If you want to learn more about the ESP8266, check our resources: Thanks for reading. 65 thoughts on “ESP8266 NodeMCU NTP Client-Server: Get Date and Time (Arduino IDE)” Thanks for your project. Because of the summer time next week, I was experimenting and searching for this kind of solution. Do you have an suggestion for switch between normal and summertime? Thanks in advantage. PS. Timezone Amsterdam Hello Jan, unfortunately this example doesn’t cover timezone adjustment. We’ve looked into that subject, but it wasn’t implemented in the libraries. Hi Rui, Thanks for your response and sorry I was not clear enough. By the way, your books and examples have helped me a lot with getting started with my smart home. I believe I have done all what you wrote. Downloaded and installed the lib’s. But I get this message: exit status 1 freertos/FreeRTOS.h: No such file or directory See: De volumenaam van station C is OS_W7 Het volumenummer is FA0D-EFD7 Map van C:\Users\Jan\Mijn documenten\Arduino\libraries 01-04-2020 19:37 . 01-04-2020 19:37 .. 19-01-2020 15:30 Adafruit_ADXL343 01-04-2020 17:45 Adafruit_BME280_Library 19-01-2020 15:30 Adafruit_Circuit_Playground 03-02-2020 19:43 Adafruit_Unified_Sensor 18-11-2019 22:01 Arduino_SigFox_for_MKRFox1200 01-04-2020 19:35 AsyncTCP 01-04-2020 19:22 async_mqtt_client 22-12-2019 18:34 DHT_sensor_library 13-03-2020 09:45 ESP32_Mail_Client 22-12-2019 15:46 ESPAsyncTCP 22-12-2019 15:44 ESPAsyncWebServer 22-03-2020 18:46 EspMQTTClient 22-03-2020 18:47 MFUthings 21-03-2020 22:35 NTPClient 21-03-2020 22:28 NTPClient-master 22-12-2019 15:50 NTPClient-oud 17-01-2018 22:52 NTPClient-Patched 22-03-2020 18:46 PubSubClient 18-08-2019 22:16 108 readme.txt 18-11-2019 22:01 SD 22-12-2019 15:50 Servo 22-12-2019 15:50 SpacebrewYun 1 bestand(en) 108 bytes 23 map(pen) 2.921.226.240 bytes beschikbaar Can someone help me out. I do i change serialprintln to something like. digitalWrite(getseconds, HIGH); Tnx in advanced Hi Sara and Rui, Sorry, reaction before was a reaction on ESP32 with BME280. Correct reaction is; I fixed Summertime with testing for weeknumber , sunday and the time. Hello Rui, For the ntp client, does it also support: sunset and sunrise to pilot a chicken coop door? Regards Hi Geert. No, it doesn’t. For that, it is better to search for an API that returns that kind of information. For example, Regards, Sara Hello, nice tutorial. I have changed this program a little bit. I use an ESP32S NodeMCU and added a OLED and a temperature sensor. Regards Wolfgang Great! Could you share the sketch? Hi , Great Tutorial. is there a way incorporate the timezone /dst/est into the code ?. my programing skills are very good. I’m sure I have read somewhere that you shouldn’t continually call an ntp, and that you should only update a clock at interval? Have you a tutorial on using an esp 8266 as a clock running on its own, maybe looking to sync on the hour or every couple of hours? I know of RTC chips and milli but is there a Clock library you could point me at that you consider to be a good one for a newbie Cheers Clive Local clock can be probably done with millis as offset to rt clock. If you get the RT, the millis() is an offset to add to the UTC time obtained at the powerup of the module. Then update every x seconds. But as the wifi is connected, it is far more easy to get the RT every x seconds. You saved me, once again! Great job. Thanks very much ! ” Correction: “Set Timezone: You can use the setTimeOffset() method to adjust the time for your timezone in milliseconds. It is ‘seconds’. Nicely explained ! Can you please write tutorial about creating own local NTP server using ESP8266 and RTC module ? Hello Sara, Rui, I love your website, it is so informative! I am a beginner with Arduino/ESP, so maybe my question is lame, but when I tried to verify this ntp code, it said: ‘gmtime’ was not declared in this scope. I tried to check, if some library is missing, but everything looks good. Any advice? Thank you, Richie Hi. Make sure you have an ESP8266 board selected in Tools > Board before compiling. Regards, Sara Thanks for doing these tutorials but here is a suggestion that I am thinking about but may not be a simple as it sounds? How can you link NTP to ESPNow? It’s going to take me a while to work this one out as I am working on some dht sensors that will feed back via espnow to a esp that is linked to my home router to display and store the readings. I have had a little success due to your tutorials but what I am thinking is this; If the remote ends send data to the centre in a many to one configuration how can I pass back or check the remote ends to sync a timestamp with an ntp? One of the remote end sensors will be in the garden and I am toying with having a digital temperature display and a clock. I guess I need to get the things working before I start to complicate it beyond my limited expertise Cheers Clive Hallo Richie concerning problem during compilation “gmtime was not declared in this scope” I did a small investigation: “struct tm” is a function type of C++ library . There should be added line #include “time.h” at beginning of the code. Than compilation is OK. Kamil install new version of esp8266 arduino menu -> tools -> board -> board manager Please comment on this” In the explanation above you write “You can use the setTimeOffset() method to adjust the time for your timezone in milliseconds.” Is that right, or isn’t it adjusted in seconds? Hi. You are right. It is in seconds. The tutorial is fixed now. Regards, Sara Hello Sara, Rui, Your website is very good, i like it. But in this case I tried to verify this ntp code, it said: ‘gmtime’ was not declared in this scope. It is the same problem as described in comment in September by Richie. I have selected “Generic ESP8266 Module”, than NodeMcu 1.0 (esp-12E), than Adafruit ESP8266 with the same problem. In your article there is not mentioned an exact board type, just ESP8266. Can you provide info, for which board type is project dedicated? Thank you, Kamil Hallo Sara, Rui, one more info to my previous comment. Do not care about it, problem is now solved: concerning error during compilation “gmtime was not declared in this scope” I did a small investigation: “struct tm” is a function type of C++ library . There should be added line #include “time.h” at beginning of the code. After this update, compilation is OK. Kamil Kamil Hi Sara and Rui, Is there the equivalent in Micropython? thanks, Luiz Hi Sara and Rui, I used your code. its run well. But whenn I integrated code in to my code and If I specify the IP number, the codes return blank. (1970). Hi. That’s because it wasn’t able to get the time from the server. Reset the board and try again. Regards, Sara Hi, I am using this program for some time now and it was working well. But now i see some errors in the date and the formatting. I even reuploading the this sketch to my NodeMcu but no luck. Following is the serial out put i get. Epoch Time: 1622996660 Formatted Time: 16:24:20 Hour: 16 Minutes: 24 Seconds: 20 Week Day: Sunday Month day: 26 Month: 3 Month name: March Year: 1340177 Current date: 1340177-3-26 As you can see date, the date format and the year is incorrect. Any idea where it has gone wrong ? Regards Sagara Hi. Downgrade your ESP8266 boards installation to version 2.7.4. In your Arduino IDE, go to Tools > Board > Boards Manager. Search for ESP8266. Downgrade to version 2.7.4. Regards, Sara Works for me, thank you. Thanks. This fixed my issue! Hi Thanks for yours tutoriels I used your code in order to get date, but it’snt run well in may case. The date change every second (see below) I am using an ESP8266 card and I program on VSCode + Plateformio. Thank you in advance for your help. Code: timeClient.update(); unsigned long epochTime = timeClient.getEpochTime(); //Get a time structure struct tm *ptm = gmtime ((time_t *)&epochTime); int monthDay = ptm->tm_mday; int currentMonth = ptm->tm_mon+1; int currentYear = ptm->tm_year+1900; Result: epochTime Date Times 1624008484 — 5/5/1884177 09:28:04 – 1655565 – Lum > 797 1624008485 — 9/6/2020279 09:28:05 – 1656565 – Lum > 795 1624008486 — 14/7/2156381 09:28:06 – 1657565 – Lum > 797 1624008487 — 17/8/2292483 09:28:07 – 1658565 – Lum > 798 1624008488 — 21/9/2428585 09:28:08 – 1659565 – Lum > 798 1624008489 — 27/10/2564687 09:28:09 – 1660566 – Lum > 796 1624008490 — 30/11/2700789 09:28:10 – 1661565 – Lum > 796 1624008491 — 4/1/2836892 09:28:11 – 1662565 – Lum > 796 1624008492 — 8/2/2972994 09:28:12 – 1663565 – Lum > 797 1624008493 — 14/3/3109096 09:28:13 – 1664565 – Lum > 797 1624008494 — 19/4/3245198 09:28:14 – 1665565 – Lum > 797 try to replace struct tm *ptm = gmtime((time_t *)&epochTime); to time_t rawtime = epochTime; struct tm *ptm = gmtime(&rawtime); Thank you I had a kind issue, and solve with this (even I dont understand exaclty why!) Hi Rui, Hi Sara, I attempted to use NTP as you described in your book ESP32/8266 WEB SERVERS, and I also tried this example. But epochTime starts with zero each time. Then continues to increment each second. Any clue? BR Hi. Were you able to solve the problem? Regards, Sara No Sara, it hasn’t been solved. By the way, I forgot to tell you that I am using ESP8266_01 1M chip. On each reset, epoch time starts with zero and then counts on. Years start with tens of thousands BC, days and months with random values. Your help shall be most appreciated. Kind Regards, Hi. What is the version of the ESP8266 boards that you are using? Downgrade to version 2.7.4 (it works well, I’ve tested it) while we cannot find the “real” solution. Regards, Sara Thanks for the instant response Sara, How shall I know the version of my ESP8266-01? It has been sitting in my drawer for 2 years or more. Then next question, how to downgrade it? BR I am using platformIO. The following lines are printed when I connect for uploading code. It seems my board is 3.0.0 version. Then ignore my first question. But the second question still persists. How to downgrade it? Shall I sacrifice any feature by downgrading it? Verbose mode can be enabled via -v, --verboseoption CONFIGURATION: PLATFORM: Espressif 8266 (3.0.0) > Espressif Generic ESP8266 ESP-01 1M HARDWARE: ESP8266 80MHz, 80KB RAM, 1MB Flash Hi. In your VS Code, go to PlatformIO Home. Then, at the left-side bar, select Platforms -> Embedded -> Espressif 8266 Then, next to the “Installation” title there’s a drop-down menu where you can select the version. Regards, Sara Hi Sara, I wanted to give you feedback and ask for additional support. I tried to change the version in VS following your prescription. Although the process seems to progress smoothly, espressif 8266 version still appears to be 3.0.0 on the console. As a result, NTP does not work. So I tried the ezTime library that worked perfectly. But that too works with only dynamic IP allocation in my Async Webserver application. When I attempt to use static IP using the following lines, NTP servers start to timeout. // Connect to Wi-Fi IPAddress ip(192,168,1,180); //Node static IP IPAddress gateway(192,168,1,1); IPAddress subnet(255,255,255,0); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); WiFi.config(ip, gateway, subnet); There may be a problem with the subnet mask, but I am a newbie with Internet protocols, maybe you can help. Static IP is a real need since I don’t know a way to know the IP of my ESP when it is not connected to my PC. I must be able to connect to the ESP server without worrying about the changed IP each time. Thanks in advance, Kind regards, Hi. Can you try that snipet of code for the static IP address without the new NTP code? This way you can figure out if there is some sort of “incompatibility” between the two or if there is something wrong with the static IP. At the moment, I still couldn’t find a way to solve the NTP issue other than using an old version of the ESP8266 boards. Regards, Sara Hi Sara, I have been using those couple of lines on all of my ESP projects without exception for years. My projects are from your books, with that small modification to establish static IP on my connections. I like to have a predetermined IP when playing with ESP8266 and ESP32. That worked also with the project “async web server with charts from file” from your book of WEB SERVERS. I can display charts nicely on clients’ screens. But their time axis’ displaying wrong date/time values since NTPClient is not working properly. In conclusion; Async web servers are working with my static IP initialization lines. But ezTime has a problem with it, the NTP server time-outs with static IP. The issue of the NTPClient is different because it does not work with dynamic IP also. I can not study it more because I couldn’t manage to downgrade the version of espressif 8266. Kind regards, Hi Sara, In return for your kind attention to my questions, I would like to inform you how I resolved this issue: I still use the ezTime library, ESP8266 Espressif 8266 version 3.0.0, and VS Platform IO. After lots of trials and errors, finally I added primary and secondary DNS definitions to my wifi.config call, as follows: IPAddress DNS_1(8, 8, 8, 8); IPAddress DNS_2(8, 8, 4, 4); WiFi.config(ip, gateway, subnet, DNS_1, DNS_2); Now ezTime works as a charm. Kind regards. Great! Thank you so much for taking the time to share this. Regards, Sara Dear Selçuk, Thank you so much for sharing this. Had exactly the same issue with my ESP8266 and static IP and your proposed fix solved it so perfectly ! bib thanks:-) Andre Glad to hear it was useful Andre. Kind regards. Year: 1340177 Current date: 1340177-3-26 As you can see date, the date format and the year is incorrect. Any idea where it has gone wrong ? Regards Sagara I was having this same problem with a NodeMCU 1.0 under MacOS 11.5 (Big Sur). I downgraded to ESP8266 2.7.4 and then started having upload failures. Compile and upload ended with “pyserial or esptool directories not found next to this upload.py tool. An error occurred while uploading the sketch”. The solution to this was found at: PySerial and EspTools Directory Error This involved editing a library file: 1.- Open ~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/pyserial/serial/tools/list_ports_osx.py 2.- Comment out lines 29 and 30 and append these lines: iokit = ctypes.cdll.LoadLibrary(‘/System/Library/Frameworks/IOKit.framework/IOKit’) cf = ctypes.cdll.LoadLibrary(‘/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation’) The code should look like this: #iokit = ctypes.cdll.LoadLibrary(ctypes.util.find_library(‘IOKit’)) #cf = ctypes.cdll.LoadLibrary(ctypes.util.find_library(‘CoreFoundation’)) iokit = ctypes.cdll.LoadLibrary(‘/System/Library/Frameworks/IOKit.framework/IOKit’) cf = ctypes.cdll.LoadLibrary(‘/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation’) Is there a better way to handle this problem? i had never get the date right i use the same code on nodemcu 1.0 i have arduino ide with this verision 1.8.15 and this is the output i got Epoch Time: 1635204557 Formatted Time: 23:29:17 Hour: 23 Minutes: 29 Seconds: 17 Week Day: Monday Month day: 14 Month: 8 Month name: August Year: 1340177 Current date: 1340177-8-14 Hi hasan, i had the same issue with your output, but after downgrade to version 2.7.4 the year issue was solved. previous i used the esp8266 board version 3.0.1, then downgrade to 2.7.4 as per Ms. Sara information i got the correct date.. hope it will solve the issue on your side cheer sonz How do I know if ESP is not receiving time from the ntp server? I need this to reset the ESP from the program. After a power failure, the router works when it returns, but the internet can return after a few minutes and ESP no longer manages to receive the time data unless I reset it while the router is functional and connected to the internet. This circuit requires a backup RTC (ds3231) in case the NTP communications drop away for whatever reason. I don’t want to use rtc, I accept that when there is no internet the clock doesn’t work, I just want as long as there is no internet esp8266 to feel this and keep resetting. Hi, Rui, Sara, This has been very helpful, but like others, I want to be near a WiFi, get the time, then move my device out into the garden where there is no WiFi. I have only started on this, I have not done any extensive testing. I am not a good programmer, but am cobbling together a work-around. Maybe Rui/Sara, you can make a follow-up tutorial with fix ? C++ has some system help here. This small code should work without any external help. But, it should return the epoch time starting at 00:00 Jan 1 1970 and count up using the internal time. It does not have any link to a WiFi, it is a bare minimum code and uses system defined variables. void setup() { } Serial.begin(115200); void loop() { } time_t current = time(nullptr); // increments internal clock Serial.print(ctime(¤t)); delay(500); The above shows the variables are system variables. Assume that when you upload, you are near a WiFi and can get NTP time. in setup() WiFi.begin(ssid, pass); // starts the connection } while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(“.”) ; in loop() if (WiFi.status() == WL_CONNECTED) { } unsigned long epochTime = timeClient.getEpochTime(); while (WiFi.status() != WL_CONNECTED) { // lastUpdateTime = 1640488470 // get from NTP attempt 1 use hard number lastUpdateTime = epochTime // get from NTP attempt 2 use epochTime. // time_t current = time(nullptr); // increments internal clock attempt 1 verify system clock // time_t current = 1640488470+time(nullptr); // adds NTP time attempt 2 use hard code time_t current = lastUpdateTime+time(nullptr); // adds NTP time attempt 3 use epoch time Serial.print(ctime(¤t)); // prints formatted as Sun Dec 26 11:15:31 2021 delay(500); } // ======== END if(while ! Connected ===== If power is lost, then the system clock and epochTime will both be lost but, the internal timer will start at 00:00 Jan1 1970 so you will be able to know when power was lost and when epochTime is available, it will correct for future readings. It would allow you to go back, and fix the time for the data. MISSING : lost_Time = epochTime – lastUpdateTime ; to know the time lost/gained when not connected. I have one device I use to test things while out in the garden. Usually less than one hour. Take readings every 15 seconds I have a device I put out and leave for a week, then bring in and download the data. Take readings every 30 minutes WISH LIST : possibly a separate tutorial go to the garden with the Android phone, connect, pass EPOCH_TIME and download the data file saved in SPIFFS/LITTLEfs in my case, my readings are temperature, sunlight, soil and are done every 30 minutes. Hello I had the issue of: Epoch Time: 1642509190 Formatted Time: 12:33:10 Hour: 12 Minutes: 33 Seconds: 10 Week Day: Tuesday Month day: 6 Month: 4 Month name: April Year: 1340722 Current date: 1340722-4-6 After a lot of research (without result) I made the following change in the code in line 59: insted of unsigned long epochTime = timeClient.getEpochTime(); I used: unsigned long long epochTime = timeClient.getEpochTime(); After this the app start to calculate correctly the date. Thanks for the app. working WELL! Thanks Mr. Ferenc Kovacs. Have good days! Hi. You can use time_t epochTime = timeClient.getEpochTime(); I updated the code just now. Regards, Sara A get a wrong year, I have to change from //unsigned long epochTime = timeClient.getEpochTime(); to time_t epochTime = timeClient.getEpochTime(); // was unsigned long I do not kow the update who ignite that. Look at my example here: Not need any external library, just use #include “time.h” you can set your time zone and day saving with this lines: String TimeZone = “CET-1CEST,M3.5.0,M10.5.0/3”; /* Rome */ and in this link you can see all world time zones string ESP32 at start show 1970 how current year, so i use this approach for wait NTP server response ok while (Year == “1970”) { } getLocalTime(&timeinfo); strftime(TT, sizeof(TT), “%Y”, &timeinfo); Year = String(TT); where TT is a char array Hello, I’d like to share my idea to you. I had a problem with crashed or incomplete information from NTP printed to the serial monitor and sometimes also with showing the downloaded time on my 7segment display – the time started from 01:00:00. It seems like a problem with very fast comunication to me, so i put some delay(50) instructions among the lines wifi.begin, timeClient.begin and Serial.print. Now the connecting process is more stable and problem with crashed information is really fixed. Thanks for sharing. Regards, Sara
https://randomnerdtutorials.com/esp8266-nodemcu-date-time-ntp-client-server-arduino/
CC-MAIN-2022-21
refinedweb
4,906
66.44
Another Java 7 blog, this time it's about the new concurrency utilities. It's about plain fork and join in particular. Everything is explained with a straight code example. Compared to Project Coin concurrency is an inherently complex topic. The code example is a little more complex. Let's get started. The Fork and Join Executor Service Fork and join employs an efficient task scheduling algorithm that ensures optimized resource usage (memory and cpu) on multi core machines. That algorithm is known as "work stealing". Idle threads in a fork join pool attempt to find and execute subtasks created by other active threads. This is very efficient 'cause larger units get divided into smaller units of work that get distributed accross all active threads (and CPU's). Here is an analogy to explain the strength of fork and join algorithms: if you have a jam jar and you fill it with ping-pong balls, there is a lot air left in the glass. Think of the air as unused CPU resource. If you fill your jam jar with peas (or sand) there is less air in the glass. Fork and join is like filling the jam jar with peas. There is also more volume in your glass using peas, 'cause there is less air (less waste). Fork and join algorithms always ensure an optimal (smaller) number of active threads then work sharing algorithms. This is for the same "peas reason". Think of the jam jar being your thread pool and the peas are your tasks. With fork and join you can host more tasks (and complete volume) with the same amount of threads (in the same jam jar). Here is a plain fork and join code example: import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; public class ForkJoinTaskExample_Plain extends RecursiveTask<List<Map<String, Double>>> { private List<Proposal> proposals; private static final long serialVersionUID = -2703342063482619328L; public ForkJoinTaskExample_Plain(List<Proposal> proposals) { super(); this.proposals = proposals; } @Override protected List<Map<String, Double>> compute() { if (proposals.size() == 1) { // task is small enough to compute linear in this thread return Arrays.asList(computeDirectly(proposals.get(0))); } // task is to large for one thread to execute efficiently, split the task // make sure splitting of tasks makes sense! tasks must not be too small ... int split = proposals.size() / 2; ForkJoinTaskExample_Plain f1 = new ForkJoinTaskExample_Plain(proposals.subList(0, split)); f1.fork(); // generate task for some other thread that can execute on some other CPU ForkJoinTaskExample_Plain f2 = new ForkJoinTaskExample_Plain(proposals.subList(split, proposals.size())); List<Map<String, Double>> newList = new ArrayList<>(); newList.addAll(f2.compute()); // compute this sub task in the current thread newList.addAll(f1.join()); // join the results of the other sub task return newList; } private Map<String, Double> computeDirectly(Proposal proposal) { return new PricingEngine().calculatePrices(proposal); } public static void main(String[] args) { // Calculate four proposals ForkJoinTaskExample_Plain task = new ForkJoinTaskExample_Plain(Arrays.asList(new Proposal("Niklas", "Schlimm", "7909", "AAL", true, true, true), new Proposal("Andreas", "Fritz", "0005", "432", true, true, true), new Proposal("Christian", "Toennessen", "0583", "442", true, true, true), new Proposal("Frank", "Hinkel", "4026", "AAA", true, true, true))); ForkJoinPool pool = new ForkJoinPool(); System.out.println(new Date()); System.out.println(pool.invoke(task)); System.out.println(new Date()); } } Fork and join tasks always have a similar typical fork and join control flow. In my example I do want to calculate the prices for a list of car insurance offers. Let's go through the example. Line 10: Fork and join tasks extend RecursiveTask or RecursiveAction. Tasks do return a result, actions doesn't. The result of my example is a List of Maps which contain the prices for the car insurance covers. One map of prices for each proposal. Line 12: The task will calculate prices for proposals. Line 22: Fork and join tasks implement the compute method. Again, the compute method returns a list of maps that contain prices. If there are four proposals in the input list, then there will be four maps of prices. Line 24-26: Is the task stack (list of proposals) small enough to compute directly? If yes, then compute in this thread, which means call the pricing engine to calculate the proposal. If no, continue: split the work and call task recursively. Line 31: Determine where to split the list. Line 33: Create a new task for the first part of the split list. Line 34: Fork that task: allow some other thread to perform that smaller subtask. That thread will call compute recursively on that subtask instance. Line 35: Create a new task for the second part of the split list. Line 36: Prepare the composed result list of the two devided subtask (you need to compose the results of the two subtwasks into a single result of the parent task) Line 37: Compute the second subtask in this current thread and add the result to the result list. Line 38: In the meantime the first subtask f1 was computed by some other thread. Join the result of the first subtask into the composed result list. Line 39: Return the composed result. You need to start the fork and join task. Line 49: Create the main fork and join task with the initial list of proposals. Line 53: Create a fork and join thread pool. Line 55: Submit the main task to the fork and join pool. That's it. You can look into the complete code here. You'll need the PricingEngine.java and the Proposal.java. From {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/java-7-fork-and-join-and-jam
CC-MAIN-2017-17
refinedweb
944
67.76
std::vector<int> v{ 1, 2, 3 }; v.pop_back(); // v becomes {1, 2} std::vector<int> v{ 1, 2, 3 }; v.clear(); // v becomes an empty vector std::vector<int> v{ 1, 2, 3, 4, 5, 6 }; v.erase(v.begin() + 3); // v becomes {1, 2, 3, 5, 6} Note: For a vector deleting an element which is not the last element, all elements beyond the deleted element have to be copied or moved to fill the gap, see the note below and std::list. std::vector<int> v{ 1, 2, 3, 4, 5, 6 }; v.erase(v.begin() + 1, v.begin() + 5); // v becomes {1, 6} Note: The above methods do not change the capacity of the vector, only the size. See Vector Size and Capacity. The erase method, which removes a range of elements, is often used as a part of the erase-remove idiom. That is, first std::remove moves some elements to the end of the vector, and then erase chops them off. This is a relatively inefficient operation for any indices less than the last index of the vector because all elements after the erased segments must be relocated to new positions. For speed critical applications that require efficient removal of arbitrary elements in a container, see std::list. std::vector<int> v{ 1, 1, 2, 2, 3, 3 }; int value_to_remove = 2; v.erase(std::remove(v.begin(), v.end(), value_to_remove), v.end()); // v becomes {1, 1, 3, 3} // std::remove_if needs a function, that takes a vector element as argument and returns true, // if the element shall be removed bool _predicate(const int& element) { return (element > 3); // This will cause all elements to be deleted that are larger than 3 } ... std::vector<int> v{ 1, 2, 3, 4, 5, 6 }; v.erase(std::remove_if(v.begin(), v.end(), _predicate), v.end()); // v becomes {1, 2, 3} std::vector<int> v{ 1, 2, 3, 4, 5, 6 }; v.erase(std::remove_if(v.begin(), v.end(), [](auto& element){return element > 3;} ), v.end() ); std::vector<int> v{ 1, 2, 3, 4, 5, 6 }; std::vector<int>::iterator it = v.begin(); while (it != v.end()) { if (condition) it = v.erase(it); // after erasing, 'it' will be set to the next element in v else ++it; // manually set 'it' to the next element in v } While it is important not to increment it in case of a deletion, you should consider using a different method when then erasing repeatedly in a loop. Consider remove_if for a more efficient way. std::vector<int> v{ -1, 0, 1, 2, 3, 4, 5, 6 }; typedef std::vector<int>::reverse_iterator rev_itr; rev_itr it = v.rbegin(); while (it != v.rend()) { // after the loop only '0' will be in v int value = *it; if (value) { ++it; // See explanation below for the following line. it = rev_itr(v.erase(it.base())); } else ++it; } Note some points for the preceding loop: Given a reverse iterator it pointing to some element, the method base gives the regular (non-reverse) iterator pointing to the same element. vector::erase(iterator) erases the element pointed to by an iterator, and returns an iterator to the element that followed the given element. reverse_iterator::reverse_iterator(iterator) constructs a reverse iterator from an iterator. Put altogether, the line it = rev_itr(v.erase(it.base())) says: take the reverse iterator it, have v erase the element pointed by its regular iterator; take the resulting iterator, construct a reverse iterator from it, and assign it to the reverse iterator it. Deleting all elements using v.clear() does not free up memory ( capacity() of the vector remains unchanged). To reclaim space, use: std::vector<int>().swap(v); shrink_to_fit() frees up unused vector capacity: v.shrink_to_fit(); The shrink_to_fit does not guarantee to really reclaim space, but most current implementations do.
https://riptutorial.com/cplusplus/example/2156/deleting-elements
CC-MAIN-2022-05
refinedweb
632
56.45
Python macro: Update cell contents during execution Hi. I have a problem, similar to this question (The provided answer does not work for me). I have a python macro in a Calc document that runs a long calculation and I would like to update cell contents during the macro's execution. Here is a simple example: import time def myfunction(*args): desktop = XSCRIPTCONTEXT.getDesktop() model = desktop.getCurrentComponent() sheet = model.CurrentController.ActiveSheet cell = sheet.getCellByPosition(0, 0) cell.setString("In progress...") # Some long calculation time.sleep(5) cell = sheet.getCellByPosition(1, 0) cell.setString("done.") return None My problem is that "In progress" is not displayed until the function returns, when "In progress..." and "done." appear at once. Is there a way to update cell contents during the execution of the macro? I have attached a document with the macro included.
https://ask.libreoffice.org/en/question/166963/python-macro-update-cell-contents-during-execution/
CC-MAIN-2019-09
refinedweb
140
54.59
Difference Between HashMap And HashTable 1. Synchronization or Thread Safe : This is the most important difference between two. HashMap is non synchronized and not thread safe. On the other hand, HashTable is thread safe and synchronized. 2. Null keys and null values : Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object. 3. Iterating the values: Hashmap object values are iterated by using iterator. HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object. 4. Performance : Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment. in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multi threaded application prefer ConcurrentHashMap instead of Hashtable. Example of HashMap and HashTable public class HashMapHashtableExample { public static void main(String[] args) { Hashtable<String,String> hashtableobj = new Hashtable<String, String>(); hashtableobj.put("Crazyfor ", "code"); hashtableobj.put("Love", "the site"); System.out.println("Hashtable object output :"+ hashtableobj); HashMap hashmapobj = new HashMap(); hashmapobj.put("Crazyfor ", "code"); hashmapobj.put("Love", "the site"); System.out.println("HashMap object output :"+hashmapobj); } } Output : Hashtable object output :{Love=the site, Crazyfor =code} HashMap object output :{Crazyfor =code, Love=the site}
http://www.crazyforcode.com/difference-hashmap-hashtable/
CC-MAIN-2016-50
refinedweb
231
60.21
Hi! I worked some more on my GNAP patchset, improved some stuff and split it up nicer. This 5 emails deprecate the previous patchset i found. There are also some bugs i fixed recently, after i send this stuff to BaSS. Since I'm only working with gnap_make at the moment, i did no testing with the other scripts. So any testing and comments are apreciated. The patches are: 01-gnap-cleanup.patch 02-gnap-split.patch 03-gnap-namespace.patch 04-gnap-environment.patch I will send them as replies to this email.. Thanks, Philipp -- gnap-dev@g.o mailing list
https://archives.gentoo.org/gnap-dev/message/e15facfe7751a9aa664e05f63febada4
CC-MAIN-2017-22
refinedweb
102
70.19
Plone 4.0.3 4.0.3 - 2011-01-18 -] 4.0.2 - 2010-11-15 -]] 4.0a3 - 2009-12-21 - Updated statusmessages code to more modern API. [hannosch] - Updated add-on configuration section. Clarified terminology to refer to de/activation and interpret product readme files as restructered text. [hannosch] - Adjusted control panel and upgrade screens to show software instead of profile version and removed dependency on the persistent product registry. [hannosch] - Changed the default profile metadata version to 4003, to follow our own best practices of distinguishing between profile and software versions. [hannosch] - Added Plone site back to the all_meta_types list and revert change that made the site object not copyable. These prevented Plone sites from being imported from zexp files. [hannosch] - Do not display the author contact form when the author has no email (for example for openid users). Refs #8707. [maurits] - Only specify icon_expr in factory type info; not also content_icon which has been deprecated in CMF 2.2. [davisagli] - Optimize RSS template and make it work for items without a getText method. This closes. [hannosch] - Define encoding for RSS feeds. This closes. [hannosch] - On author.cpt, only display the “log in to add comments” button if mailhost is defined. Only show the mailhost warning if user is authenticated. [esteele] - Adjusted rss_template to work for content items without an effective date and include issued and modified tags. Thanks for the patch anthonygerrard. This closes. [hannosch] 4.0a2 - 2009-12-03 - Restore the ability to add Plone sites within ZODB mountpoints (and other OFS folders). [davisagli] - Move prefs_navigation_form to plone.app.controlpanel as @@navigation-controlpanel. The form and its cpy script have been deprecated. [esteele] - Use the @@plone-upgrade view as the default management screen for the migration tool. [davisagli] - Respect multibyte language delimiter in search field. This closes. [hannosch] - RegistrationTool’s registeredNotify now sends mail immediately instead of waiting until the end of the transaction. This puts the function back in line with the way the method worked in previous versions of Plone. [esteele] - Create normal folders instead of Large Folders (which are deprecated) for the initial example content. All folders are now BTree-based. [davisagli] - fixed validation of prefs_main_template for plonetheme.classic [spliter] - re-applied fix for plone.css by aaronv. Fixes #9366 and #9761 [spliter] - moved plone.css.py to CMFPlone in order to share it among all themes [spliter] - moved “Manage portlets” fallback link out of main_template to plone.manage_portlets_fallback viewlet [spliter] - Point the “Join” action the newly-renamed @@register view. [esteele] - Remove calendarpopup.js from jsregistry.xml. It no longer exists. [hannosch] - Depend on plone.app.upgrade so it gets installed by default. Keeping the upgrade package separate only made sense when it had massively more dependencies than Plone itself. That cleanup isn’t part of Plone 4.0. [hannosch] - Added back an utranslate function to the i18nl10n module that retains the old call signature. [hannosch] 4.0a1 - 2009-11-19 - Moved Image Handling control panel into the main Plone category. It’s not an add-on anymore. [hannosch] - Clarified the default labels shown on the site setup overview page. [hannosch] - Adjust tests to new Archetypes behavior, which respects the default language of the portal_languages tool. [hannosch] - Adjust the _createObjectByType functions in utils and FactoryTool to use the _constructInstance method of the FTI instead of duplicating pieces of its logic. [davisagli] - By default hide the “Subfolders” tab on collections. They don’t behave in a way understandable to users. Existing sites aren’t changed. [hannosch] - Converted plone_javascript_variables.js to a browser page. Dynamically generating JS using a page template was too cumbersome. This also avoids the special escape_for_js handling of the translate script. [hannosch] - “Relevance” was not internationalized in search_form.pt. This closes [vincentfretin] - “Your Plone site is up to date” was not internationalized in plone-upgrade.pt. This closes [vincentfretin] - “Preferences” link should go directly to the personal prefs, the memberprefs panel is an unnecessary abstraction here. Add-on products can easily add new links to the personal menu now, so that’s the pattern we want to encourage. - Removed the login portlet from the default setup now that the login link opens an inline window. [limi] - Fixed a DYNAMIC_CONTENT in site_feedback_template.pt [vincentfretin] - Make sure the ‘Portlets: View dashboard’ permission is set for Members. [davisagli] - Make sure the mock MailHost used in tests is registered as a local utility so that it can be found via getToolByName. [davisagli] - Moved all CSS styles to plonetheme.classic package. plonetheme.sunburst is now default theme, both are installed by default, classic theme may be uninstalled, sunburst theme can’t be uninstalled. [limi, naro] - Added site_encoding and bodyClass methods to the @@plone view. These should simplify main template a bit. [naro] - Avoid AttributeError while getting the CMF version for the plone_control_panel when enable-product-installation is off in zope.conf. [maurits] - Fixed bad internationalized messages in logged_out.pt [vincentfretin] - Changed default message for label_show_all msgid from “Show all…” to “Show all items” in livesearch_reply.py to be the same as in folder_contents view which use the same msgid. [vincentfretin] - Use the new pas_member view in the overview templates. This avoids getting the member info for each item in the listing from the PAS internals. [hannosch] - registerNotify and mailPassword now send properly encoded emails. Fixes [alecm] - Deprecated register.py and join_form.cpt. This functionality has been moved to plone.app.users. [esteele] - Changed listActions on the workflow tool to no longer call the listGlobalActions method on every installed workflow. This method would internally call and calculate the worklist (reviewer_queue) for every workflow. The listActions method is called by the workflow menu to show the state drop down menu on almost all pages. [hannosch] - Deprecated the selectedTabs script in favor of a method on the GlobalSectionsViewlet. [hannosch] - Micro-optimize the CatalogNavigationTabs view. [hannosch] - Added a more prominent upgrade warning to the top of the ZMI screen, instead of the old tiny note on the portal migration tool. [hannosch] - Added a new @@plone-upgrade view, which replaces the old migration tool DTML ZMI screens. [hannosch] - Added a simple advanced mode to the add site form. If advanced is passed as a query argument to the @@plone-addsite more options are available. The button in the ZMI uses the advanced mode by default. Currently the choice of omitting the default content and deselecting any of the default extension profiles are limited to the advanced mode. [hannosch] - Expose the site language in the add site form and refactor the language guessing based on the browser language into that view. The addPloneSite function takes an explicit argument for the language now. [hannosch] - Hardcode utf-8 for UnicodeSplitter, since Hanno says that’s all we can accept and there’s no way to use getSiteEncoding from the splitter. [alecm] - Added option to skip the creation of the default example content in the new add site form. Grouped the add-ons selection via a fieldset. [hannosch] - Refactored the old factory dispatcher / addPloneSiteForm to use a modern browser page instead. [hannosch] - Removed the special default page and translation handling. LinguaPlone uses a content language negotiator per default instead. [hannosch] - Replaced highlightsearchterms.js with the Plone trunk jquery.highlightsearchterms.js plugin. This removes the need to add searchterm= query parameters to search.pt results. Refs. [mj] - Add a link to log out from the logged_out template if logged in as a Zope user via basic HTTP Authentication and the standard logout failed. [davisagli] - Removed the cut/copy/paste icons from the action menu in new sites, as they just add noise + more HTTP requests. [limi] - Moved happytalk in site_feedback_template.pt and author_feedback_template.pt to bottom of emails, per [jonstahl] - Added precedence: bulk header to several PasswordReset’s mail_password_template, per - still haven’t added this header to CMFPlone templates. [jonstahl] - Added the upgrade warning to the main control panel screen. This is the same as found on the new overview page. [hannosch] - Changed the new default overview page to be a normal browser page and made it aware of multiple Plone sites in the root or in ZODB mountpoints. [hannosch, davisagli] - Overwrote the Zope quick start page, with a more helpful Plone specific version as already found in the unified installer. [hannosch] - Turned the new add Plone site button in the ZMI into a link. This allows us to get out of the frameset to the top. [hannosch] - Add jQueryTools integration, using plone.app.jquerytools. [smcmahon] - Updated our add site ZMI screen. [hannosch] - Changed search.pt (plone_forms) and rss_template.pt (plone_templates) so they display fullname instead of creator. [ralphjacobs] - Cleaned up old an unused scripts to edit the plone site object itself. This is done via the site control panel now. [hannosch] - Hide the TinyMCE profiles hidden from the Plone site add form. [robgietema] - Added ‘Use site default’ to the wysiwyg_editor field in the Personal Preferences view. [robgietema] - Set default value of wysiwyg_editor to blank (use site default). [robgietema] - Added default editor property to the site properties. [robgietema] - Added TinyMCE and set TinyMCE as default visual editor. [robgietema] - Removed getProductInfo method from the migration tool. It wasn’t used anymore and depended on the persistent product registry. [hannosch] - Inlined the enableSyndication function into importFinalSteps in setuphandlers. Avoid an unneeded catalog search. [hannosch] - Simplified portal creation code and got rid of the PloneGenerator class in setuphandlers. It was a useless closure for independent functions. [hannosch] - Removed the plone-site import step and stop overriding the componentregistry step. The portal object directly implements the IObjectManagerSite interface, so we don’t need to activate it as a site manager in an extra step anymore. [hannosch] - Updated and added various ZMI-visible tool titles. [hannosch] - Removed the plone-archetypes import step. This is handled via a normal GenericSetup dependency in metadata.xml. [hannosch] - Merged the plone_various import step into the plone-final step and install more packages directly by their profiles. [hannosch] - Removed the zserverPatch. There’s not many people running ZServer as the front-end web server anymore, so this isn’t particular useful. [hannosch] - Fixed the default portlet blacklisting for the Members folder. [hannosch] - Replaced Products.ATReferenceBrowserWidget with archetypes.referencebrowserwidget. This is PLIP 9258 [tom_gross] - Clarified help text for extension profiles on the add site form. [davisagli] - Added a mechanism for specifying profiles that are selected by default on the add site form. This should be kept in sync with PloneTestCase’s list of default extension profiles. [davisagli] - Hide the plonetheme.sunburst uninstall profile from the add site form. [davisagli] - Default to plonetheme.sunburst for new sites. [esteele, davisagli] - Allow email addresses as login name, with a switch on the security panel. This is plip 9214: Refs. [maurits] - Extend the language specific default configuration to set a reasonable first day of week on the calendar tool. [hannosch] - Stop pretending to use GenericSetup’s content import. As a last item we now create the translated front-page purely in imperative code. As a bonus we moved the body text of the front-page to a page template, so i18ndude can automatically extract it. [hannosch] - Create and configure Members folder purely in setupPortalContent. [hannosch] - Converted import and export steps XML files to use ZCML registrations. [hannosch] - Made sure to have a complete list of non-installable profiles. No longer apply the filter to base profiles and ignore our default profile. This works in combination with the corresponding changes in quick installer to reduce portal creation time. [hannosch] - Make use of the new authenticated flag for ResourceRegistries entries instead of specifying verbose condition expressions. [hannosch] - “Categories” are now “Tags”, in line with common usage and terminology. [limi] - Changed workflow actor variable from user/getUserName to user/getId.. [hannosch] - Removed the AT graphviz references action from all content types. [davisagli] - Finished switching tool and action icons to use PNG format. [davisagli] - Exclude some of the CMFDefault functionality, that isn’t used or usable inside Plone sites. The CMFDefault types are no longer supported. [hannosch] - Move prefs_users_overview and prefs_groups_overview pages to plone.app.controlpanel (@@usergroup-userprefs and @@usergroup-groupprefs respectively). [esteele] - Adjust to CMF’s splitting of CMFCatalogAware into separate CatalogAware, WorkflowAware, and OpaqueItemManager mixins. [davisagli] - Added zope.app.locales dependency, some strings are in zope domain such as ‘Invalid value’ and ‘(no value)’ found in portlet EditForm. [vincentfretin] - Moved membershipRolemapping.dtml and portrait_fix.dtml to PlonePAS. [davisagli] - Added icon_expr property to the Plone control panel tool actions, and switched to registering configlet icons here instead of in the action icons tool. [davisagli] - Moved the diff tool registration to this package, so it can still be a tool for Plone 4. [davisagli] - Use the new zope.ramcache in favor of zope.app.cache. [hannosch] - Removed GroupUserFolder skin layers. [davisagli] - Silenced the deprecation warning about old-style actions from CMFCore’s ActionProviderBase when listing configlets with the control panel tool. [davisagli] - Added the _IMREALLYPLONE4 hint to factory.py for PloneTestCase to use. [hannosch] - Removed the calendar and review portlets from the standard global assignments. The review list is better put onto a personal dashboard and the calendar is exceptionally slow and rather user unfriendly. The news and events portlets are a better fit to show-case the portlets system. [hannosch] - Include the overrides.zcml from Products.PlacelessTranslationService to actually make PTS’ language negotiator available to the zope.i18n machinery. [hannosch] - Got rid of the ToolNames indirection and declared the meta_types directly in the relevant tool class themselves. [hannosch] - Moved ATCT specific exportimport code into the ATCT package itself. [hannosch] - Made sure the plone.indexer registration works by introducing a more specific IPloneCatalogTool marker interface and registering the indexable object wrapper for this. [optilude] - Added a restricted version of the opaqueItems method for CMFCatalogAware. This takes the idea of experimental.opaquespeedup one step further. [hannosch] - Actually made the types tool action lookup optimization effective. Slightly optimized the add items drop-down menu. [hannosch] - Removed the ResourceRegistries skin layer. It only contained test code. [hannosch] - Make use of the new IContainer API of object managers and replace objectIds and objectValues calls. [hannosch] - Finally removed the interfacePatch for the IContainer interface of OFS.ObjectManager after it has been merged upstream. [hannosch] - Removed CMFTopic from our dependency list, it turns out that we aren’t actually using any of it. [hannosch] - Added proper deprecation warnings for the IBrowserDefault, IDynamicViewTypeInformation and ISelectableBrowserDefault interfaces, who has always come from Products.CMFDynamicViewFTI. [hannosch] - Use the replace_local_role_manager method from borg.localrole. [hannosch] - Deprecate our own IOrderedContainer interface in favor of the original one from OFS. [hannosch] - Avoid dependency on the zope.app.zapi package. [hannosch] - Declare package dependencies and fixed deprecation warnings for use of Globals. [hannosch] - No longer depend on the PageTemplates.GlobalTranslationService but use zope.i18n directly. [hannosch] - Merged in more performance optimizations from experimental.contentcreation. We don’t restrict the permissions for the temporary folder anymore, but only care about the permissions of the actual target folder. [hannosch] - Use the new icon_expr for specifying icons for content types instead. [hannosch] - Prefer path expressions over Python expressions for persistent expressions. [hannosch] - Fixed the content_status_history form to include the required content table. The old_folder_contents template is gone. [hannosch] - Fixed the browserDefault tests to use actual traversal to look up views for content items instead of relying on Acquisition. [hannosch] - Moved the scale_image function from utils into the PlonePAS.utils module, as PlonePAS is the only user of it. [hannosch] - The remaining functionality from GroupUserFolder has been merged into the PlonePAS package. GroupUserFolder is no longer required. [hannosch] - Removed the groups, groupdata, membership and memberdata tools from this package. All code is now in a central place inside PlonePAS. The persistent tools have been from the PlonePAS package since Plone 2.5. [hannosch] - Replaced has_key method calls with containment checks via in. [hannosch] - Replaced a direct interface invocation with a queryAdapter call, to avoid an internal getattr call and make the pattern clearer. [hannosch] - Replaced here with context in all templates and scripts. The old spelling is still supported, but we need to settle on one to avoid confusion. [hannosch] - Optimized the types tool action lookup further to avoid Acquisition lookups. [hannosch] - Simplified the normalizeString method. [hannosch] - Optimized the action lookup code and implemented category restriction for the types tool in the same way it was available for the actions tool. [hannosch] - Removed remaining sys.modules hacks to provide the browser.ploneview as browser.plone. [hannosch] - Removed last unused external methods and PloneInitialize code. To my knowledge the Windows installer doesn’t use this code anymore. [hannosch] - Write the doctype definition in the main_template in a way that does not claim to be valid XML, as the main_template really isn’t. [hannosch] - Worked around sys._getframe call in mark_view. [malthe, hannosch] - Removed macro slot for changing the document type; this was not correct XML and should this flexibility be required, it’s recommended to customize main_template.pt. [malthe] - Turned deprecated string ‘Unauthorized’ exceptions into real exceptions. [davisagli] - Removed module alias for the ploneview formerly named plone. [hannosch] - Clarified content language versus response language handling. [hannosch] - Removed unmaintained and unused Favorite content type. [hannosch] - Removed our own home-grown dependency checking code. [hannosch] - Exposed option to honour exclude from navigation even in subfolders from navtree_preferences. Request from theming sprinter at ploneconf2008. [MatthewWilkes] - Made the fieldset tabbing code faster on startup (especially for IE) by constructing a big string and creating the HTML elements in one bunch instead of using DOM functions to add them step by step. [fschulze] - Added uniqueItemIndex as a method to the plone view. [hannosch] - Added back global_defines.pt as a template including the (empty) macro definition. This allows main templates to be compatible with both Plone 3.x and 4.0 at the same time. [hannosch] - Removed global_defines.pt and the globalize-hack. Templates now bring in their tool and function dependency using the standard utility views or via normal Acquisition of tools. [malthe, hannosch] - Fixed test for editing language fields. This refs. [hannosch] - Removed deprecated context parameter in getDefaultPage and isDefaultPage in utils.py. [maurits] - Made sure the export order of the factory tool GS step is consistent. This closes. [hannosch] - Replaced lock_icon with smaller version with one third of the size. [hannosch] - Removed backwards-compatibility code in calendar_formfields.js introduced in Plone 3.1.4. Any date-time picker not based on calendar_macros.pt using the old-style (no plone.jscalendar namespace) methods will no longer work until adjusted. [mj] - Don’t show relevance information of one percent in the search form, since sort_on searches will always show this for all entries This closes [hannosch] - Removed duplicated isMemberIdAllowed method from registration tool. [hannosch] - Fixed mailto link in event view and enhanced the spam protect script to allow setting css ids on the generated anchor tag. This closes [hannosch] - Fixed contact form to be usable for authenticated users which have no email address stored in their member data. This closes [hannosch] - Avoid empty tags in the contact form. This closes [hannosch] - Avoid an empty div in login_form. This closes [hannosch] - Avoid an empty dd in recently modified.pt. This closes [hannosch] - Avoid an empty span in folder_summary_view. This closes [hannosch] - Changed wording in personalize form to remove reference to external editor icon and add a note about ZopeEditManager. This closes [hannosch] - Changed webstats_js in portal properties to a text field. This refs [hannosch] - Added option to the error log control panel to search for an error log entry by number, since the number is the only thing that is exposed to normal users. This closes [hannosch] - Changed title of collections control panel to plural form. This closes [hannosch] - Include link to the plone.org upgrade manual from the migration tool inside the ZMI. This closes [hannosch] - Clarify help text in content_status_history. This closes [hannosch] - Let default RSS list publication date, not modified date and include the body text. This closes [hannosch] - Updated the check_id script to disallowed content by the name of properties. This closes [hannosch] - Fixed invalid markup in membershipRolemapping.dtml. This closes [hannosch] - Removed long unused getObjPositionInParent.py script which wasn’t functional at all anymore, since it used Zope 2 interfaces. Also simplified the getObjPositionInParent function in the CatalogTool. This closes [hannosch] - Removed getActionObject call from createObject script. It was a private method and would always fail. This closes [hannosch] - Removed testing of sendto action visibilty from sendto.cpy. There’s a permission to use to restrict sending mail. This closes [hannosch] - Disable external editor icon for structural folders. This closes [hannosch] - Updated the check_id script to disallowed content by the name of zip or plone since this shadows the views by those names. This closes [hannosch] - Purged old Zope 2 Interface interfaces for Zope 2.12 compatibility. [elro] - Make use of upgrade steps with a source ‘*’ version and an explicit destination, to register the ‘enable site’ and ‘register tools as utilities’ only once. [hannosch] - Added support for upgrade step groups to the migration tool and started exposing the individual upgrade methods as steps. [hannosch] - Changed the way messages are handled during migration. We don’t pass an out list around anymore, but use the logging framework. [hannosch] - Replaced our own migration step registration by using GenericSetup steps directly. Changed the migration tool to integrate with GS instead. Added BBB code to read the instance version from the migration tool if the last profile version isn’t set yet inside the GS tool. [hannosch] - Exposed all our migration steps as GenericSetup upgrade steps. [hannosch] - Hide the deprecation warning about the moved ITranslatable interface for our own code. [hannosch] - Use png icons instead of gif icons since they are much more flexible for styling. [dannyb, wichert] - Fixed the coreVersions method in MigrationTool to return strings and not bound methods for the Zope and Python version. [hannosch] - Fixed off-by-two error in transaction_note. This closes [hannosch] - Moved all icons for real actions from the action icons tool to the actions themselves. [hannosch] - Changed PloneTool’s getIconFor method to prefer the icon expression set on the action itself instead of looking it up in the action icons tool. This finally makes use of the new icon expression on actions introduced in CMF 2.1. [hannosch] - Avoid unneeded line breaks in TAL output, by effectively disabling the internal beautified wrapping inside tags. This reduces the HTML output by 5% - 10% for normal Plone pages. [hannosch] - Memoize the installed products and packages in App.FactoryDispatcher for the duration of the process runtime. [hannosch] - Hiding page history, page navigation, and busy icon (spinner) in print.css Related to [siebo] - Updated webdav_enabled method in utils.py to check for webdav.interfaces.IWriteLock interface in addition to the old Zope2 interface. [hannosch] - Use a FauxArchetypeTool which returns no catalogs for CatalogMultiplex aware objects in portal factory. This prevents most temporary objects from being indexed in the first place. [tesdal, hannosch] - Move our GenericSetup import step registrations to zcml. [wichert] - Added a ‘do-not-use’ warning to the ZMI security screen for Plone content objects. Sharing tab or workflows are what you are looking for. [hannosch] - Moved interface declarations for factorytool from ZCML to the class. [hannosch] - Added BBB code for ITranslatable, which is now part of LinguaPlone. [hannosch] - Added an explicit button to add a new Plone site to the ZMI for faster access. If you have installed Plone this is probably what you want to add most of the time. The button only shows up in the root folder. [hannosch] - Deprecate the ITranslatable interface. This interface is LinguaPlone- specific and has thus been moved to LinguaPlone. [wichert] - Removed tests for isRTL method of PTS. The method was deprecated in the last release and is gone now. [hannosch] - Removed PTSTranslationDomain utilities. PTS exposes all translation files as pure Zope3 translation utilities now, so these aren’t needed anymore. [hannosch] - Replaced our FasterStringIO implementation by one based on collections.deque, which is a faster than StringIO. [hannosch] - Removed more deprecated code, adjusted some comments. [hannosch] - Tweaked sortable_title method to give reasonable results for titles with many numbers in them, like ‘1.2.3 document’. [hannosch] - Moved CMF skins registration into configure.zcml, removed security declaration for no-longer extant listPolicies of the portal. [hannosch] - Refactored initial content creation into a separate extension profile, thus making it possible to skip it. This refs [hannosch] - Removed some outdated Extension scripts. [hannosch] - Removed deprecated tool related Zope2 interfaces. Extended the deprecation period for ConstrainTypes and NonStructuralFolder as these are still used in Plone Core. [hannosch] - Removed work-around code for insertion of non-unicode non-ascii non-utf8 encoded text in TAL. This will produce an error now. Always use Unicode when using data in page templates and TAL. [hannosch] - Removed lots of deprecated code and zcml registrations. [hannosch] - Fixed ticket #9420 DC.date.valid_range not emitted if only Publishing Date is set. [jaroel] -.3.xml
https://pypi.python.org/pypi/Plone/4.0.3
CC-MAIN-2017-13
refinedweb
4,120
59.9
USB components overview The Universal Serial Bus (USB) is the most widely used bus in today's computer. USB has been designed to standardize connections between the computer and peripherals. For example, keyboards, mice, USB audio devices, printers, scanners, disk drives and cameras can use the same bus to exchange data with a computer. This document refers to the Mbed OS classes providing USB peripheral functionality as USB components. These USB components inherit from USBDevice and provide specific USB peripherial functionality. Below is information common to all of the Mbed OS USB components and how to use them. Component construction Constructing a USB component with the default parameters perform initialization for you. Once the constructor is finished then the device is ready to be used. This process: - Selects the built-in USBPhy for your hardware. - Starts the USB connection sequence. - Blocks until everything is ready. An example of USBKeyboard's default constructor: #include "mbed.h" #include "USBKeyboard.h" // Default constructor to connect and block until ready USBKeyboard key; int main(void) { while (1) { key.printf("Hello World\r\n"); wait(1); } } The first optional parameter to the constructor of all USB components is a bool that specifies whether the USB component should connect and block until ready. By default, this value is true. When set to false, USB still selects the built-in USBPhy for your hardware, but it does not block or start the connection sequence. This is useful when you do not want to connect USB at boot. An example of using the connect parameter to connect after boot: #include "mbed.h" #include "USBKeyboard.h" USBKeyboard key(false); int main(void) { // Start the USB connect sequence key.connect(); // Block until ready key.wait_ready(); while (1) { key.printf("Hello World\r\n"); wait(1); } } The constructors mentioned so far use the default built-in USBPhy as the back end. To allow support for boards without a built-in USBPhy, all USB components provide a second constructor, which takes a USBPhy as one of its parameters. You can use this to pass an off-chip USBPhy into any of the USB clases. This constructor does not connect or block, so you must do this elsewhere. An example of using the secondary constructor to explicitly pass in a USBPhy: #include "mbed.h" #include "USBKeyboard.h" #include "usb_phy_api.h" USBPhy *phy = get_usb_phy(); USBKeyboard key(phy); int main(void) { // Start the USB connect sequence key.connect(); // Block until ready key.wait_ready(); while (1) { key.printf("Hello World\r\n"); wait(1); } } USB component state The connect() and disconnect() functions control the state of the physical USB line to the host. When a device is connected, it is visible to the host PC to which it is attached. Once connected, the host PC must finish setup. USB components provide at least one service. When a service is available for use, it is ready. For example, the USBSerial component enters the ready state after a serial port has been opened on the host PC. To determine whether a USB component's service is ready, you can use the ready() function. It returns true if the USB component is ready for use and false otherwise. Some components provide multiple services, such as USBAudio, which can send or receive data and has two separate ready functions - read_ready() and write_ready(). Furthermore, for each ready() function, there is also a corresponding wait_ready() function, which you can use to block until the USB component's service is available. USB component and power saving Some instantiated USB components prevent devices from going to deep sleep because their USBPhyHw implentation holds a deep sleep lock. You can temporarily disable USB using USBDevice::deinit() to permit deep sleep. However, you must make sure all the data transfers have concluded to avoid any data corruption. The USB host controls the enumeration process, so it chooses when and how to restore the device. Even if the device state is returned to what it was before the disconnect, the host PC software may not be where it left off - for example, you may need to reopen a serial port. You can use USBDevice::connect() to resume USB component operation when USB power is detected after it was previously suspended through USBDevice::deinit().
https://os.mbed.com/docs/mbed-os/v6.2/apis/usb-overview.html
CC-MAIN-2020-34
refinedweb
706
57.77
Narrow DPA Scope There are a number of cases when you may want to exclude certain issues from the DPA issue list. For example: This is not an issue All programs require memory. A method may sometimes allocate a lot of memory - not because of code design, but just because this is required by the current use case. If these are just a few methods, the best solution is to suppress these issues. If you get a lot of false positives, then probably it is better to increase the memory allocation threshold. This issue is not mine Large solutions include hundreds of projects with many people working on them simultaneously. DPA lets you exclude issues, so that you can leave only issues related to you and your current work. This issue is already fixed A rare case when you have already fixed the issue but have not run/debug the solution one more time. If you want such an issue to be hidden from the list, you can mark the issue as fixed. Short summary: Suppress issues To suppress an issue, you must mark the corresponding method with the SuppressMessage attribute. The main benefit of suppressing the issue is that the attribute is set in the source code, so, it can be shared through VCS. The easiest way to set the attribute is to use a context action. In the editor, find the method you want to suppress. Note that the SuppressMessageattribute makes DPA ignore memory allocations not only in the method itself but in all child calls as well. Put the caret at the line highlighted by DPA and press Alt+Enter. In the context action list, choose Suppress memory allocation issues and then choose what exactly you want to suppress in the current call subtree: only the selected issue, all issues of this type, or all issues. You can set the SuppressMessage attribute manually. For example: Here: "ReSharper.DPA"is the required attribute category. checkIdspecifies what issue type must be suppressed (description is optional): "DPA0001: Memory allocation issues": any memory allocation issues. "DPA0002: Excessive memory allocations in SOH": allocations to the small object heap. "DPA0003: Excessive memory allocations in LOH": allocations to the large objects heap. "DPA0004: Closure object allocation": allocations because of closures. MessageId: lets you to narrow the attribute's scope by allocation size and/or type. You should set the scope filter using a list of key-value pairs: "key1: value1; key2: value2; ..."The following keys are available: type: EXACT_FQN: suppress issues where the objects of the specified type are allocated. EXACT_FQNis the type full name, including namespace and all substitutions of generic types. size: VALUE "B"|"KB"|"MB"|"GB"|"TB": suppress issues if the total size of allocated objects is less than VALUE. For example: "type: System.Object; type: System.String; size: 500MB" This filter means that DPA must suppress all issues related to allocations of objects of the System.Objector System.Stringtypes, unless the total size of allocated objects is less than 500MB. Exclude issues Excluding may be required when you are not interested in a particular issue, for example, if it is not related to your work. As well as suppressed issues, excluded issues are hidden from the Dynamic Program Analysis window and from the editor. The main difference is that you exclude issues only for yourself: The 'excluded' issue state is not propagated to VCS. Exclude an issue Return an excluded issue back Mark issues as fixed Marking an issue as fixed is similar to excluding. The main difference is that excluding is permanent while 'marking as fixed' hides the issue until you run/debug your solution: If the issue was not in fact fixed, DPA will return it back to the issue list. Change issue thresholds DPA marks a method as an issue only if it allocates memory above the threshold value. Therefore, the easiest way to get rid of false positives is to increase the corresponding threshold. Note that there is no universal threshold: Depending on the current execution context, your application can allocate different amount of memory. For example, the size of the data your app works with can change from run to run. You can set a threshold for each issue type in the Thresholds tab of the Dynamic Program Analysis window. The default thresholds are: Closure object: 50MB Large Object Heap: 50MB Small Object Heap: 100MB Open the Dynamic Program Analysis window. Do one of the following: Select the issue which is above the current threshold, and in the context menu, choose Ignore | Set New Threshold for .... This will set the corresponding threshold right above the issue allocation value. Switch to the Thresholds tab and set a new threshold value for the desired issue type.
https://www.jetbrains.com/help/rider/Narrowing_DPA_Scope.html
CC-MAIN-2020-34
refinedweb
789
54.42
13 September 2012 08:42 [Source: ICIS news] ?xml:namespace> “The monetary Policy Committee of the Bank of Korea (BOK) decided today [Thursday] to leave the Base Rate unchanged at 3.00%,” the central bank said in a statement. The pace of the global economy is expected to be very modest going forward, with downside risks to growth forecast to be large owing mainly to the “spillover of the euro area fiscal crisis to the real economy”, it said. The economic recovery in the “Growth has continued to slow in emerging market countries as well, due mostly to the impact of the economic slumps in advanced countries,” it added. This follows the W8,500bn stimulus package announced in June this year to spur the economy in the latter half of 2012, they said. The slowdown in external demand because of the global economic slowdown and the effect of typhoon Bolaven led to a decrease in both exports and imports in August this year, according to the Ministry of Knowledge Economy (MKE) in an earlier statement. Overall exports slipped by 6.2% year on year to $43bn in August, while imports fell by 9.8% to $40.9bn, it said. Shipments to both the EU and the Meanwhile, inflation in South Korea is forecast to pick up going forward on the back of the recent damages brought upon by typhoons and the volatility of oil and grain prices but is expected to stay below the central bank’s 3% target for the time being, the BOK added. ($1 = W1
http://www.icis.com/Articles/2012/09/13/9595053/s-korea-central-bank-holds-interest-rates-unchanged-at-3.html
CC-MAIN-2015-22
refinedweb
258
67.28
go to bug id or search bugs for There is a dependency in certain modules (notably php_openssl) on apphelp.dll. This file seems to only be available on WindowsXP (and the file shipped with XP won't work on win2000). If I am correct (I'm not entirely sure), any use of this dll will render the extensions useless on any windows version prior to XP). Source: DLL Help on MSDN. (The file is only listed as part of Windows XP). Add a Patch Add a Pull Request there's no dll in the binary package which is directly dependent upon that dll. where did you get that info from? daniel --- Daniel, next time, use the web interface for replying to bug reports. --Jani It seems that I have narrowed down the problem. The culprit does seem to be IE6. I did the same installation on a Win2000 machine with IE5.5 instead on IE6, and the install came clean, including the dependencies. IE6 seems to put in a dependency on a file which belongs to XP; why it doesn't break other apps is a mystery, but that's M$. I'm definitely paying the price for not following my own advice about putting a new version of a microsoft product on my system before the 2nd SP. Report this to Microsoft. Not a PHP bug -> bogus. I found a number of EXEs and DLLs that Dependancy Walker show as requiring the missing APPHELP.DLL. As a bit of humor, open DEPENDS.EXE in Windows 2000 with IE 6; you will find some flagged DLLs that can't find APPHELP.DLL Thanks for having this site accessable; it helped track down the same problem in one of our products also. build a bogus apphelp.dll borland c++ source ---BEGIN APPHELP.C--- #include <windows.h> __declspec(dllexport) BOOL ApphelpCheckShellObject( REFCLSID ObjectCLSID, BOOL bShimIfNecessary, ULONGLONG* pullFlags ) { return FALSE; } ---END FILE--- then build it with bcc32 -WD apphelp.c copy it in a path directory it work on windows 2000 no problem so far with this fix. msdn has been quite usefull to know what this function basically do. The fix identified here disables Windows Explorer and other features under Win2K after the first reboot. I do appreciate the openess of the site, it has been very helpful.
https://bugs.php.net/bug.php?id=14464
CC-MAIN-2016-36
refinedweb
386
75
> I'm new and don't really know what I'm doing working with rotations and the camera. I found a script in a free asset that almost does what I want and I started modifying it. The code below is what I have right now. I'm trying to get the camera to zoom in and out from the player with the scroll wheel, rotate around the player and up and down by holding down the right mouse button and moving the mouse, and then trying to get the camera to stay locked in place relative to the player when you are not moving the camera IE you have the camera on your right side and turn while running and its still on your right side. This script works exactly like I want it to now except for one major glitch. If I turn the player at all and then go to move the camera again it will jump to a new position at the first click of the mouse. After that it works just how I want it too until I turn the player again. I'm hoping someone knows an easy way to fix this. Edit: the camera is a child of the player object and the script is attached to it. public class ThirdPersonCamera : MonoBehaviour { private const float Y_ANGLE_MIN = 0.0f; private const float Y_ANGLE_MAX = 80.0f; public Transform lookAt; //this is set in inspecter to the characters head. public Transform camTransform; public float distance = 5.0f; //how far away the camara is private float currentX = 0.0f; private float currentY = 45.0f; private float speed = 3f; //speed multiplier for moving camera. Quaternion rotation; private void Start() { camTransform = transform; rotation = Quaternion.Euler(currentY, currentX, 0); //get camera in the starting position. camTransform.position = lookAt.position + rotation * new Vector3(0, 0, -distance); } private void Update() { distance -= Input.mouseScrollDelta.y * 40 * Time.deltaTime; // mouse scroll to change cameras distance from player. distance = Mathf.Clamp(distance, 0.7f, 10f); //stop camera from going into player or way far away. if (Input.GetMouseButton(1)) //try to get the camera to only move while holding down right mouse button. { currentX += Input.GetAxis("Mouse X") * speed; currentY -= Input.GetAxis("Mouse Y") *speed; //- so camera goes the other way currentY = Mathf.Clamp(currentY, Y_ANGLE_MIN, Y_ANGLE_MAX); } } private void LateUpdate() { Vector3 dir = new Vector3(0, 0, -distance); if (Input.GetMouseButton(1) || Input.mouseScrollDelta.y != 0) //trying to keep the camera locked in place relative to the player when not moving the camera. { rotation = Quaternion.Euler(currentY, currentX, 0); camTransform.position = lookAt.position + rotation * dir; } camTransform.LookAt(lookAt.position); } } Answer by CybexGS · Mar 15 at 10:31 AM Put this in your Update() method; Update() camTransform.position = Vector3.MoveTowards(camTransform.position, camTransform.position + camTransform.forward * Input.mouseScrollDelta.y, 1); if (Input.GetMouseButton(1)) { camTransform.RotateAround(lookAt.position, Vector3.up, Input.GetAxis("Mouse X") * speed); camTransform.RotateAround(lookAt.position, camTransform.right, -Input.GetAxis("Mouse Y") * speed); } and you can get rid of the entire LateUpdate() . LateUpdate() Now, there is no clamping / limits to movement implemented in there yet, but it should otherwise behave the way you want it to. Thank you for this. The camera jumping no longer happens and it seems like it should work how I want after I put the clamps back in. You're very welcome. Let me know if you're having trouble with the clamping, the system now is entirely different than before. I have gotten the distance clamped and don't really care about the y clamp at the moment. There was one issue with the min distance clamp where the camera would sometimes jump to the other side of the player but this doesn't need to be fixed as my plan all along has been to move the camera into a first person view once you zoom in past the min distance. I already have it working where it moves the camera into first person after zooming in and goes back to third person when zooming out. Now I just need to figure out the mouse look part of the first person view. I shouldn't need help with that though because I have done it before in tutorials and can just go back to them if I can't figure it out. Thanks again for your help it would have been awhile before I could have gotten this done on my own. Answer by Somewittyname · Mar 14 at 09:05 PM Thanks for the reply. This example doesn't seem to work for me. The camera will no longer rotate when I hold down the mouse button and it will still jump to a new position when I hit mouse button after turning the character. I'm assuming the camTransform.position = lookAt.posistion + rotation * dir; is what is changing the camera's position. Unfortunately I don't understand the math here as it was part of the script before I started modifying it. What value is multiplying those 2 vectors together intended to give? Why does it only drastically change the position after the character has rotated and then seem to move smoothly? Why doesn't it do the same thing if I hold down the mouse button the entire time (it seems to not jump when moving around then)? Somehow it seems to be deciding a rotation for the camera vastly different then what it was on the first frame of the click and then it moves the camera to match that rotation and still be the same distance away and looking at the player. Oh well I guess I'll work on something else for now and figure it out later after I learn some of the math involved. I already bought a Udemy course on math for games and just haven't done it yet. Yes, you're right. Doesn't work at all. But there is a lot more to it, i think. What happens, or shall hapen if you release the RMB? Shall the camera snap back in its original position behind the player or shall the player change the walk direction? The camera stays in the same place relative to the player and moves with him and looks at him when the RMB is released which is exactly what I want it to do. If the player turns with RMB released the camera again moves with the player and stays looking at him at the same angle which is what I want. If you hold down the RMB and run in a straight line you can move the mouse around the player and it doesn't change the direction he is running in again as I want it to do. If you hold down RMB and turn while running then it changes the angle of the player facing the camera again as intended. The camera does not snap back to the starting position or to the same position each time it happens. I'm not sure what the logic is that is deciding where it goes. It always stays at the same distance from the player and looks at him though just from a different position. Playing around with it some more it does look like the camera wants to keep having the blue transform line face in about the same direction each time it happens. The camera is a child of the Player object, right? Answer by Cornelis-de-Jager · Mar 14 at 10:24 PM Hi, the solution below isn't tested, and doesn't contain rotation restrictions, but give it a try and tell me if it works for you. [SerializedField] Transform player; Transform cam; Vector3 offsetDir; float distance; float camDelay; float camRotSpeed; float camScrollSpeed; void Start () { cam = Camera.Main.transform; offsetDir = cam.position - player.position; } public FixedUpdate () { // Function to handle the adjusted camera HandleAdjustment(); // Function to handle the camera following the player HandleCameraMovement (); } void HandleAdjustment () { // Change Distance distance -= Input.mouseScrollDelta.y * camScrollSpeed * Time.deltaTime; distance = Mathf.Clamp(distance, 0.7f, 10f); // Dont do anything if the right mouse is not held down if (!Input.GetKey(KeyCode.MouseButton(1))) return; offsetDir += new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0) * camRotSpeed * Time.DeltaTime; } void HandleCameraMovement () { var targetLocation = (offsetDir).normalized * distance; cam.position = Vector3.Lerp (cam.position, targetLocation, camDelay); cam.LookAt(player.position + new Vector3 (0,player.localScal.y / 2,0)); } Isn't working for me. Thanks for trying. camera control-zoom in/out and rotate left and right for a terain 2 Answers How can you move main camera along x,z axis without moving along y axis with DotA/LoL mouse control 0 Answers Raycast only works in cartain areas of scene 0 Answers Using Camera Y Rotation to Determine Player Movement Direction 0 Answers How to implement lock on with a camera that is not a child of the player object? 1 Answer
https://answers.unity.com/questions/1612316/trying-to-get-a-third-person-camera-to-be-movable.html
CC-MAIN-2019-22
refinedweb
1,479
64.1
Inkscape/Interface ne of Inkscape's main priorities is ease of use. This is visible on the Main Window as every bar's button (icon), numeric value and unit of measure boxes will produce tooltip (help) messages. The Menu bar is title, not button, based so when using these titled edits Inkscape still provides updated assistance. For a quick example, click the Menu's bar ‣File option, then mouseover 🖰 one of the ‣File options and there will be two feedback features. (1) The mouseover of one of the drop down menu items will highlight (background color) the item. (2) The Statusbar (bottom center) will provide an updated Notificaton message describing the highlighted Menu bar item.[1] The Inkscape default window is laid out with four bars at the top, two on the left, two on the right and three at the bottom. You can create and edit graphics using various displays, such as bars, dialogs, numeric value and unit of measure boxes. You can also adapt the bars and dialog displays to the way you draw, by customizing the Main Window view with style settings. The window layout of an application is also referred to as the Graphical User Interface (GUI).[2] - The Menu bar across the top contains file and graphic based editing, using a number of drop-down menus. The menu titles are displayed, and if assigned the titles keyboard shortcut key(s) are also displayed. - The Commands bar contains common commands associated with file and graphic editing. Related commands are grouped together and separated by vertical lines (|). - The Tool Controls bar displays editing option buttons (icons), numeric-value (if applicable) and unit of measure boxes for the currently enabled Toolbox bar tool. - The Rulers bar shows the x and y axis positioning of the cursor on the canvas and is one source for placing Guidelines over the canvas. - The Scrollbars are placed to the right and bottom, adjacent to the canvas. - The Snap Controls bar is displayed on the right side of the user interface and sets the snapping methods (modes). - The Pallete bar below the bottom Scrollbar and above the Statusbar displays customizable color palletes. - The Statusbar at the very bottom of the interface, displays common editors, dynamic tool-tip messages of the current on Canvas node/handle mouseover 🖰, edits and Menu bar interaction being performed. - The Canvas area is the play area for your creations, the canvas has no borders. - The Page can be seen as the print area and is restricted by its 'page border'. One can still export based on page, selection, drawing and custom. The sub Menu option ‣View ‣‣Show/Hide allows on and off display of various bars, the Menu bar is the only bar that cannot be hidden. If you work with two or more files, you can position each window side by side on the screen or across multiple monitors. You can also switch between file windows using; - ‣View ‣‣Next Window or ⇧ Shift+Tab ↹ - ‣View ‣‣Previous Window or Ctrl+⇧ Shift+Tab ↹ Contents - 1 Interface basics - 2 Interface preferences - 3 View modes - 4 Menu bar - 5 Commands bar - 6 Toolbox and Tool Controls bars - 7 Rulers bar - 8 Scrollbars - 9 Scrolling preferences - 10 Snap controls bar - 11 Snapping preferences - 12 Palette bar - 13 Statusbar - 14 Canvas - 15 Menu types - 16 Dialogs - 17 Panning - 18 References Interface basics[edit] The Inkscape interface is based on the GNOME Human Interface Guidelines (HIG) standard. The HIG uses visual indicators, like background and cursor (pointer) changes. It also provides feedback with pop-ups, tooltip and notification messages for any interface buttons, numeric value and units of measure boxes, on canvas editing icons, bounding boxes, guides, etc. and Menu bar 'titled' commands.[3] Here are some examples of Inkscapes HIG features: - Mouseover 🖰 the cursor on top of any interface button, numeric-value or unit of measure box and the interface will display a pop-up (feedback) description of the button and boxes. And if the button or box is available for execution, the interface will highlight the button/box with a light blue visual indicator (background). - When a button or numerical-value box foreground is grayed out, this indicates that the button/box cannot be used under the current canvas selection/status, but will still display a pop-up message. - Edit/Tool buttons that are currently enabled will have blue square/rectangle backgrounds. - Mouseover 🖰 on top of any on canvas editing icons (i.e., nodes, handles, segments, etc.) and the editing icon will change colors and generate a tooltip message in the Statusbar's Notification area. - When Snap Controls are enabled, during the 'snap to' action an on-canvas pop-up messages will briefly display feedback on how the snap will be placed (example, Bounding Box Corner to Bounding Box Corner) - Within the Statusbar there is a Notification Area that will display dynamic messages based on; - Mouseover 🖰 of any on canvas edit icons/segments - Menu bar highlighting of command features - Menu bar transactions Interface preferences[edit] To open the Interface preferences menu, use the Menu bar ‣Edit, ‣‣Preferences... (Ctrl+⇧ Shift+P) and open the <Interface> sub-menu. There are many customizable settings available under the Interface preferences and its three sub-menus. Just like the mouseover 🖰 feature availability for on canvas edits and interface bars, you can also mouseover 🖰 preferences' window items; drop down menus, check box descriptions and value boxes. The three sub-menus under Interface are; Windows, Grids and Keyboard Shortcuts. Under the Windows sub-menu there is a setting for: Dialog behavior (requires restart) - Dockable - Floating The Dockable setting will place a dialog's (example, Fill and Stroke Dialog) window against (docked) the Snap Controls bar on the right side of the Interface. The Floating setting will place the dialog's window onto the top right area of the Canvas. View modes[edit] You can change the interface display of the Inkscape window using three view modes. 1. Normal view mode displays artwork in the default window. In this mode, access to all of the editing tools and menu interactions are available. 2. Fullscreen view mode ‣View ‣‣Fullscreen (Alt+V, F) or shortcut F11 displays artwork in a fullscreen window, only eliminating the document title bar. In this mode, shortcut key edits still are available. To return to Normal view mode use ‣View ‣‣Fullscreen (Alt+V, F) or shortcut F11. 3. Fullscreen view mode with Dialog (Dock) Bar ⇧ Shift+F11 displays artwork in a fullscreen window with the dialog window or dock bar displayed. In this mode, shortcut key edits are also available, to return to Normal view mode press ⇧ Shift+F11. Menu bar[edit] The very top bar of the Inkscape interface is the Menu bar, the Menu contains the basic File, Edit and Help functions like many other programs. A fairly new feature worth noting is the ‣File ‣‣Import Clip Art... window which allows for the searching and importing of files from the Open Clip Art library, for this to work you need to be connected to the internet. The remainder of the Menu bar's commands are related to working with graphic design. Most commands are available directly from the keyboard, by either using access keys (underlined letter) or keyboard shortcuts. These two keyboard methods are available features within Inkscape. Using the ‣File drop down menu as an example, access keys for commands under the ‣File menu are available by first using Alt+F (drop down menu is displayed), then a given access key. Example, to access the ‣File ‣‣Document Properties command use the following keyboard entries of Alt+F, D, you can also use the assigned keyboard shortcut of ⇧ Shift+Ctrl+D. Frequently used menu items are assigned keyboard shortcuts, this amounts to over 60% (not including Filters, Extensions and Help) of Inkscape's Menu bar commands having keyboard shortcuts.[4] Additionally, in the Menu bar - drop down graphic above, the Document Properties... Shift+Ctrl+D item is highlighted. When a Menu bar item has a mouseover applied the Statusbar's Notification display will update with a live message. Here is the notification message for the mouseover of Document Properties: Statusbar, notification message: Edit properties of this document (to be saved with the document) Commands bar[edit] The Commands bar has buttons of frequently used edits such as file options, zoom levels, undo, copy, group, etc. Related edits are grouped along the bar and are separated by a vertical line |. A great example of this is the grouping of the highly used Zoom levels. Toolbox and Tool Controls bars[edit] The third bar down is the Tool Controls bar, which changes depending upon the currently enabled tool in the Toolbox bar. The Toolbox bar is located on the left side of the user interface. In the example graphic the Tool Controls bar edits are complementary to the Toolbox bar's Selector Tool. The Tool Controls bar edit buttons (icons) and numeric-value boxes are editors under the Selector Tool properties and are grouped into five sections, each separated with vertical lines |. Here is a summary of the groupings starting with the left grouping first: - ① Select all objects or all nodes(Ctrl+A); ② Select all objects in all visible and unlocked layers (Ctrl+Alt+A); ③ Deselect any selected objects or nodes(Esc) | - ④ Rotate selected objects 90° counter-clockwise (Ctrl+[); ⑤ Rotate selected objects 90° clockwise (Ctrl+]); ⑥ Flip selected objects horizontally (H); ⑦ Flip selected objects vertically (V) | - ⑧ Lower selection to bottom (End); ⑨ Lower selection one step (Page Down); ⑩ Raise selection one step (Page Up); ⑪ Raise selection to top (Home) | - ⑫ Horizontal coordinate of selection; ⑬ Vertical coordinate of selection; - ⑭Width of selection; Lock button - See graphic above for mouseover pop up msg; ⑮ Height of selection; ⑯ Drop down menu, sets the selected object(s) units of measure - For value box shortcuts, see the "Control bar shortcuts" section below | - ⑰ When scaling objects, scale the stroke width to the same proportion; ⑱ When scaling rectangles, scale the reach of rounded corner; ⑲ Move gradients (in fill or stroke) along with objects; ⑳ Move patterns (in fill or stroke) along with objects The amount of interface bar button pop-up messages support in Inkscape is very impressive, as it is hard to find a button, numeric-value and unit of measure boxes that do not generate pop-up messages on mouseovers 🖰. The Tool Controls bar example graphic shows a pop-up message, that is generated (feedback) when a mouseover 🖰 is above the Selector's Tool Controls bar open lock button. Controls bar value boxes[edit] To access the Tool Controls bar numeric-value boxes and units of measure box: - Click inside the numeric-value boxes - Click the drop down button in the unit of measure box There are also Controls bar shortcuts that not only make the navigation of the varying boxes quicker, but will likely lead to a great habit of using more precise settings when creating detail oriented files. While svg editors compliment bitmap editors, svg editors can be seen as another domain for artwork. SVG relies heavily on mathematics and a part of Inkscape's ease of use gateway to its internal mathematics are via these boxes. While the shortcuts below may seem cumbersome at first, over time they will ultimately lead to enhanced graphic creations through ease of use and a 'best practice' of zeroing in on Inkscape's rich mathematics. Tool controls bar shortcuts[edit] Access - The Tool Controls bar provides different buttons and numeric-value boxes for each tool. Navigate - Use these shortcut keys to move between boxes in the Tool Controls bar. Change values - Values can be entered by typing, right-clicking for a preset pop-up menu along with these shortcut key options: Tool controls bar visual feedback[edit] The currently enabled Toolbox tool will have a blue colored squared backdrop. The Tool Controls bar also places a blue colored squared backdrop to any enabled edits. In the Tool Controls graphic there is an example of four edit features grouped together. The first button is not enabled so there is no blue background on the button, but it is available since it is not grayed out. The next three edits are enabled: and have blue color backgrounds. For new (rookie) graphic designers over looking these settings can lead to re-editing of objects. Selector tool rate of use[edit] The Selector Tool is the most used tool in Inkscape. So to improve the ease of use for this tool it has three shortcuts, and is one of the two tools that has a 'toggle' feature. One of the three Selector Tool shortcuts is the Spacebar, which toggles the activation of the Selector Tool. When using any other tool, press the Spacebar to switch to the Selector Tool, then perform the Selector Tool-based edit(s). Once the Selector Tool edit(s) are completed press the Spacebar again to return (toggle) to the previously enabled tool. Toolbox bar descriptions[edit] The tools can be enabled from the Toolbox bar on the left side of the interface or by using the shortcut key assigned to the specific tool. To find out what edit/feature each tool provides, simply mouseover 🖰 a Toolbox bar button (icon) and a pop-up message (feedback) will provide the tools title and its assigned shortcut key in parenthesis. Here is a table with shortcut key(s), tool's name and descriptions for each of the Toolbox tools (v0.91): Rulers bar [edit] Keyboard shortcut: Ctrl+R The fourth bar down, from the top, is the Rulers bar, this interface bar is two-sided as it also displays along the left side of the Canvas. Both of the rulers directly border the Canvas area. The top bar (left to right) is "horizontal" and is referred to as the X axis. The left bar (down to up) is "vertical" and is referred to as the Y axis within Inkscape. In the example Rulers bar graphic, the X axis ruler's down arrow icon (⏷) and Y axis ruler's right arrow icon (⏵) follow the on-canvas cursor's positioning. If you prefer not to use the Guidelines or Canvas Grids, zooming in while editing nodes, handles, etc. will increase the accuracy of on-canvas editing. The Node's Tool Controls bar also has precise x/y numeric-value boxes for an objects bottom-left bounding boxes corner for x/y placement on the canvas. The rulers can represent distances by different units of measure and can be set using the following Menu bar command, ‣File ‣‣ Document Properties ‣‣‣Page Tab <Default units>, ⇧ Shift+Ctrl+D. Any changes will be saved with the document, as this is not an entire (application) preference. Inkscape provides the following configurable default units of measure: The Document Properties default units (of measure setting) is px (pixels). To verify any change of the default units, simply mouseover 🖰 the Rulers bar and a pop-up will display the default units of measure setting. Displaying the Rulers bar to the user interface can also be viewed or hidden using the following options, Ctrl+R or via the Menu bar ‣View ‣‣Show/Hide ‣‣‣Ruler bars (Alt+V,O, R. Rulers bar - Guidelines[edit] Keyboard Shortcut: ⇧ Shift+| The Rulers bar is one method of placing guidelines onto the canvas area. The guidelines are in place to assist in editing and are not part of rendering or exporting of any files. To extract (pull out) a guideline from one of the Rulers bar, switch the Toolbox tool to either the Selector Tool (spacebar) or the Node Tool (N). For a 0° angle guideline place the mouse cursor over the top Ruler Bar (X axis ⏷), then Drag (Click+Hold) the mouse cursor down toward the canvas. A red line will come out of the Rulers bar and will be positioned (x/y) over the canvas where the drag is released. Once released the Guideline will change to the color blue (default). For a 90° angle guideline repeat this drag over the left Ruler Bar (Y axis ⏵). The graphic (Inkscape v0.91 Rulers bar guideline drags) also shows how to drag pre-configured guidelines from the top left corner for a 45° angle and for a -45° angle from the top right or the bottom left of the Rulers bar. The modifier keys Ctrl and ⇧ Shift enhance the edits of the guidelines. Here is the Statusbar's Notification display (bottom-center) tooltip message when hovering the Selector or Node Tool cursor over an existing guideline: Guideline: horizontal, at 50px; Shift+Drag to rotate, Ctrl+Drag to move origin, Del to delete To angle a guideline at 15° snap increments drag the guideline using the following keys, Ctrl+⇧ Shift+Drag. The guidelines can be viewed or hidden by, a Single-Click over the Rulers bar, shortcut ⇧ Shift+| and ‣View ‣‣Guides (Alt+V, U). Displaying the Guidleines to the user interface can be viewed or hidden using the following options, ⇧ Shift+| or via the Menu bar ‣View ‣‣Guides (Alt+V, U). Scrollbars[edit] Keyboard shortcut: Ctrl+B Thumb dragging[edit] Move the cursor over one of the two thumbs and then Drag (press and hold) the thumb, to scroll the canvas. If using a laptop pad, move the cursor over a thumb and double-click the thumb, then drag it. Clicking the trough[edit] The trough area above or below the thumbs can be clicked in order to jump to that point on the canvas. After clicking the trough, scrolling automatically begins and then stops once the thumb has reached the position of the mouse cursor. To jump the thumb to a trough position use the shortcut Click the Middle Mouse Button (Click+MMB). [edit] Left-clicking on the arrows scrolls a small amount of the canvas at a time. Press and hold an arrow button and the canvas continuously scrolls faster until released. Right-clicking the arrows will automatically move the canvas' to the far left, far right, very top or very bottom of the canvas. Scrolling preferences[edit] Mouse wheel[edit] A mouse wheel, the middle mouse button (MMB), on a three button mouse may also be used to scroll the canvas. Moving the wheel in a desired direction moves the content in the same direction. Most mouses have a MMB that only scroll up and down, to scroll horizontally (left or right) use ⇧ Shift+MMB. To change the distance one notch of the mouse wheel scrolls (moves) edit the "Mouse wheel scrolls by" spin box in the Edit Preferences... (Alt+E, R) or shortcut ⇧ Shift+Ctrl+P Scrolling menu, shown above. Arrow keys[edit] You can scroll the canvas in any direction using Ctrl+Arrow keys. Or drag (click + hold) the middle mouse button (Drag+MMB) scrolling the mouse in any direction. The Inkscape ‣Preferences ‣‣Behavior ‣‣‣Scrolling provides user settings for the Ctrl+arrows feature: - Scroll by: will set the distance for each notch (step) of the MMB - Acceleration: will gradually (gently) speed up scrolling, set the spin box to '0' for no acceleration Mouse wheel zooms by default[edit] When the Mouse well zooms by default check box is checked (on), the mouse wheel zooms without Ctrl and scrolls the canvas with Ctrl. When this setting is unchecked (off), the mouse wheel zooms with Ctrl and scrolls without Ctrl. The graphic above shows the tooltip message when you mouseover 🖰 the check box or the check box description. To view/hide the scrollbars using the Menu bar, ‣View ‣‣Show/Hide <Scrollbars> (Alt+V, B) or shortcut keys Ctrl+B). Snap controls bar [edit] Keyboard Shortcut: % The bar to the far right, of the interface, is the Snap Controls bar that enables setting of object snapping modes. In general, snapping is a method for accurate and symmetrical (balanced) placement of objects onto the canvas. It features edits that easily align items in many different ways. The topmost icon in the bar enables snapping in general for the current file, the keyboard shortcut % is assigned to the Snap bar. Once snapping is enabled, there are six modes available, the first three modes have secondary snap edits available, while the last three snap edits are stand alone modes. Snap bar settings[edit] The options for Snap bounding boxes include: The second mode of snapping, is Snap nodes, paths and path segments, here are the options: The third mode of snapping is Snap to other points (centers, guideline origins, gradient handles, rotation center (+), etc.), options include: The last three snap modes are independent of each other and are not grouped like the previous modes. These snap modes require that the general snapping mode is enabled, shortcut key %. The independent modes are: Bounding boxes[edit] One of the six modes of snapping, is Snap bounding boxes. A bounding box is a dashed line box, outlining an object's height and width. There are two outlining settings for the bounding box feature. (1) Visual bounding box; encloses strokes, markers, filter margins, etc. and (2) Geometric bounding box; outlines only the bare path. Here are some example graphics of the two bounding box types with plain and filtered objects, using the Selector tool: To choose between the two bounding box features open ‣Edit ‣‣Preferences (Alt+E, R) or shortcut ⇧ Shift+Ctrl+P select Tools, then click the radio button of your choice; Bounding box to use: - ◉ Visual bounding box (default) - ◎ Geometric bounding box Snapping preferences[edit] Keyboard Shortcut: ⇧ Shift+Ctrl+P A 'Snapping' tab is available in the ‣Edit ‣‣Preferences (Alt+E, R or ⇧ Shift+Ctrl+P) ‣‣‣Behavior <Snapping> options. Features found on this tab are: - Enable snap indicator (checkbox) - After snapping has occurred, an on canvas pop up message is displayed at the specific snap position, providing vector and snap mode information (feedback) of the edit. - Delay in ms (slider) - Postpone snapping as long as the mouse is moving, then wait in milliseconds (ms) before applying the snap. The delay is set on this slider, with values from 0 to 1000 ms available. When set to zero or a very small number snapping will be immediate. - Only snap the node closest to the pointer (checkbox) - Try to snap to the node that is closest to the mouse pointer (cursor). Example, If you want to use the bottom left node (corner) of an object as a snap point, start the drag (click + hold, left mouse button) close to the bottom left corner of the object. - Weight factor (slider) - When multiple snap targets are found, Inkscape can either prefer the closest transformation (when set to 0). Or prefer the node that was initially the closest to the pointer (when the slider is set to 1). - Snap the mouse pointer when dragging a constrained knot (checkbox) - When dragging a knot along a constraint line, then snap the position of the mouse pointer instead of snapping the projection of the knot onto the constrained line. Palette bar[edit] Keyboard Shortcut: ⇧ Shift+Alt+P At the bottom of the user interface below the Scrollbar is the Palette bar. This bar provides fill and stroke style (colors, gradients, patterns, etc.) options. Fill is the style inside of an object, stroke is the outer edge (border) of an object. Here is how some of the palette's color edits are placed onto objects: - Drag (press and hold the left mouse button) a color box from the palette onto an object and release the drag, this will change the target object's fill. The great benefit of this feature is the object does not have to be selected before the drag color box edit. - ⇧ Shift+Drag a color box from the pallete onto an object and release the drag, this will change the object's stroke color. Again, the target object does not have to be selected. - Select an object first, then Right-Click a color box in the palette. A pop-up menu provides options to 'Set fill' or 'Set stroke'. - Select an object then Left-Click a color box to set the object's fill. - Select an object then ⇧ Shift+Left-Click a color box to set the object's stroke. The top half of the palette bar displays color boxes. To the right of the last displayed color box is a small left arrow. Click the arrow ⏴ for a menu with the following options: - Size - from tiny to huge color boxes (5 settings). - Width - from narrower to wider color boxes (5 settings) - Border - none, solid and wide (wide setting is shown in the palette bar graphic) - Wrap - will add a second row of color boxes to the palette - Color theme - there are 21 (v0.91) themes to chose from. Just below the color boxes is the palette's scrollbar, there are many colors to choose from and most of the color themes require the use of this scrollbar. The scrollbar's default placement is to the left of the palette bar. Statusbar[edit] The Statusbar delivers routine edit settings and essential display only information. - Settings with editing capabilities - Style settings: Fill and Stroke style bars, Stroke width setting - O: Opacity numeric value spin box - Layer: Visibility, Lock/Unlock and Selection drop down menu - Z: Zoom percentage value spin box - Window size: Change window size - Displays only - Notification Display: On canvas editing tooltip and Menubar interaction messages - X: Y:: Horizontal (X) and vertical (Y) values of the cursor's on canvas position Style settings [edit] First, select an object and the style setting (bottom left of the user interface) will update to reflect the style of the object. With the selection still in place, Right-Click the Fill style bar and a pop-up menu will provide the following options: - Edit fill... (opens the Fill and Stroke Dialog, to the Fill tab) - Last set color (a) - Last selected color(b) - Invert; changes fill to the opposite color - White and Black; set fill to white or black - Copy/Paste color - Swap fill and stroke - Make fill opaque (full coloring, no alpha or opacity) - Unset fill - Remove fill (a) Lest set - will replace the color to the object's last 'set' color, no matter what sequence of selections and edits that have occurred. This edit is attached to the object's properties and is not attached to a que (chain) of selections/edits. (b) Last selected - is a mirror of the common chain based ‣Edit ‣‣Undo, shortcut key Ctrl+Z edit. The Stroke style bar, Right-Click is a mirror of the Fill style bar pop-up menu (above), but it applies to the selected object's stroke, not the fill. When a stroke style is displayed of a selected object, the stroke style bar is narrowed and the stroke's width numeric value is displayed (example graphic the stroke is set to 2). Right-Click the numeric value and a pop-up menu provides editing of the stroke's unit of measure (example; px, mm, inch, etc.), preset stroke width values from 0.1 to 32 and a remove (stroke) edit. Opacity spin box [edit] First lets define Opacity with regards to graphic design. The opacity value applies the transparency (see through) percentage of an object or a group of objects. The percentage is a unit of measure to which the background behind (below) the object is overlaid. The opacity percentage-value, O: box displays the opacity value for the selected object's combined fill and stroke. Right-Click the percentage-value O: box to select preset values from 0% (transparent/no color) to 100% (opaque/full color). Double-Click the box to manually enter an opacity setting of any number between 0 and 100. Please note that in Inkscape, Opacity refers to the transparency of both an object's fill and stroke. While the term Alpha refers to Color models (RGBA, HSLA, CMYKA, etc.) and allows for individual transparency editing of either an object's fill and stroke. Layer settings [edit] The Statusbar's layer settings is a minimized version of the full featured Layers Dialog and allows for quick layer selection/settings. The full Layer Dialog will be covered in the Dialogs chapter. Briefly, layers allow for the creation of and grouping objects within a given layer, not to be confused with the object group/ungroup features. If you are new to graphics, most graphic nerds use layers from a bottom to top method for their artwork, this is a side step as most people see things from a top to bottom view. An example of using layers can be drawn from the creation of a birthday card, here is a quick outline of the potential layers: - Text (layer 6 - Top), Happy Birthday _ _ _ _ _! - Photograph (layer 5), bitmap image of birthday person - Candles (layer 4) - Balloons (layer 3) - Gradient (layer 2), contains a radial gradient or a filter/effect over the background layer - 2nd Background/Backrop, contains a different background color for quick comparison - Background/Backdrop (layer 1 - Bottom), contains a background color for the birthday card The Layer settings let you work on one layer and its objects potential filters/effects, with no worry of mistakenly editing other objects. For a first time user the layer features may not seem essential. But as a given creation becomes more complex, the layers make graphic editing so much easier. Here are the definitions of the Statusbars' layer settings. The first button is the layer view / hide button. Followed, to the right, by the lock / unlock button of the current layer. When a layer is locked the objects within this layer are still displayed but cannot be selected nor edited. The layer's name and its drop down menu allows for a quick way to change layers. The Statusbar's layer settings are a quick and essential way of moving between layers. Tool-tips and Notifications display[edit] The Tool-tips and Notifications display is very helpful for beginners, as it generates Tool-tip Messages by following the sequence of possible on canvas edits one is performing on an object. It also generates Notification Messages when interacting with the Menu bar functions. If you are new to graphics, the tool-tip messages are prominent within graphic programs when compared to other types of programs. Please note Inkscape has thousands of edits, and this display is a key element if you want to grow your graphic design skills and have more fun. Tooltip messages[edit] Here is an example of the on-canvas tooltip messaging feature. First select the Square and Rectangle tool, while you are actively dragging (editing) the shape onto the canvas, the Statusbar's messaging will change and provide 'live' object and modifier key (Ctrl, ⇧ Shift, Alt) tooltip message, this shows Object, Ctrl and Shift tips: Statusbar, tooltip message: Rectangle: 11.00px x 766px; with Ctrl to make square or integer-ratio rectangle; with Shift to draw around the starting point Now with the rectangle on the canvas, mouseover 🖰 one of the rectangles square handles, the handle will change color (visual indicator) and a new two item (width and height and Ctrl) tooltip message (feedback) will appear: Statusbar, tooltip message: Adjust the width and height of the rectangle; with Ctrl to lock ratio or stretch in one dimension only Another example, again with the rectangle already rendered (displayed) on the canvas, mouseover 🖰 a handle then press and hold one or two of the modifier keys, like the Ctrl key or both the Ctrl+⇧ Shift. While holding down the modifier key(s) the tooltip message updates again and provides assistance for the modifier key(s) you are holding, here is the tooltip for two modifier Ctrl+⇧ Shift keys: Statusbar, tooltip message: Ctrl: make a square or integer-ratio rectangle; lock a rounded corner circular; Shift: draw around the starting point To summarize the rectangle tooltips over the three separate messages we received seven tips, to help make Inkscape easier to use. Here is a breakdown of the seven tips provided: When you switch from a newly created rectangle to either the Selector spacebar or Node tool N, the tooltip messaging will update to the newly enabled tool. Tooltips are extensive and very helpful, here are the on-canvas tooltips based on frequently used tools: - Shape or Path tools active on-canvas edits, along with handle, node, node handles and path segment mouseovers 🖰. - Selector tool active edits of scale, stretch, skew, rotation and center of rotation along with mouseovers 🖰 also generate tooltips. - The Node tool also generates extensive tooltips based on active edits and mouseovers 🖰 of cusp, smooth and auto-smooth nodes, node handles and segments. Regardless of the active tool, nearly every on-canvas edit icon will generate a new tooltip message. Notification messages[edit] The Statusbar Notifications Messages are generated based on any type of Menu bar interactions, except for the ‣Extensions menu (v0.91). As an example, click ‣File then move the cursor down and highlight the ‣‣Save option. The Statusbar will update and display a new notification message of "Save Document'. Now click on the ‣‣Save option and a new notification message of "Saving file" will be displayed. Once the file save is complete the Statusbar will then display an updated notification message with the file's directory information. While most applications have this similar feature, Inkscape's notifications implementation stands as one of its best features. If you are new to graphics, notification messages are very helpful when interacting with the Menu's bar. More than 70% of the Menu bar's commands are based on graphics. These messages provide great help with the understanding of what a specific graphic based command will do and will also update the message if a command failed to execute. In this example three messages are shown with the last two b) and c) are user errors and shows how the Statusbars display will update with assistance based notification messages on how to execute the command correctly. 1) Command: ‣Object ‣‣Clip <Set> Notes[edit] Cursor display [edit] In vector graphics, sometimes the positioning of objects can be cumbersome. But dependent upon what the final workup will be used for positioning can be very important. Laser printers, material cutters will print/cut with precision and therefore any mis-alignment of objects may easily be seen. The X: (horizontal) and Y: (vertical) display shows exactly where the cursor is on the canvas. A higher zoom level increases the accuracy of the cursor's position. Grids, Guides, Snapping and Zoom levels are additional methods for increasing accuracy of object, handle, node, text, etc. vector based placements. Zoom box [edit] Keyboard shortcut: Alt+Z The Zoom box increases accuracy of any on canvas edits. Right-Click the percentage-value box for a pop-up menu with preset zoom levels. The pop-up menu also has options for setting zoom levels to; page, drawing and selection. You can also click inside the value box and set the zoom percentage to your liking. Window size[edit] At the bottom right corner of the Statusbar is the freehand window size handle. Using this handle is free form, you can set the height and width of the Inkscape window to your monitors liking. To resize the window, Drag the window size handle to the way you want the window to be displayed, then release the mouse. Like other applications the top right corner of the Inkscape interface has window minimize _ and maximize □ buttons. In the Menu bar there is a full screen option using ‣View ‣‣Fullscreen (Alt+V, F) or the shortcut key F11, to toggle back to the previous window display repeat the previous fullscreen menu command or press the shortcut key again. Canvas[edit] For all objects, the canvas describes "the space where SVG objects are rendered.[5] It is the area for drawing objects and may extend beyond the zoom (viewable) area. Scrollbars, Keyboard shortcuts and Zoom levels can be used to move around the canvas. Grids[edit] Guides[edit] Menu types[edit] [edit] [edit] [edit] Dialogs[edit] A dialog is a window that allows an exchange of information and settings between the user and Inkscape features. A dialog obtains additional information from the user that is needed to carry out a particular setting or edit. A dialog appears in a its own panel window. Inkscape's dialog windows can be identified by a Menu bar command/edit that is followed by three dots, here is an example of a Menu bar dialog feature: Dock and Float[edit] Any open dialogs are raised above (float) the canvas and can also be viewed under a dockable (right attachment) setting. When a dialog is docked it will attach itself to the right side of the interface next to the Snap Controls bar. Both of the dialogs, float and dock, have left pointing arrow on the right side of the title bar. Mouseover of the left arrow will display the tooltip message "Iconify this dock". Left-clicking this button will minimize the dialog to the right side of the interface. Panning[edit] Panning is another way of moving around the canvas without using the scrollbar's features. Panning is not restricted to left-right and up-down movement like scrolling. Panning allows moving in any direction/angle of the canvas (also known as main view). - Pan the canvas in any direction using Ctrl plus the Arrow keys Ctrl+Arrow-keys. - For a two button mouse use Shift or Ctrl plus the right mouse button (RMB) and drag (click and hold) ⇧ Shift+RMB+Drag or Ctrl+RMB+Drag. - With a three button mouse by dragging (click and hold) the middle mouse button (MMB) MMB+Drag, then moving the mouse at any angle. - Rolling the middle mouse button MMB+Roll, rolling up and down pans the canvas up and down. To pan left and right, press and hold the Shift key while rolling the MMB (⇧ Shift+MMB+Roll) up pans to the left, down pans to the right. Changing between multiple Inkscape windows, for the next window Ctrl+Tab ↹, the previous window, use Ctrl+⇧ Shift+Tab ↹ . To view/hide the scrollbars using the Menu bar, ‣View ‣‣Show/Hide <Scrollbars> or shortcut keys Ctrl+B. References[edit] - ↑ GNOME HIG, Feedback types - ↑ GUI definition at techtarget.com - ↑ GNOME HIG Book, Menu bar - ↑ GNOME HIG Book, User Input - ↑ W3C, SVG coordinates - ↑ Inkscape 0.91, Release notes
https://en.wikibooks.org/wiki/Inkscape/Interface
CC-MAIN-2018-09
refinedweb
6,389
57.4
Hi. I've been playing around with Allegro 5 on my Raspberry Pi for a little while now (enjoying it a lot, by the way). I recently purchased a small LCD and followed this tutorial to get the drivers working for it. Now I'd like to be able to display Allegro happenings to the TFT, but it doesn't work by default. It plays on my TV through composite cables, but not on the LCD itself. So, I was wondering if there was anyway to make it work with the LCD's framebuffer, or if it could detect and display on the LCD in any way possible. Is there a way to specify the framebuffer? Do you know? EditI know that both pygame and SDL have things to allow for the setting of environment settings to use a framebuffer. For example, in pygame I'd use: os.environ["SDL_FBDEV"] = “/dev/fb1″, and in SDL I'd use: SDL_putenv(“SDL_FBDEV=/dev/fb1″);. Does Allegro have any such feature? I appreciate feedback. Allegro 5 on RPi can't use the framebuffer devices. It uses some broadcom thing to get OpenGL. The only way you could do it (if it is limited to fbdev) is fish out the old GP2X Wiz code from Allegro git history. That had a framebuffer device driver that should work with some tweaks. I appreciate your reply, Trent. So this "GP2X Wiz code" was under the Allegro 5 development at one point, or was it Allegro 4? Also, where would I find the git repository? Allegro 5. There were some optimized blitting routines for it for 16 bit color... not sure they're faster than what we have now or not. Interesting. Why was it removed/not included in proceeding versions of Allegro 5? Are there any plans to implement framebuffers to Allegro 5 at any point in the foreseeable future? By framebuffer, you mean CPU addressable display memory? You can emulate it with glDrawPixels(), or I think you can still do it with DirectDraw for windows, just blitting a memory buffer to/from the video Pretty much, Arthur. Allegro has/uses some OpenGL at its core, right? Would the Allegro 5 library itself support glDrawPixels(), or would I need to include OpenGL in my project alongside Allegro 5? I have to #include <allegro5/allegro_opengl.h> and link in at least the GL library. "...and link in at least the GL library." The wording on that bit throws me off. Care to elaborate? I know very little about RP, if you're using GCC, you'd link -lGL at the command line, similar to -lallegro. How is this screen connected? It sounded to me like it wasn't a regular monitor. If it's a regular monitor A5 should work with OpenGL. If it's just something that you plugin USB or something that gives you /de/fb* device, it won't work with OpenGL. You'll have to add framebuffer support to A5. Just for fun, I threw together a little "framebuffer" demo. First couple seconds, it shows a blank white screen, then it draws a red line and blue line across the screen, and after four seconds, starts filling the screen with a gradient (one scanline per frame) and then after a few more seconds, draws 1000 random pixels per frame. It'll end by itself after the screen is full of dots, or hit ESC. [EDIT] I forgot the compile command gcc -s -O2 -Wall main.c -o t -lallegro -lGL In this case I think we're talking about the linux framebuffer "fbdev" remember playing with the framebuffer a bit a couple years ago on Slackware, but what difference does it make? In that demo I put up last post, you set ints in an array to whatever color you want them to be, then use glDrawPixels() to blit that to the screen. You could do a software rendered 3D game if you wanted. You use the framebuffer device to actually output to the screen attached to it. And there may not be GL support on those devices. And there may not be GL support on those devices. So A5 for Raspberry Pi uses DirectX? Or A5 has something else? After googling a bit, I see that OpenGL ES doesn't have glDrawPixels(). First off, let me say that I am extremely appreciative of each of you posting your thoughts and ideas on this forum. Secondly, yes, this does pertain to the Linux framebuffer "fbdev" drivers. I have a small (128x160 resolution) TFT LCD attached to my RPi via GPIO pins, and have it attached to /dev/fb1. I followed this tutorial to get the drivers working. Arthur, I appreciate you writing a demo for me. One thing I've noticed from examining the source files is that there is no GLES directory on Allegro 5.0.6. So, when I tried your demo, it threw me an error saying... "In file included from main.cpp:4:0:/usr/local/include/allegro5/allegro_opengl.h:63:21: fatal error: GLES/gl.h: No such file or directory compilation terminated." So, allegro_opengl.h is including GLES/gl.h, but that doesn't exist as far I can see on 5.0.6. I took a look at the 5.0.9 release and couldn't find GLES there either. Perhaps I'm blind? So A5 for Raspberry Pi uses DirectX? Or A5 has something else? After looking at the OPs links, yeah, no the LCD device he's talking about will NOT have hw GL support of any kind. Its a small TFT lcd riding on the SPI bus. It might be possible that the lcd driver on the tft lcd module might have some acceleration for basic things like clears and basic drawing, but I highly doubt it'll have anything more than that. So basically, all he gets is framebuffer access to the device, which is likely going to be very slow as the SPI bus can be quite slow (1-10MB/s?). append2: I took a look at the 5.0.9 release and couldn't find GLES there either. Perhaps I'm blind? It's built into the opengl code. Actually, I have the console and x11 desktop environment displaying on the LCD at ~60 FPS, so the display itself is actually quite fast. As for the above being built into the OpenGL code, how come it can't procure the appropriate files upon compilation? If Allegro 5 is ultimately unable to draw to my LCD, then the only other options are to 1) Use SDL (which I believe can accomplish this), or 2) Use an LCD with composite jacks, which would act like a regular TV. The issue with the first option is that I enjoy Allegro much more than SDL, and the second is that it would cost me more money and is more cumbersome. So at this point I'm willing to try virtually everything with Allegro. Are you really sure the LCD is actually updating at 60fps? I somehow doubt it. Some google results hint at 32mhz being the maximum useable SPI frequency on the pi, which might get you 40fps for 16bit color. As for the above being built into the OpenGL code, how come it can't procure the appropriate files upon compilation? I meant to say that allegro's OpenGL ES code is part of allegros OpenGL code. They aren't separate ports, a lot of the code between the two is very similar, so there's a few ifdefs here and there to determine whether you want GL or GLES for each port. "Are you really sure the LCD is actually updating at 60fps? I somehow doubt it. Some google results hint at 32mhz being the maximum useable SPI frequency on the pi, which might get you 40fps for 16bit color." (Too lazy to properly quote you, sorry. Ha ha.) I'm not an expert at frame rates, nor did I properly measure it myself, but it feels and definitely looks like ~60 FPS. I'm quite impressed with the small display, actually. Also keep in mind that LCDs on the Pi itself are quite experimental, so there's a lot of mention of it floating around, some of which is spot on and others which is outdated. As for GL and GLES, do you know what ifdefs I'd need to use to specify one over the other? I'm unexperienced in this respect. There is no GL or GLES support for your LCD device. I am 100% certain of that. What you'll want to do, is try and get Mesa Software support on the fbdev device, and see if allegro plays well with that, or do as Trent suggested and see if you can't resurrect the old GPX Wiz driver code which knows what a /dev/fbX device is. I imagine you mean this when you mention "Mesa Software"? As for resurrecting old drivers, do you know where the build for that is? I did a few quick searches for it and only came across mention of it on forums and a few entries from Trent's blog, but not source itself. Perhaps you'd know, Trent? Thanks for the continual input, Thomas. [EDIT]You're correct about the lack of GL nor GL ES support on the Pi. I'm looking for the Wiz whatnots now. I pinpointed where Trent's work on the GP2X Wiz began; it was here. Also, it seems that the last entry in his blog regarding the Wiz was this one here. At least, the last I've seen so far. Cool stuff! You have to go back in git history to find it. There are ways to search old history like git log --name-status. You can narrow the search by looking around those dates of those blog posts. git help <command> and Google will tell you all you need to know to dig it out. Ha, scratch that. It was never removed from the repo. It's in src/gp2xwiz. Wha? I could swear you committed a "remove gp2x" changeset. Maybe we're both crazy.
https://www.allegro.cc/forums/thread/612537/982120
CC-MAIN-2018-51
refinedweb
1,704
74.49
On Sun, 2009-11-29 at 21:17 -0500, Jonathan Yu wrote: > Hi: > > [Cc'ing Adam Kennedy since I'm not sure if he's subscribed to debian-devel] > > Since Adam mentions that Perl's pip predates Python's pip by a > significant margin, I think we should close this issue by renaming > Python's installer back to pyinstall. It doesn't seem fair for someone > who came on the scene later (who didn't do the appropriate research, > and who, when prompted with the problem, decided to proceed with pip > anyway) to be able to usurp the namespace from Perl. Some facts: ----------- pip - It's in the archive since 2002-08 - It never entered testing or stable - It's average popcon since 2004 is about 10 (out of 70000) - It's popularity suddenly increased in Octobre (reaching 68) python-pip - It's in the archive since 2009-04 - It is in testing - It's popcon is slowly and constantly increasing, reaching 57/70000 Why (perl) pip popcon suddenly[1] reached 68? Is it due to the new version, or is it due to people installing it by mistake? Non-factual! ------------ WTF? 1. Can't perl and python upstream just talk together, this is not just about Debian. Having two ${p}-installer-program it just so convenient, what ever the platform! 2. <flame> Don't we use apt/dpkg in Debian? Do those $pip install stuffs outside /usr/local? Shouldn't those packages description mention that users should ITP/RFP desired modules? and that modules installed "manually" are guaranteed to: - Never be upgraded by Debian on upgrade/security updates - Conflict with some properly installed packages - Download untrusted/unsigned material (?) - Download stuffs with unknown license (?) - Never be supported by Debian </flame> /usr/bin/pip should be a wrapper to invoke perl-pip and python-pop randomly, in order to be really fair. My 2¢ Franklin popcon data: 2009-05: python-pip 3 0 0 3 0 2009-05: pip 8 1 7 0 0 2009-06: python-pip 18 0 6 12 0 2009-06: pip 8 1 7 0 0 2009-07: python-pip 19 1 15 3 0 2009-07: pip 8 0 8 0 0 2009-08: python-pip 25 1 15 9 0 2009-08: pip 8 0 8 0 0 2009-09: python-pip 32 6 20 6 0 2009-09: pip 9 0 9 0 0 2009-10: python-pip 42 11 25 6 0 2009-10: pip 9 0 9 0 0 2009-11: python-pip 51 9 34 8 0 2009-11: pip 19 4 7 8 0 2009-12: python-pip 55 14 34 7 0 2009-12: pip 68 15 10 43 0 [1]
http://lists.debian.org/debian-devel/2009/12/msg00001.html
CC-MAIN-2013-20
refinedweb
453
57.74
If you are new to python programming and if you’re using ubuntu linux as your operating system then you can start programming easily as Ubuntu comes up with the command line version of python pre-installed. Ubuntu community develops its own tools and scripts under python,so you can learn a lot from the community. Official Community also offers bounties on some of its python projects. So in that way you can also get in touch with the experienced python developers. In python you have two choices to learn how to program, one is with command line version and another is IDLE. I’ll explain both these methods one by one. Command Line Command line version of python is already installed in Ubuntu. To get into python’s interactive mode,Click on Appliations>Accesorries>Terminal. Then type ‘python’ without quotes,that will open up the interactive mode of the python.Now you can test your python scripts. You can also write the program with help of text editor like gedit or Emacs. Then save it with extension .py. Now if you want to execute that file,then open the terminal, move yourself to the directory where that .py file exists. Then type the following commands in terminal. python hello.py this will execute the program. Once program is executed you’ll return back to the command prompt.To exit from the python interpreter type the following: import sys;sys.exit(); or you can use exit(); or CTRL-D This will exit from the interpreter and return back to the terminal. IDLE If you don’t want to use the command line version of python then there is another choice “IDLE”. IDLE means interactive developement envirement. IDLE is a Python IDE that includes a GUI debugger based on pdb. IDLE is not installed in ubuntu by default, you have to install it from DVD. To install the IDLE,follow these steps. Click on Application>Add-remove applications. In Add-remove applcations select categary > Programming >then Select “IDLE” check-box point.Click OK. Then it will ask for the install disk and then installs it from there. Now you can write your program with help of text editor like emacs/gedit. Once you’re done with it,save it with extension .py. Now right click “Open with” then select >IDLE. OR you can open the file from IDLE. IDLE shows the colored syntax of your program. Now to run your program,follow these steps: Click>RUN>Run Module. This will execute the program in the IDLE. (Graphical user interface-GUI for Python) Once you learn the techniques of the text processing in python. Then you need to learn how to program applications in GUI. To program GUI based applcations you have many option like Wxpython,Tkinter,Pyqt etc. Tkinter is a GUI widget set for Python.There are many introductory tutorials for the Tkinter on the web. Some of them are : [1] Introduction to python [2] Python and Tkinter Programming by John Grayson (Manning, 2000, ISBN 1-884777-81-3) [3] Tkinter reference [Here] WxPython is another GUI toolkit for the Python programming language which allows easy creation of graphical user interfaces.You can obtain more information about Wxpython from official wxpython website. You can learn more from python community so check out the activestate’s “CookBook” where you can learn a lot about the python coding. More Python Tutorials - Python Dictionaries - Python Tuples - Python Lists - Python Date and Time - SQlite Python - Python easy_install modules I hope above information helps.If you have any quesstion & suggestion or errors.Then please don’t hesitate to post it over here. I am just learning to program with Python and found IDLE a bit counter intuitive. My professor advised me SPE: I am very happy with it as especially the uml gives a nice overview of my program. There are still a lot of features to explore, but I am sure one day I’ll know more about them. i’ve just started off with python. the above info was exactly what i was lookin for. thanks Thank you very much, this really helped me to start with programming in Python. I look for forward for more tutorials of you. Keep ’em comin’! Thanks really thanks….. Thanks, this was exactly what I was looking for 😉 Thanks for the info. This is exactly what python beginners need. Thanks for the useful info. thanks dude!! I just discovered Ubuntu 2 weeks ago and am interested in using python,…much thanks. Another nice option for python ide is eclipse. Installing eclipse and adding pydev(without any additional features) plugin helps to write python programs with features of eclipse as in other languages thank you, very useful Thanks for the info although I would like to develop Gnome apps in Python, how would I go about doing this? Great info for a beginner with Linux and Python.It really helped thanks so much. very useful and easy for a beginner. Hi! This is a simple and very useful article. Thank you! Simple and effective for newbie, nice stuff Thanks! 🙂 There is another option to try – using Netbeans Python early access: With python I can build a program for many platforms.. almost! This article is helpful… Thanks a lot! Thank you so much for this. I’m looking to start a Computer Science degree and I found a wonderful book through MIT called Think Python. IT was originally titled Think like a Computer Scientist – Python. He charges 90 for it on Amazon so Thank God he believes in open source and open GL because he provides it for free. He even lists your name in his book if you come up with a helpful change and he replies to your comments, a very nice Computer Science teacher. Any way…. one thing he forgot in chapter two is how to get your script to work after you create a “simple.py” script, how do you run it. I could find nothing that made sense in a windows environment after two days of researching over the weekend. Now I start looking up in the Linux enivronment and (DOH DOH DOH) first try I find the answers to my questions. Sigh, I just wish it was easier to play windows games in linux environment and I’d give up windows altogether. You’ve almost got me. Brad Thank you for this nice information as a beginer like me. thanx for that man Thank you! Quite helpful. python kicks a** . I thot C++ was easiest but hey pythons more logical and easier 😛 Exactly what I was looking for. Thanks heaps 😀 Thanks for nice introduction regarding python,
http://onecore.net/how-topython-programming-under-ubuntu.htm
CC-MAIN-2016-40
refinedweb
1,113
75.4
In Windows Phone, the developers can send SMS from their Windows Phone 8 Programatically using the launchers. The Windows Phone SDK provides the SMSComposeTask launcher which can be used to send SMS in Windows Phone 8. Below is a code snippet demonstrating the usage of the SMSComposeTask to send SMS in Windows Phone 8. How to send SMS in Windows Phone 8 Programatically using C#? using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using Windows.Phone.Speech.Recognition; using Windows.System; namespace AbundantCodeWP8 { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); } private void Button_Click_1(object sender, RoutedEventArgs e) { SmsComposeTask SMSCompose = new SmsComposeTask(); SMSCompose.To = "<Number to which the SMS needs to be sent"; SMSCompose.Body = "Message that needs to be sent"; SMSCompose.Show(); } } } Is there a way to access sms inbox ? No , the Windows Phone 8 SDK does not have the API does not allow the access at this moment Will the SMS sent programatically appear in the Sent Messages of the phone?? This will appear in the Messaging App of your Windows Phone device. Will the message be sent or we will have to confirm?? ( ie, should we press send?? ) Cant we send SMS without user interaction (without poping SMS app)? Without interaction is currenting not possible to send email
http://abundantcode.com/how-to-send-sms-in-windows-phone-8-programatically-using-c/
CC-MAIN-2018-26
refinedweb
227
52.87
Tutorial: Embed a Power BI report, dashboard, or tile into an application for your customers With Power BI Embedded in Azure, you can embed reports, dashboards, or tiles into an application using app owns data. App owns data is about having an application that uses Power BI as its embedded analytics platform. Using app owns data is typically an ISV developer scenario. As an ISV developer, you can create Power BI content that displays reports, dashboards, or tiles in an application that is fully integrated and interactive, without requiring users of the application to have a Power BI license. This tutorial demonstrates how to integrate a report into an application using the Power BI .NET SDK along with the Power BI JavaScript API when using Power BI Embedded in Azure for your customers using app owns data. In this tutorial, you learn how to: - Register an application in Azure. - Embed a Power BI report into an application. Prerequisites To get started, you need a Power BI Pro account (this account is your master). Set up your embedded analytics development environment Before you start embedding reports, dashboard, or tiles into your application, you need to make sure your environment is set up to allow for embedding. As part of the setup, you need to do the following. You can go through the Onboarding experience tool to quickly get started and download a sample application that helps you walk through creating an environment and embedding a report. However, if you choose to set up the environment manually, you can continue below. Register an application in Azure Active Directory (Azure AD) You register your application with Azure Active Directory to allow your application access to the Power BI REST APIs. This allows you to establish an identity for your application and specify permissions to Power BI REST resources. Accept the Microsoft Power BI API Terms. In the left-hand navigation pane, choose All Services, select App Registrations, and then select New application registration. Follow the prompts and create a new application. For apps owns data you need to use Native for the application type. You also need to provide a Redirect URI, which Azure AD uses to return token responses. Enter a value specific to your application (for example:). Apply permissions to your application within Azure Active Directory You need to enable additional permissions for your application in addition to what was provided on the app registration page. You need to be logged in with the master account, used for embedding, which needs to be a global admin account. Use the Azure Active Directory portal Browse to App registrations within the Azure portal and select the app that you are using for embedding. Select Settings, then under API Access select Required permissions. Select Windows Azure Active Directory and then make sure Access the directory as the signed-in user is selected. Select Save. Select Add. Select Select an API. Select Power BI Service, then select Select. Select all permissions under Delegated Permissions. You need to select them one by one to save the selections. Select Save when done. Within Required permissions, select Grant Permissions. The Grant Permissions action needs the master account to avoid being prompted for consent by Azure AD. If the account performing this action is a Global Admin, you need to grant permissions to all users within your organization for this application. If the account performing this action is the master account and is not a Global Admin, you need to grant permissions only to the master account for this application. Set up your Power BI environment Create an app workspace If you are embedding reports, dashboards, or tiles for your customers, then you have to place your content within an app workspace. The master account must be an admin of the app workspace. Start by creating the workspace. Select workspaces > Create app workspace. This is where you place the content that your application needs to access. Give the workspace a name. If the corresponding Workspace ID isn't available, edit it to come up with a unique ID. This needs to be the name of the app, too. You have a few options to set. If you choose Public, anyone in your organization can see what’s in the workspace. Private, on the other hand, means only members of the workspace can see its contents. You can't change the Public/Private setting after you've created the group. admins and members can publish the app. Now you can view the new workspace. Power BI creates the workspace and opens it. It appears in the list of workspaces in which you’re a member. Because you’re an admin, you can select the ellipsis (…) to go back and make changes to it, adding new members or changing their permissions. Create and publish your reports You can create your reports and datasets using Power BI Desktop and then publish those reports to an app workspace. The end user publishing the reports need to have a Power BI Pro license to publish to an app workspace. Download the sample Blog Demo from GitHub. Open sample PBIX report in Power BI Desktop Publish to the app workspace Now you can view the report in the Power BI service online. Embed your content using the sample application Follow these steps to start embedding your content using a sample application. Download the App Owns Data sample from GitHub to get started. Open up the Web.config file in the sample application. There are 5 fields you need to fill in to run the application successfully. The clientId, the groupId, the reportId, the pbiUsername and the pbiPassword. Fill in the clientId information with the Application ID from Azure. The clientId is used by the application to identify itself to the users from which you're requesting permissions. To get the clientId, follow these steps: In the left-hand navigation pane, choose All Services and select App Registrations. Select the application that you want to get the clientId for. You should see an Application ID that is listed as a GUID. Use this Application ID as the clientId for the application. Fill in the groupId information with the app workspace GUID from Power BI. Fill in the reportId information with the report GUID from Power BI. - Fill in the pbiUsername with the Power BI master user account. - Fill in the pbiPassword with the password for the Power BI master user account. Run the application! First select Run in Visual Studio. Then select Embed Report. Depending on which content you choose to test with - reports, dashboards or tiles - then select that option in the application. Now you can view the report in the sample application. Embed your content within your application Even though the steps to embed your content can be done with the Power BI REST APIs, the example codes described in this article are made with the .NET SDK. Embedding for your customers within your application requires you to get an access token for your master account from Azure AD. It is required to get an Azure AD access token for your Power BI application using app owns data before you make calls to the Power BI REST APIs. To create the Power BI Client with your access token, you want to create your Power BI client object which allows you to interact with the Power BI REST APIs. This is done is a report, dashboard, or tile that you want to embed is available within the Controllers\HomeController.cs file in the sample application. using Microsoft.PowerBI.Api.V2; using Microsoft.PowerBI.Api.V2.Models; // You need to provide the GroupID where the dashboard resides. ODataResponseListReport reports = client.Reports.GetReportsInGroupAsync(GroupId); // Get the first report in the group. Report report = reports.Value.FirstOrDefault(); Create the embed token An embed token needs to be generated which can be used from the JavaScript API. The embed token is specific to the item you are embedding. So at any time you embed a piece of Power BI content, you need to create a new embed token for it. For more information, including which accessLevel to use, see GenerateToken API. Here is a sample of adding an embed token for a report to your application. A sample of creating an embed token for a report, dashboard, or tile is available within the Controllers\HomeController(GroupId, report.Id, generateTokenRequestParameters); // Generate Embed Configuration. var embedConfig = new EmbedConfig() { EmbedToken = tokenResponse, EmbedUrl = report.EmbedUrl, Id = report.Id }; This assumes a class is created for EmbedConfig and TileEmbedConfig. A sample of these. This the is time to back your app workspace with a dedicated capacity. cannot access Power BI content with a FREE Power BI license. Using embed tokens with PRO licenses are intended for development testing, so the number of embed tokens a Power BI master account can generate is limited. You must purchase a dedicated capacity for embedding in a production environment. There is no limit on how many embed tokens you can generate with a dedicated capacity. Go to Available Features to check the usage value that indicates the current embedded usage in percentage. The usage amount is based per master account. For more details, see Embedded analytics capacity planning whitepaper. Assign an app workspace to a dedicated capacity Once you create a dedicated capacity, you can assign your app workspace to that dedicated capacity. To complete this, follow these steps.
https://docs.microsoft.com/en-us/power-bi/developer/embed-sample-for-customers
CC-MAIN-2018-34
refinedweb
1,571
57.16
Is it acceptable/Pythonic to use a method in a class as a generator? All the examples I have found show the yield statement in a function, not in a class. Here is an example working code: class SomeClass(object): def first_ten(self): for i in range(10): yield i def test(self): for i in self.first_ten(): print i SomeClass().test() Yes, this is perfectly normal. For example, it is commonly used to implement an object.__iter__() method: class SomeContainer(object): def __iter__(self): for elem in self._datastructure: if elem.visible: yield elem.value However, don't feel limited by that common pattern; anything that requires iteration is a candidate for a generator method.
https://codedump.io/share/cT6nxXQR1ad1/1/can-a-method-within-a-class-be-generator
CC-MAIN-2018-26
refinedweb
116
61.12
User Name: Published: 29 Jul 2009 By: Andrew Siemer Download Sample Code In the previous article we discussed the idea of a dynamic email drop box. In this article we will take a look at the first half of our task list. In the previous article we discussed the idea of a dynamic email drop box. We took a look at some existing services that are offered that piggy back a feature like this. I then defined a quick list of all the tasks that we would need to perform to create an email drop box. In this article we will take a look at the first half of our task list. We will discuss how to set up your pop3 server so that it can support the drop box feature. We will then take a look at what is required for your application to communicate with your pop3 server. And finally we will go over some of the basic email parsing that is required to get us to the making the actual features. Let’s get started! In order for our entire application to work we must first set up an email address that can collect all of the email for a specific domain on behalf of our users. This address might look like dropbox@andrewsiemer.com. The key here is that the users won’t be sending their emails to this address directly (although they could if they so chose). They would instead be sending their communications to VeryPrettyGirl123@andrewsiemer.com or ScottsWidgets@andrewsiemer.com. These email addresses won’t physically exist on our pop3 server and so it will be the duty of dropbox@andrewsiemer.com to accept them up for later distribution. To set this email address up appropriately we need to take a look at setting up an email alias. An alias is a recipient mapping rule. You might think of this as a regular expression for recipient email addresses. Any email that comes into the pop server that matches the specified rule will get routed according to that rule. In our case we need to create a dropbox@andrewsiemer.com email account. Then go to the alias’ configuration for that newly created account and add a rule for *@andrewsiemer.com (or whatever is appropriate for your type of pop server to collect “ALL” unknown emails delivered to that domain). This means any email that comes to the andrewsiemer.com domain that doesn’t match a physical account on the server will get sent to dropbox@andrewsiemer.com. I can’t really show you step by step instructions on how to set up an alias as every pop server is different! Just do a quick search for your mail server name and “set up an address alias”. You should get many specific listings on this topic! Once you have your dropbox@YourDomain.com email address created, test it by sending an email to someaccount@YourDomain.com. Verify that this email was indeed delivered to your dropbox account. If it worked, send 4 or 5 test emails to various accounts so that we have something to code against in the next section. I am not sure why tools don’t exist in the .NET framework to interact with a pop3 server in a clean fashion (as they do for sending mail through an SMTP server). While you can buy many widgets that interact with a pop3 server I figured we may as well address the need ourselves directly. A quick Google search of “C# pop3” will give you loads of tutorials on how to connect to and interact with a pop3 server as well as discussing the basics of pop3 interactions using telnet. However, none of them appear to really provide you with a good framework or wrapper to hide the complexities of communicating with your pop3 server. These communications after all rely directly on RFC 1725 – or simple telnet commands via TCP with your pop3 server. Talk about old school! Keep the RFC specification in front of you to help you decipher the responses you get back from your server while coding – it will help you understand things better. Let’s first get started by creating a directory structure to work in. I like to work with all of my solutions resources (not just code) under a “trunk” directory. Next I would have my “src” (or source) directory where all of my projects go. If I had documents, a database, artwork, or other items those would go under trunk as well. As I know that I will be adding a database to collect email message data, solution wide configuration resources, etc. I like to start each project with a specific directory structure. I do this for a couple of reasons. First, if all of my projects big or small are laid out in the same way in theory I should be able to open any project and know specifically where to go for a given item. Second, if this works for me then it also stands to reason that it will help people that inherit my projects (like you!). Then in Visual Studio we will create a C# Class Library project which will live inside the “src” directory. I named my project PopClient and set the assembly name and namespace to be “AndrewSiemer.Email”. Feel free to name your assemblies and namespaces as you wish. I generally try to follow along with the suggested best practice of CompanyName.TechnologyName as the root or in my case DomainName.TechnologyName. This is in following with how the .NET framework is put together and is easy for people to follow! This is a good resource for naming conventions: In this project I have created the following class files in the root of the project: ConfigurationService.cs, Extensions.cs, Message.cs, MessageSummary.cs, Pop3Exception.cs, and PopClient.cs. I also added a reference to System.Configuration for future use. System.Configuration There are some configuration aspects to our program so I am going to start off by introducing our ConfigurationService class. While we could just hard wire some values for now I know that we will need the ability to play with these values down the road. For that reason it makes sense to set up a utility to make configuration quick and painless. ConfigurationService This will be a no frills class that provides two private methods GetNumberFromConfig(string Key) and GetStringFromConfig(string Key). This class allows me a way to centralize all communications with my configuration files in case I need to swap my configuration plumbing out down the road (a wrapper if you will). From this class I expose public methods for each of my configuration keys. The ConfigurationService class is shown in the listing below. GetNumberFromConfig(string Key) GetStringFromConfig(string Key This class (and possibly some others) doesn’t have any or much error checking/handling. In a production environment you may want to extend this code to incorporate some basic error handling and checking. Once we have this class built we then need to put a configuration file under it. In this case I didn’t simply add an app.config file to my existing project. I added the app.config to my src directory above my project directories. This way all of my projects can have access to the same config file as a linked resource. This will make sense when we build our window service. Here is what my configuration looks like at the moment: Next I have a couple of structures that I defined to help us with moving data around. These are basically data transfer objects (or DTO’s for short). We have a Message and a MessageSummary. MessageSummary The Message object is used in our application as a container to hold the data that we will parse out of an email message. An email message is basically a large blob of text (for the most part). It has a lot more data in it than we care about so we will eventually get to a point where we will extract what we need from that blob and push it into this message object where we can then more easily interact with the items that we care about. The MessageSummary is a similar DTO style object in that it will carry some parsed data. In this case though we won’t get the data from an email message. Instead we will be getting it from a response from our pop3 server. MessageSummary Next we will discuss our Pop3Exception class. This is a custom ApplicationException based class that we will use to express possible errors or response messages in our application. While we could have chosen to inherit directly from the base class Exception I chose ApplicationException as it was created specifically for user’s applications to create their own custom exceptions (ApplicationException after all inherits from Exception). One rule of a top notch programmer is that you never try to handle Exception directly and so one should use ApplicationException to build out custom exceptions which can then themselves be trapped in your error handling logic. You will see that I handle the base class exceptions directly throughout my code though – sorry! As it turns out this is a huge battle between purists and everyone else. Take a look here for more information on this subject: I prefer to minimize flames on silly subjects such as this though. (although the word choice SILLY may cause flames!) Pop3Exception ApplicationException Exception Exception This is a simple exception that pushes the error message through to the base ApplicationException class. Finally we will look at our Extensions utility. In this class I defined a PrintMessage method that our Message object can use. This will help us when debugging later so that we can easily print a Message in the command window. Nothing fancy here. This is just a simple extension method that builds a formatted string of all the data in the Message object. Extensions PrintMessage With all of the set up stuff out of the way we can now take a look at the PopClient code. To interact with our pop3 server we are going to be using TcpClient, NetworkStream, StreamReader, byte arrays, and strings. Some familiarity with these would be good but is not required. We will define methods to connect, disconnect, list messages, delete messages, get message counts, etc. PopClient TcpClient NetworkStream StreamReader The best place to start with our PopClient is with the general use variables. From top to bottom (in the listing below) you will see the declaration of the TcpClient which is used to connect to the pop3 server. Next you will see our NetworkStream which is used to send commands to the server. Then our StreamReader which we use to read the response from the server. Then we have the _data string which we format our commands in. We then break the commands (_data) into a byte array and place it into _arrData (which is what is sent to the server). Then we have _crlf which is used for formatting our commands and messages. The remaining _popServer, _username, _password, and _port variables are used for getting to and authenticating with the pop server. TcpClient NetworkStream StreamReader _data data arrData _crlf _popServer _username _port Then we have the constructor for PopClient. Here we are reading our configuration values from our ConfigurationService (discussed above). PopClient Keep in mind that according to RFC 1725 all commands are terminated by a CRLF pair. Also, there are two status indicators: positive “+OK” and negative “-ERR” which you can use to interrogate how things are going with your communications. And the biggest thing to keep in mind – POP3 is a state based protocol. Initially you are in an authorization state where you authenticate yourself to the server. You are then moved into a transaction state where you issue commands to and interact with the pop server. When you finally issue the QUIT command you enter the update state. In this last state is where any modifications you might have made to the server are actually applied. If your session times out or you somehow disconnect from the server without issuing the QUIT command your changes are not committed! Next we get to our most important method – the Connect method. As the name suggests we will use this method to connect to our pop server. The first part is probably the most important part. We are instantiating a connection via our TcpClient with our pop server. We do this by specifying our pop servers address and port. We then open up our NetworkStream by calling _server.GetStream(). Next we set up our StreamReader in the same manner as the NetworkStream so that we can receive the responses from the server. We are now set up to send commands to the server and receive data (responses) back from the server. Keep in mind that once you connect, this socket is open until you disconnect or dispose of the PopClient, or the session times out. Connect server.GetStream You will notice a lot of Console.WriteLine(_streamReader.ReadLine()); calls. Don’t remove this in an effort to “clean house” so to speak. They are important as each time you issue a command you will get a response. You need to read this response or you will have data backed up in your stream reader. Eventually you will want to get an email or read a STAT command and you will get some other response data that was not properly flushed out from a previous command. Just a warning as this can be a booger to debug! Console.WriteLine streamReader.ReadLine()); Once connected to the server we are put into the authentication state. In this state we must issue the username (USER) and password (PASS) commands to the server so that it can authenticate us and locate our email account. Once connected and authenticated remember that all your resources are open and waiting for use! You are next put into the transaction state where you can issue any of the other commands such as listing your messages, deleting messages, reading a message, etc. All of these interactions with your pop server are pretty much identical to issuing your username command or password command. For this reason we will not delve into them specifically. Take a look at the attached source code for all of these listings. Next let’s take a look at working with the server responses and specifically how to parse the data that we are most interested in. Email parsing is not really a terribly tricky business. In reality it is digging into a text response and isolating the information that you are most interested in. In our first example we will look at the data that comes back from the LIST command. The LIST command returns to us a list of all the emails in the system and their size. It doesn’t return the actual email but instead returns the index of each email and the size of that email. The data returned from the LIST command might look something like this: Notice that our response starts off with a “+OK”. You can always check for this to ensure that your response will contain what you think it will. Then notice that the last line of the response is a “.”. You can also test for this to determine the end of your response message (though it is not guaranteed to be at the end of EVERY message!). The data that we are actually interested in here is the index (the number on the left) and the message size (the number on the right). In order to get to each of these values we need to move past the first response and pass each consecutive response to our MessageSummary parser until we hit the final period. The code for that process looks like this: With each iteration over our LIST responses we make a call to ParseMessageSummary(readerOutput). This is where we get our first parsing done. In the case of the LIST data this is very easy to dig into. We take the string that is passed in, split it on a space, and read the appropriate index for the value that we would like to get. We then pass that value into an instance of a MessageSummary and then return it to the caller. ParseMessageSummary(readerOutput The last form of parsing is fairly easy compared to our next set of tasks. It is all pretty straight forward as you will see shortly. Now we can take a look at parsing an actual mail message. Once we have a listing of emails we can then choose to download an actual message. Downloading a message might come in two forms. We might know a specific email message that we are interested in, in which case we would call the GetMessage method. With this method we would pass in the index of the email message we are interested in. Or we might execute the LIST command and iterate through all the email messages on the server. Either way, we have to parse the email messages that are passed down. GetMessage Before we discuss parsing in depth let’s take a look at what a raw email message might look like. Notice that it starts with a “+OK” and after that…well that is a whole different article! WOW! I don’t know if you noticed but all of the above text was simply to send the following line of text: Yep. You may have also noticed that there are some bits of information in there that are fairly easy to get to. The Message-ID, From, To, Subject, and Date are tags that we can test for at the beginning of each new line. Do notice that when there are multiple email addresses in the To field that we have a different type of format to work with! If we had CC’d someone here they would show up too. The other bit that we will be interested in gathering for the purpose of our drop box application is this: And this bit: These are the actual body of the email that was sent. The important parts to watch for are the bracketing pieces of that text. The chunks that starts with Content-Type: text/plain; and Content-Type: text/html;. Both of them end with ------=_.... Content-Type: text/plain; Content-Type: text/html With that quick text analysis let’s take a look at the actual ParseMessage method. You will notice that the majority of the work is done by iterating through each line of the email message. We look at each line once and only once. We run each line through various tests to find out what we are dealing with and process it accordingly. ParseMessage There is much room for optimization here. You could break the message string into an array of strings by line and then use LINQ to query that for what you need. Or you could optimize this code by discontinuing the interrogation after you find a match for each line rather than continuing to test after a match is found! Most of the tests are easy in that they sample the first part of the line to look for things such as “Date:” or “Subject:”. There are however other cases where things are a bit more complex. When we locate the “To:” field for example there is possibly the case where we may have more than one email address. Each additional email address comes in on a new line. For this reason when we locate a “To:” tag I set a ReadingTo flag to true to indicate that each following iteration may be an additional email address. Once we get to the next field (I only test for “Subject:” but there may be other insertions available that would need to be tested for) we can turn off the ReadingTo flag and continue parsing for other fields. ReadingTo true We play similar games when it comes to reading the text and html versions of the email’s message. As we parse the bits of data out of the message that we need we can feed them into our Message object. As there is tons of data in an email message there is much room for improvement for this parser. You can expand the Message object to hold as much of if not all of this data as you see fit. Once the message is parsed appropriately we can then return what we need as a simple to use Message object. Once you have had a chance to dig through the PopClient’s full code listing (in the source code download) and understand all of the functionality that it offers then the next logical step is to toss together a test harness. I generally use a console application to do this. Let’s add a new project to our solution. We will add a C# console application to the “src” directory and name it TestHarness. Next we need to add a project reference to our new project. Add a reference to the PopClient project. Then open up your program.cs file. In there you can play with your new PopClient till your heart’s content. In my test harness I have the following: Not everything in the PopClient will output something to the console apps window. Many of the methods will though. Feel free to add some Console.WriteLine() statements where you are interested to see what’s going on. Console.WriteLine() Notice that in my test harness project I am running through some of the basic commands of the PopClient. I start by instantiating a new PopClient. I then ask it to Connect to my pop server. Then we call ListMessagesSummary and then GetMessageCount. Next I make a list of all the messages on the pop server and print them to the console using the extension method we looked at: PrintMessage. Then I ask for a specific message using the GetMessage method. I have some code there to delete a message but don’t run that over and over again as it kills all of my test messages! Finally I call Disconnect and close the connection to the pop server. ListMessagesSummary GetMessageCount PrintMessage Disconnect In this article we took a look at setting up the base framework for our application. We configured our pop3 server to accept email on behalf of our users. We then created a pop3 client framework to allow our application to communicate with our pop3 server. Then we analyzed the incoming email packets and set up some basic email parsing to make working with the received emails a little less painful. With the PopClient completed we created a quick little test harness to make sure that it works as expected. In the next article we will finish up our email drop box application. We will start by creating some account matching tools. Then we will take a look at how we can support tags in our emails. Then we will take a closer look at how to use those tags to support specific features such as statuses, blog posts, and anonymous user messaging. Finally we will finish up our application by sticking all of this functionality into a window service. See you then! This author has published 29 articles on DotNetSlackers. View other articles or the complete profile here.
http://dotnetslackers.com/articles/aspnet/Creating-a-Dynamic-Email-Drop-Box-Part2.aspx
crawl-003
refinedweb
3,924
71.65
pytest-travis-foldpytest-travis-fold Pytest plugin that folds captured output sections in Travis CI build log. In addition, pytest-travis-fold recognizes presence of the pytest-cov plugin and folds coverage reports accordingly. Installation and UsageInstallation and Usage Just install the pytest-travis-fold package as part of your build. When using tox, add the package to the deps list in your tox.ini and make sure the TRAVIS environment variable is passed: [testenv] deps = pytest-travis-fold passenv = TRAVIS If you don't use tox and invoke py.test directly from .travis.yml, you may install the package as an additional install step: install: - pip install -e . - pip install pytest-travis-fold script: py.test Output folding is enabled automatically when running inside Travis CI. It is OK to have the plugin installed also in your dev environment: it is only activated by checking the presence of the TRAVIS environmental variable, unless the --travis-fold command line switch is used. The travis fixture The plugin by itself only makes the captured output sections appear folded. If you wish to make the same thing with arbitrary lines, you can do it manually by using the travis fixture. It is possible to fold the output of a certain code block using the travis.folding_output() context manager: def test_something(travis): with travis.folding_output(): print('Lines, lines, lines...') print('Lots of them!') ... Or you may want to use lower-level travis.fold_string() and travis.fold_lines() functions and then output the result as usual. ContributingContributing Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request. LicenseLicense Distributed under the terms of the MIT license, "pytest-travis-fold" is free and open source software IssuesIssues If you encounter any problems, please file an issue along with a detailed description.
https://libraries.io/pypi/pytest-travis-fold
CC-MAIN-2019-47
refinedweb
310
58.48
Building Animated Components, or How React Makes D3 BetterBy Swizec Teller This article was peer reviewed by Mark Brown and Jack Franklin. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! D3 is great. As the jQuery of the web data visualization world, it can do everything you can think of. Many of the best data visualizations you’ve seen online use D3. It. 🙌} <Histogram data={engineerData} value={(d) => d.base_salary} x={450} y={0} width={400} height={200} <Histogram data={programmerData} value={(d) => d.base_salary} x={0} y={220} width={400} height={200} <Histogram data={developerData} value={(d) => d.base_salary} x={450} y={220} width={400} height={200} <erat. A Practical Example We’re going to build an animated alphabet. Not because it’s the simplest example of using React and D3 together, but because it looks cool. When I show this at live talks, people always oooh and aaah, especially when I show proof that only the DOM elements with changes get redrawn. This is a shortened version of a more in-depth article on React and D3 and transitions that I posted on my blog a few months ago. We’re going to gloss over some details in this version to keep it short. You can dive into the full codebase in the github repository. The code is based on React 15 and D3 4.0.0. Some of the syntax I use, like class properties, is not in stable ES6 yet, but should work if you use create-react-app for your tooling setup. ———— To make an animated alphabet, we need two components: Alphabet, which creates random lists of letters every 1.5 seconds, then maps through them to render Lettercomponents Letter, which renders an SVG text element, and takes care of its own enter/update/exit transitions We’re going to use React to render SVG elements, and we’ll use D3 for transitions, intervals, and some maths. The Alphabet Component The Alphabet component holds the current list of letters in state and renders a collection of Letter components in a loop. We start with a skeleton like this: // src/components/Alphabet/index.jsx import React, { Component } from 'react'; import ReactTransitionGroup from 'react-addons-transition-group'; import * as d3 from 'd3'; require('./style.css'); import Letter from './Letter'; class Alphabet extends Component { static letters = "abcdefghijklmnopqrstuvwxyz".split(''); state = {alphabet: []} componentWillMount() { // starts an interval to update alphabet } render() { // spits out svg elements } } export default Alphabet; We import our dependencies, add some styling, and define the Alphabet component. It holds a list of available letters in a static letters property and an empty alphabet in component state. We’ll need a componentWillMount and a render method as well. The best place to create a new alphabet every 1.5 seconds is in componentWillMount: // src/components/Alphabet/index.jsx componentWillMount() { d3.interval(() => this.setState({ alphabet: d3.shuffle(Alphabet.letters) .slice(0, Math.floor(Math.random() * Alphabet.letters.length)) .sort() }), 1500); } We use d3.interval( //.., 1500) to call a function every 1.5 seconds. On each period, we shuffle the available letters, slice out a random amount, sort them, and update component state with setState(). This ensures our alphabet is both random and in alphabetical order. setState() triggers a re-render. Our declarative magic starts in the render method. // src/components/Alphabet/index.jsx render() { let transform = `translate(${this.props.x}, ${this.props.y})`; return ( <g transform={transform}> <ReactTransitionGroup component="g"> {this.state.alphabet.map((d, i) => ( <Letter d={d} i={i} key={`letter-${d}`} /> ))} </ReactTransitionGroup> </g> ); } We use an SVG transformation to move our alphabet into the specified (x, y) position, then define a ReactTransitionGroup and map through this.state.alphabet to render a bunch of Letter components with wanton disregard. Each Letter gets its current text, d, and index, i. The key attribute helps React recognize which component is which. Using ReactTransitionGroup gives us special component lifecycle methods that help with smooth transitions. ReactTransitionGroup In addition to the normal lifecycle hooks that tell us when a component mounts, updates, and unmounts, ReactTransitionGroup gives. D3’s hooks operate on entire selections – groups of components – while React’s hooks operate on each component individually. In D3, an overlord is dictating what happens; in React, each component knows what to do. That makes React code easier to understand. I think. ¯_(ツ)_/¯ ReactTransitionGroup gives us even more hooks, but these three are all we need. It’s nice that in both componentWillEnter and componentWillLeave, we can use a callback to explicitly say “The transition is done. React, back to you”. My thanks to Michelle Tilley for writing about ReactTransitionGroup on StackOverflow. The Letter Component Now we’re ready for the cool stuff – a component that can transition itself into and out of a visualization declaratively. The basic skeleton for our Letter component looks like this: // src/components/Alphabet/Letter.jsx import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import * as d3 from 'd3'; class Letter extends Component { state = { y: -60, x: 0, className: 'enter', fillOpacity: 1e-6 } transition = d3.transition() .duration(750) .ease(d3.easeCubicInOut); componentWillEnter(callback) { // start enter transition, then callback() } componentWillLeave(callback) { // start exit transition, then callback() } componentWillReceiveProps(nextProps) { if (this.props.i != nextProps.i) { // start update transition } } render() { // spit out a <text> element } }; export default Letter; We start with some dependencies and define a Letter component with a default state and a default transition. In most cases, you’d want to avoid using state for coordinates and other transient properties. That’s what props are for. With transitions we use state because it helps us keep React’s reality in sync with D3’s reality. That said, those magic default values could be default props. That would make our Alphabet more flexible. componentWillEnter We put the enter transition in componentWillEnter. // src/components/Alphabet/Letter.jsx componentWillEnter(callback) { let node = d3.select(ReactDOM.findDOMNode(this)); this.setState({x: this.props.i*32}); node.transition(this.transition) .attr('y', 0) .style('fill-opacity', 1) .on('end', () => { this.setState({y: 0, fillOpacity: 1}); callback() }); } We use reactDOM.findDOMNode() to get our DOM node and use d3.select() to turn it into a d3 selection. Now anything D3 can do, our component can do. Yessss! 🙌 Then we update this.state.x using the current index and letter width. The width is a value that we Just Know™. Putting x in state helps us avoid jumpiness: The i prop changes on each update, but we want to delay when the Letter moves. When a Letter first renders, it’s invisible and 60 pixels above the baseline. To animate it moving down and becoming visible, we use a D3 transition. We use node.transition(this.transition) to start a new transition with default settings from earlier. Any .attr and .style changes that we make happen over time directly on the DOM element itself. This confuses React because it assumes it’s the lord and master of the DOM. So we have to sync React’s reality with actual reality using a callback: .on('end', ...). We use setState() to update component state, and trigger the main callback. React now knows this letter is done appearing. componentWillLeave The exit transition goes in componentWillLeave(). Same concept as above, just in reverse. // src/components/Alphabet/ componentWillLeave(callback) { let node = d3.select(ReactDOM.findDOMNode(this)); this.setState({className: 'exit'}); node.transition(this.transition) .attr('y', 60) .style('fill-opacity', 1e-6) .on('end', () => { callback() }); } This time, we update state to change the className instead of x. That’s because x doesn’t change. The exit transition itself is an inverse of the enter transition: letter moves down and becomes invisible. After the transition, we tell React it’s okay to remove the component. componentWillReceiveProps The update transition goes into componentWillReceiveProps(). // src/components/Alphabet/Letter.jsx componentWillReceiveProps(nextProps) { if (this.props.i != nextProps.i) { let node = d3.select(ReactDOM.findDOMNode(this)); this.setState({className: 'update'}); node.transition(this.transition) .attr('x', nextProps.i*32) .on('end', () => this.setState({x: nextProps.i*32})); } } You know the pattern by now, don’t you? Update state, do transition, sync state with reality after transition. In this case, we change the className, then move the letter into its new horizontal position. render After all that transition magic, you might be thinking “Holy cow, how do I render this!?”. I don’t blame ya! But we did all the hard work. Rendering is straightforward: // src/components/Alphabet/Letter.jsx render() { return ( <text dy=".35em" y={this.state.y} x={this.state.x} className={this.state.className} style={{fillOpacity: this.state.fillOpacity}}> {this.props.d} </text> ); } We return an SVG <text> element rendered at an (x, y) position with a className and a fillOpacity. It shows a single letter given by the d prop. As mentioned: using state for x, y, className, and fillOpacity is wrong in theory. You’d normally use props for that. But state is the simplest way I can think of to communicate between the render and lifecycle methods. You Know the Basics! Boom. That’s it. You know how to build an animated declarative visualization. That’s pretty cool if you ask me. This is what it looks like in action: Such nice transitions, and all you had to do was loop through an array and render some <Letter> components. How cool is that? 😉 In Conclusion You now understand React well enough to make technical decisions. You can look at project and decide: “Yes, this is more than a throwaway toy. Components and debuggability will help me.” For extra fun, you also know how to use React and D3 together to build declarative animations. A feat most difficult in the olden days. To learn more about properly integrating React and D3 check out my book, React+d3js ES6.
https://www.sitepoint.com/how-react-makes-your-d3-better/
CC-MAIN-2017-22
refinedweb
1,638
50.84
This guide shows how to host a webhook target in a Cloud Run service. Cloud Functions vs Cloud Run Cloud Functions and Cloud Run both provide good solutions for hosting your webhook targets. Generally, Cloud Functions is quick to set up, good for prototyping, and ideal for lower volume workflows. Cloud Run provides more flexibility and is able to handle larger volumes with concurrency. Use Cloud Run if: - You're using languages or runtimes not supported in Cloud Functions - You want longer request timeouts (up to 15 minutes) - You're expecting large volume and need concurrency (80 concurrent requests per container instance) Creating a webhook target in Cloud Run Using Cloud Run, you can define a webhook target in any language you choose. You only need to create an HTTP endpoint that can accept the data. Typically this is done with a POST, for example: @app.route('/', methods=['POST']) def index(): data = request.get_json() In the above example, the index page of the URL is configured to accept only POST requests and expects data to be delivered via a JSON payload. Integrating with the webhook provider Most services that provide HTTP callbacks require you to verify URL ownership. This is usually done by sending some kind of token, message, or secret and expecting a valid response. You'll need to obtain these requirements from the service provider. Using the same example above, this could look like: def index(): data = request.get_json() return data['challenge'] After the provider verifies your ownership, you'll need to add authorization on your end as well. Authorizing requests A webhook target is an open and public URL. Most services provide a token or a secret to ensure that the incoming requests are from authorized services. Because the URL is public, you cannot prevent malicious attempts to send data to the webhook target. However, using tokens or secrets ensures you only process data from authorized sources. In order to verify the request, you need to store your copy of the secret either as an environment variable or using some kind of key management system. Each request should have a secret or token in the request headers or the JSON payload, and you must check it to ensure the source is valid. def index(): request_secret = request.headers['Secret'] if request_secret != os.environ['SECRET']: return ('Unauthorized', 401) If the webhook provider does not support a secret or other authentication mechanism, anyone with the URL of your webhook target will be able to send messages. In this case, your webhook implementation should be safe to expose to the public internet. Responding to requests Most services require you to respond to a request within a set amount of time, as specified by the service. Some webhooks have built-in retry methods if there is an error response, such as an HTTP status code of 4xx or 5xx, so you'll need to return a successful status code (2xx) to let the service know the event was processed properly. def index(): data = request.get_json() return ('', 200) Timeouts Both Cloud Run and the webhooks provider have timeouts. The shorter of the two will apply to your application. If your data processing exceeds the time allotted by either Cloud Run or the webhooks provider, you'll need to use a product that allows you to complete your processing asynchronously, such as Pub/Sub or Cloud Tasks. These products allow you to quickly hand off the data, immediately return a success response to the webhooks provider, and continue the processing without the timeout concern. These are also good options for handling failures and retries. Common webhooks patterns What's next - Learn more about webhooks (HTTP Triggers) on Cloud Functions - Set up webhooks notifications on Google Cloud's operations suite - Send Pub/Sub messages to a webhook using push subscriptions - Fulfill actions on Dialogflow with webhooks
https://cloud.google.com/run/docs/triggering/webhooks?hl=lt&skip_cache=false
CC-MAIN-2021-49
refinedweb
641
60.85
Chat program using Socket Programming In this blog, we are going to create a simple chat app using socket programming. In this, we are going to use UDP protocol to transfer the data from one system to another. Socket Programming Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite. With UDP, computer applications can send messages, in this case, referred to as datagrams, to other hosts on an (IP) network. UDP uses a simple connectionless communication model with a minimum of protocol mechanisms. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. In this program, we will not only use socket programming but also use multithreading for the sender and the receiver to be able to send and receive the messages in real-time. Multi-Threading Multithreading is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. It allows the execution of multiple parts of a program at the same time. These parts are known as threads and are lightweight processes available within the process. So multithreading leads to maximum utilization of the CPU by multitasking. Here, multithreading will help us in creating a real-time chat application. The first step is to import all the necessary modules from the python library. import socket import threading import datetime Here, we are going to use these three modules where socket will help us in creating a UDP link between the two systems, threading will help us in creating multiple threads and datetime module will help us in printing the time. s= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s_ip= "<IP Address>" s_port= <Port number> s.bind((s_ip, s_port)) These lines will help us bind the sender’s IP and port to bind them together. def send(): while 1: msg= input() s.sendto( msg.encode(), (r_ip, r_port)) print('_'*(40) + time()) print("")def receive(): while 1: buffer_size= 1024 msg= s.recvfrom(buffer_size) print('[' +r_ip + ']' + ' ' + msg[0].decode()) print('_'*(40) + time()) print("") These are the two functions we have to write in order to send and receive the data. But, before sending the data we need to encode it. While receiving the data we need to justify the buffer_size (size of the data) beforehand and then decode it before printing. That’s all, our simple chat program is created. GitHub URL for reference Output: Hope you find this blog useful Happy reading!
https://gauravtank2203.medium.com/chat-program-using-socket-programming-b6fb69834586?responsesOpen=true&source=user_profile---------8-------------------------------
CC-MAIN-2022-05
refinedweb
467
55.44
This article shows how a directory and all missing parents of this directory can be created in Python. Use pathlib.Path.mkdir Since Python 3.5 the best and easiest way to create a nested directory is by using pathlib.Path.mkdir: from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True) If parents is true, any missing parents of this path are created as needed (Make sure to have required permissions for this path). If parents is false (the default), a missing parent raises FileNotFoundError. If exist_ok is false (the default), FileExistsError is raised if the target directory already exists. If exist_ok is true, FileExistsError exceptions will be ignored, but only if the last path component is not an existing non-directory file. Use os.path.makedirs For older Python versions os.path.makedirs can be used together with os.path.exists: import os if not os.path.exists(directory): os.makedirs(directory) Be aware that in rare cases a race condition can occur here – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. More information about this can be found here. Use Pathlib to check if a file exists The pathlib module is also very useful to check if a file or a directory exists in Python. You can read more about this in the following short article: How to check if a file or directory exists in Python
https://www.python-engineer.com/posts/create-nested-directory/
CC-MAIN-2022-21
refinedweb
247
59.09
Problem 42 How many triangle words can you make using the list of common English words? Solution: import Data.Char trilist = takeWhile (<300) (scanl1 (+) [1..]) wordscore xs = sum $ map (subtract 64 . ord) xs problem_42 megalist = length [ wordscore a | a <- megalist, elem (wordscore a) trilist ] main = do f <- readFile "words.txt" let words = read $"["++f++"]" print $ problem_42 words [edit] 3 Problem 43 Find the sum of all pandigital numbers with an unusual sub-string divisibility property. Solution: import Data.List l2n :: (Integral a) => [a] -> a l2n = foldl' (\a b -> 10*a+b) 0 swap (a,b) = (b,a) explode :: (Integral a) => a -> [a] explode = unfoldr (\a -> if a==0 then Nothing else Just $ swap $ quotRem a 10) problem_43 = sum . map l2n . map (\s -> head ([0..9] \\ s):s) . filter (elem 0) . genSeq [] $ [17,13,11,7,5,3,2] mults mi ma n = takeWhile (< ma) . dropWhile (<mi) . iterate (+n) $ n sequ xs ys = tail xs == init ys addZ n xs = replicate (n - length xs) 0 ++ xs genSeq [] (x:xs) = genSeq (filter (not . doub) . map (addZ 3 . reverse . explode) $ mults 9 1000 x) xs genSeq ys (x:xs) = genSeq (do m <- mults 9 1000 x let s = addZ 3 . reverse . explode $ m y <- filter (sequ s . take 3) $ filter Problem 44 Find the smallest pair of pentagonal numbers whose sum and difference is pentagonal. Solution: import Data.Set problem_44 = head solutions where solutions = [a-b | a <- penta, b <- takeWhile (<a) penta, isPenta (a-b), isPenta (b+a) ] isPenta = (`member` fromList penta) penta = [(n * (3*n-1)) `div` 2 | n <- [1..5000]] The above solution finds the correct answer but searches the pairs in the wrong order. Lengthier and slower but perhaps more correct solution here. [edit] 5 Problem 45 After 40755, what is the next triangle number that is also pentagonal and hexagonal? Solution: isPent n = (af == 0) && ai `mod` 6 == 5 where (ai, af) = properFraction . sqrt $ 1 + 24 * (fromInteger n) problem_45 = head [x | x <- scanl (+) 1 [5,9..], x > 40755, isPent x] [edit] 6 Problem 46 What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? Solution: This solution is inspired by exercise 3.70 in Structure and Interpretation of Computer Programs, (2nd ed.). millerRabinPrimality on the Prime_numbers page import Data.List isPrime x | x==3 = True | otherwise = millerRabinPrimality x 2 problem_46 = find (\x -> not (isPrime x) && check x) [3,5..] where check x = not . any isPrime . takeWhile (>0) . map (\y -> x - 2 * y * y) $ [1..] Problem 47 Find the first four consecutive integers to have four distinct primes factors. Solution: import Data.List problem_47 = find (all ((==4).snd)) . map (take 4) . tails . zip [1..] . map (length . factors) $ [1..] fstfac x = [(head a ,length a) | a <- group $ primeFactors x] fac [(x,y)] = [x^a | a <- [0..y]] fac (x:xs) = [a*b | a <- fac [x], b <- fac xs] factors x = fac $ fstfac x primes = 2 : filter ((==1) . length . primeFactors) [3,5..] primeFactors n = factor n primes where factor _ [] = [] factor m (p:ps) | p*p > m = [m] | m `mod` p == 0 = [p, m `div` p] | otherwise = factor m ps Problem 50 Which prime, below one-million, can be written as the sum of the most consecutive primes? Solution: (prime and isPrime not included) import Control.Monad findPrimeSum ps | isPrime sumps = Just sumps | otherwise = findPrimeSum (tail ps) `mplus` findPrimeSum (init ps) where sumps = sum ps problem_50 = findPrimeSum $ take 546 pr)
http://www.haskell.org/haskellwiki/index.php?title=Euler_problems/41_to_50&diff=50123&oldid=32567
CC-MAIN-2014-23
refinedweb
568
66.23
Details - Type: Bug - Status: Closed - Priority: Major - Resolution: Not A Problem - Affects Version/s: 1.8.3 - Fix Version/s: None - Component/s: groovy-jdk - Labels:None - Environment:JVM 1.6.0_14 on RHEL4u8 Description I received the following crash from a Groovy script sometimes: Exception in thread "Thread-2" groovy.lang.GroovyRuntimeException: exception while dumping process stream at org.codehaus.groovy.runtime.ProcessGroovyMethods$ByteDumper.run(ProcessGroovyMethods.java:488) at java.lang.Thread.run(Thread.java:619) Caused by: java.io.IOException: Bad file descriptor at java.io.FileInputStream.available(Native Method) at java.io.BufferedInputStream.read(BufferedInputStream.java:325) at java.io.FilterInputStream.read(FilterInputStream.java:90) at org.codehaus.groovy.runtime.ProcessGroovyMethods$ByteDumper.run(ProcessGroovyMethods.java:484) ... 1 more I can't trap the exception from within the script and there's a few nested Groovy scripts but my guess is that it's from the call to Process.destroy(). Below is a snippet from my script which performs that call: def process = ["/tools/bin/reQrsh", "-q", "batch.q,compile.q", "-verbose", "-now", "n", "-cwd", "-V", "-l", "os=redhat4$cbOpt,h_rt=28800", "./$bobExe $bobArgs"].execute() def pipedOutputStream = new PipedOutputStream() process.consumeProcessOutput( new TeeOutputStream(System.out, pipedOutputStream), new TeeOutputStream(System.err, pipedOutputStream)) new PipedInputStream(pipedOutputStream).eachLine \{ (it =~ /<stripped>/).find \{ process.destroy() \} \} System.exit(0) Activity - All - Work Log - History - Activity - Transitions From Apache commons library. It still fails with latest (2.0.0-beta-2 and 1.7.0_03). I guess it's really a JDK bug but one that's exposed with Groovy features. You can add an exception handler to the threads once they're created to ignore it. I can't think of an easy way to prevent it from being thrown - that is, to say that an already blocking read operation should unblock and the read loop should stop. This quick example seems to work: @Grab( 'commons-io:commons-io:2.2' ) import org.apache.commons.io.output.TeeOutputStream as TOS def process = './test.sh'.execute() def pos = new PipedOutputStream() def pis = new PipedInputStream( pos ) def tos = [ new TOS( System.out, pos ), new TOS( System.err, pos ) ] process.consumeProcessOutput( *tos ) pis.eachLine { (it =~ /stop/).find { println "Stopping..." tos*.close() process.destroy() } } Can you try plugging in the process you are trying to run, and see if it works for you too? I think, rather than it being a bug, it's an issue with suddenly unplugging the process from the TeeOutputStream. Fingers crossed closing the streams nicely before calling process.destroy() will stop it happening... Without the tos*.close() line, I get the exception: Caught: java.io.IOException: Pipe broken java.io.IOException: Pipe broken On both OS X Snow Leopard and RedHat Enterprise Linux PS: My test.sh is: #!/bin/bash for i in {1..10} do if [ "$i" == "7" ] then echo "$i stop" else echo "$i continue" fi # Write something to the error stream echo "error stream" 1>&2 sleep 1 done Yup that seems to have done it - thanks for the help! Cool Glad I could help! You might as well delete the StackOverflow question too Good luck! Even though all of the discussion is here, StackOverflow seems to get better rankings on Google. I will mark the question as answered though. Funny comic on topic: Which TeeOutputStream are you using? My guess would be that the condition is being met, so you are calling process.destroy() which is pulling the plug on one of the Streams. Also, does it still fail if you use an up to date version of Groovy and an up to date version of Java 6?
https://issues.apache.org/jira/browse/GROOVY-5406
CC-MAIN-2016-07
refinedweb
599
53.47
I got the first part correct but how do I put the get height into the second part? Like would I just repeat everything the base did.. like "private double height" " public void setHeight " etc... The design is this: RightTriangle variables: base, height methods: setBase - changes the base setHeight - changes the height getBase - returns the base getHeight - returns the height area - returns the rea of the triangle(1/2bh) The output is suppose to be: The base of the right triangle is 4.0 the height of the right triangle is 5.0 The area of the right triable is 10.0 My code so far is: public class RightTriangle { public static void main(String[] args) { Triangle shape = new Triangle(); shape.setBase(4.0); shape.setHeight(5.0); System.out.println("The base of the right triangle is " + shape.getBase()); System.out.println("The height of the right triangle is " + shape.getHeight()); System.out.println("The area of the right triangle is " + shape.area()); } } The class code is: public class Triangle { private double base; public Triangle() { base = 1; } public void setBase(double newBase) { base = newBase; } public double area() { double triangleArea; triangleArea = 1/2 * base * height; return(triangleArea); } public double getBase() { return(base); } }
https://www.daniweb.com/programming/software-development/threads/228438/how-to-add-the-setheight-method
CC-MAIN-2018-43
refinedweb
202
55.44
Learn Deno: A Secure JavaScript & TypeScript Runtime May 2020 saw the release of Deno 1.0, and it’s been a pretty popular topic of conversation. If you’re wondering what the fuss is all about, you’ve come to the right place! In this article, I hope to give you an overview of what Deno is. We’ll take a look at its key features, and ask why you might want to start learning this new tool. What Is Deno? So what is it Deno, and why was it created? It’s a JavaScript and TypeScript runtime, meaning you can write programs in either language and execute them from the command line. Unlike JavaScript run within a browser, Deno programs can access resources on the host computer, such as the filesystem and environment variables. If you’re aware of Node.js, and you’re thinking that Deno sounds pretty similar, you’d be right. Deno is the brainchild of Node’s creator, Ryan Dahl, who created Deno to address what he sees as the design flaws in Node. The aims of the project are to provide a scripting environment that is secure by default, that treats TypeScript as a first-class language, and that is as browser-compatible as possible (where practical). Security Features Deno is designed to be secure out of the box. All code is executed in a secure sandbox by default, which means you need to give explicit permission to allow a program to access the network or the filesystem. Programs can be granted permissions with the following command-line flags: - -A, –allow-all: allow all permissions (disables all security). - –allow-env: allow getting and setting of environment variables. - –allow-hrtime: allow high resolution time measurement (can be used in timing attacks and fingerprinting). - –allow-net=\ : allow network access. Optionally takes a comma-separated whitelist of domains. - –allow-plugin: allow loading plugins (unstable feature). - –allow-read=\ : allow file system read access. Optionally takes a comma-separated whitelist of directories or files. - –allow-run: allow running subprocesses. - –allow-write=\ : allow file system write access. Optionally takes a comma-separated whitelist of directories or files. First-class TypeScript Support As I mentioned earlier, Deno can execute both JavaScript and TypeScript. What’s more, it supports TypeScript as a first-class language. This means it can load and run your TypeScript code without any additional build step. There’s no need to set up additional tooling to transpile your code into JavaScript first. Of course, since TypeScript is a superset of modern JavaScript, you can also write your code in good old JS if you want to! Deno supports some great, developer-friendly features such as ES Module imports Using External Code As Ryan mentioned in his talk, one of his goals for Deno was to avoid the need for a package manager. Unlike with runtimes/languages such as Node.js and PHP (which use the npm and composer package managers respectively), there’s no package manager for Deno. Instead, external packages are imported directly via a URL: import { Client } from ""; The first time you run your script, Deno will fetch, compile, and cache all the imports so that subsequent starts are lightning fast. Obviously there are times when you may want to force it to re-fetch the imports, and you can do this with the cache subcommand: deno cache --reload my_module.ts Package hosting While Deno doesn’t provide a package registry as such, there’s a list of third-party modules available. The service provides a standardized, versioned URL that maps to the module’s GitHub repo. You can search for packages by name and see a brief description, and click through to see the package readme. The Standard Library Deno provides a standard library — loosely based on Golang’s — which provides a set of high-quality standard modules with no external dependencies. The packages in the standard library are not installed along with Deno. Rather, they’re available online and linked to as we saw in the previous section. The modules are versioned, allowing you to pin your code to the usage of a specific version: import { copy } from ""; This means that any code you write that relies on a module from the standard library should continue to work in future versions. The library includes various helpers and utilities you might need for building both command-line and HTTP-based applications: - archive: modules to work with tar files - async: async utilities - bytes: helpers for working with binary arrays - datetime: a helper for parsing date strings into Dateobjects - encoding: encoders for dealing with base32, binary, CSV, TOML, and YAML formats - flags: a command line arguments parser - fmt: a tool for printing formatted output - fs: helpers for working with the filesystem - hash: a module for creating hashes using a variety of algorithms - http: create HTTP and file servers, and manipulate cookies - io: utilities for string input/output - log: simple logging module - mime: provides support for multipart data - node: a (currently in-progress) compatibility layer for Node.js code - path: path manipulation utility - permissions: helpers to check and prompt for security permissions - signal: helpers for handling Deno process signals - testing: test assertions for using with Deno’s built-in test runner - uuid: utilities for generating and validating UUIDs - ws: helpers for creating WebSocket clients and servers Installing Deno Deno ships as a single executable with no dependencies. You can download a binary from the releases page, or install it using the installers below: Shell (macOS, Linux): curl -fsSL | sh PowerShell (Windows): iwr -useb | iex brew install deno Upgrading Once installed, Deno can also upgrade itself to the latest release, using the following command: deno upgrade Or, you can up/downgrade to a specific version: deno upgrade --version 1.0.1 The Future is Bright The Deno manual suggests that it “is a great replacement for utility scripts that may have been historically written with Bash or Python”. While this is certainly true, I would expect to see it increasingly being used for the same use cases where Node.js is currently popular. There are already a number of Express/Koa-like frameworks cropping up, allowing you to build type-safe REST APIs, along with a growing number of third-party modules becoming available. So, should you forget Node.js and start learning Deno? Current opinion in the industry is that Node.js is not about to disappear anytime soon, but Deno is definitely a technology to watch. Deno Foundations Learn Deno with our Deno Foundations collection. You’ll find all of our Deno coverage here as we publish it, organized in a way that helps you most as a beginner. Deno Fundamentals - Deno Guide: A Secure JavaScript & TypeScript Runtime - Node.js vs Deno: What You Need to Know - How to Use Deno’s Built-in Tools - Deno Module System: A Beginner’s Guide - How to Fetch Data from a Third-party API with Deno - Working with the File System in Deno Deno Projects Learn the basics of programming with the web's most popular language - JavaScript
https://www.sitepoint.com/learn-deno/
CC-MAIN-2022-05
refinedweb
1,178
51.99
On 4-Feb-2004, Henry F. Mollet <address@hidden> wrote: | There may be more sophisticated ways to get an Excel Spreadsheet into Octave | on Mac but this works for me and I don't have to explicitly change the | carriage return (\r) of Mac OS into newline (\n) of Unix. I suggest that | this is suitable for medium sized data matrices, which would be cumbersome | to enter in octave at the command line prompt but not that large that a | spreadsheet wouldn't really work either. | | Copy your spreadsheet (I'm using Excel) and paste it into BBEdit Lite 6.1 | for OS X. BBEdit has a Unix save/save as option. Octave will load this file: | | octave:83> load Test&testfile | octave:84> whos | *** local user variables: | prot type rows cols name | ==== ==== ==== ==== ==== | rwd matrix 39 7 Test_testfile | Octave even takes care of the "&" in the filename and renames the matrix but | it cannot handle a space. | | Now the name of the matrix "Test_testfile" can be changed to say | "InputMatrix" (so it will the same as in the script which will use the file) | octave:92> InputMatrix=Test_testfile | | Now the file can be saved with the same name *in octave* | octave:94> save Test&testfile InputMatrix | | BBEdit will even automatically amend the file with | # Created by Octave 2.1.46, Wed Feb 04 18:50:05 2004 PST | <address@hidden> | # name: InputMatrix | # type: matrix | # rows: 39 | # columns: 7 | Henry If all you have is numeric data with no missing values, then Octave's load command should be able to read it if you save it in CSV file. For example, I loaded the following data 1,2,3,4 5,6,7,8 stored in a file called "foo bar" with no problem using the command x = load ("foo bar"); with Octave 2.1.50 (running on a Debian x86 system, but I don't think that detail matters). The file has only CR and no NL characters in it. The result of loading the file is the matrix x = 1 2 3 4 5 6 7 8 Note that this method also handles filenames with spaces and allows you to rename the data to whatever variable name you would like. Does this not work for you on OS X? Can Excel save data in this format, or does it insist on quoting fields in some way, even when you save numeric data in CSV format? jwe ------------------------------------------------------------- Octave is freely available under the terms of the GNU GPL. Octave's home on the web: How to fund new projects: Subscription information: -------------------------------------------------------------
http://lists.gnu.org/archive/html/help-octave/2004-02/msg00033.html
CC-MAIN-2019-22
refinedweb
431
64.54
I huge restructuring of the parser. As a result, some bugs lurk in the changed code. These bugs, because of the arbitrary processing order of the model gems, manifest on some machines and not others. Forcing an ordering on the gem processing masks the underlying issues, even while letting the users of the parser to get on with their lives. What to do? Random testing to the rescue! I cast around for Ruby ports of QuickCheck, and found two: rushcheck and rantly. Rushcheck hasn’t been wrapped up in a gem, so I decided to take rantly for a spin. The basic structure of a rantly test is: my_special_generator }.check { |generator, values| my_special_property(generator, values) } In other words, property_of generates some data, and the results are fed into check, where you describe the property you’re checking. So, for example, a full spec might be def peano(limit = nil) limit = 0..Peano::MAX_INT if limit.nil? Peano.from_i(integer(limit)) end end module Peano describe "Peano" do it "should 0 < n" do property_of { peano(1..100) }.check { |n| Peano.zero.should < n } end end end This example comes from a basic Peano number library I wrote for the purposes of playing with rantly. (I’m really not kidding about “basic”: I’ve intentionally limited the Peano numbers to the range [0, 1000] because I’m lazy. Rantly supports Test::Unit, so you can always just subclass Test::Unit::TestCase and write your test as per normal with assert_equals and friends. Since I like RSpec I had to add a little helper: def property_of(&block) Rantly::Property.new(block) end end rantly supplies a number of basic generators – integers, ranged integers, strings, booleans, chars, etc. – as well as various combinators, and scoped settings. Need an array of between 3 and 5 Peano numbers? No problem: sized(integer(3..5)) { array { peano } } # ... or when you don't need to. array(integer(3..5)) { peano } rantly doesn’t use a polymorphic method for data generation, unlike QuickCheck’s use of typeclasses. It’s hardly difficult, of course, to roll your own such thing: def self.generator Peano.from_i(Rantly.integer(0..Peano::MAX_INT)) end end Most importantly though, a test framework’s only as good as its output. If your assertions don’t result in decent error messages, you might as well not bother. So let’s say we have defined :== and :< for PNumbers. We would obviously also like :>. We write up a property (first!): property_of { PNumber.generator(0..3) }.check {|n| n.succ.should > n } end When we run rake test we see: . failure: 0 tests, on: # F Failures: 1) Peano should succ(n) > n Failure/Error: n.succ.should > n NoMethodError: undefined method `>' for # > # ./test/peano_test.rb:96:in `block (3 levels) in ' # ./test/peano_test.rb:93:in `block (2 levels) in ' We see a decent error message in the final output thanks to RSpec. Just as important – given that this is a test framework using random data – we see a counterexample. Subsequent runs, in this case, would give us different counterexamples. (“In this case” because, since we haven’t defined :> yet, every example is a counterexample!) Let’s play around a bit, and half-implement :>: if peano.to_i.even? then not (self < peano) and not (self == peano) else false end end Our output then looks like this: . failure: 0 tests, on: # >>> F Failures: 1) Peano should succ(n) > n Failure/Error: n.succ.should > n expected: > # >>> got: # >>>> Diff: @@ -1,2 +1,2 @@ -# >>> +# >>>> # ./test/peano_test.rb:96:in `block (3 levels) in ' # ./test/peano_test.rb:93:in `block (2 levels) in ' Or, “gosh darn, :> is broken for odd numbers!” A final note: rantly has some dependencies, but fortunately not that many: rake (naturally), technicalpickles-jeweler, yaml. In summary, rantly is a simple, easy to use random data generator that works nicely with Test::Unit and is easily extended to use RSpec. It comes with basic generators, and it’s easy to extend the generator support to arbitrary structures.
https://tech.labs.oliverwyman.com/blog/2011/11/26/randomly-testing-ruby/
CC-MAIN-2019-26
refinedweb
667
67.86
This is the mail archive of the cygwin mailing list for the Cygwin project. Ryan Johnson wrote:On 05/07/2012 9:36 AM, Claude SIMON wrote.A crash inside malloc is 99.99% likely due to a bug in user code (wild pointer, double-free, smashed stack, etc). The fact that your code doesn't crash under other circumstances does precisely *nothing* to rule out a bug in your code if bad has been observed anywhere (it just proves the platforms really are different). The buggy code may have nothing to do with malloc, other than having the bad luck of clobbering a data structure the latter needs. Even a single mix-up of new/malloc usage (perhaps due to losing track of a pointer's provenance) is also enough.Indeed. The problem is... the crash happens even when there is no other code which could be buggy. #include <stdlib.h> int main() { return (int) malloc(10); }.As asked in another reply to this thread, I've made a test case, which can be found at : There is a README file which contains some further explanations. Great. Please do.Great. Please do. This is all standard memory management debugging stuff that's off topic for this list. If at some point you have some evidence besides "it crashes when I run it under cygwin" *that* would be a topic for this list.With the test case above, I think that it is easy to establish if the problem is off or on topic. Why not? Try it, you might be surprised.Why not? Try it, you might be surprised. My suggestion: run under the debugging malloc library of your choice and/or Valgrind and see what that turns up.Should be interesting to see if a alternative 'malloc' would also crash, but would not solve my problem given what I wrote above. I don't manage to make 'gdb' step into a 'new' call...I don't manage to make 'gdb' step into a 'new' call...As to your question, new() usually calls malloc under the hood (with extra bookkeeping), but five minutes with gdb will give you a definitive answer. b _malloc r It's burned into gcc. That's why I highly doubt cygwin's code is directly causing the problem here.It's burned into gcc. That's why I highly doubt cygwin's code is directly causing the problem here.Beside the crash thing, all I'm interested into, is if someone here can show me the implementation of the 'new' operator as used in Cygwin, or give me an address where I can found the source code of this 'new' implementation, or where I may ask this questions to obtain a response to one of this question. -- Problem reports: FAQ: Documentation: Unsubscribe info:
https://cygwin.com/ml/cygwin/2012-07/msg00189.html
CC-MAIN-2019-43
refinedweb
469
72.05
i set it.....but it's still not giving me a number after i put in a equation, altho i get no error. was there anything else u saw wrong with mine? This is a discussion on C++ Tree Calculator within the C++ Programming forums, part of the General Programming Boards category; i set it.....but it's still not giving me a number after i put in a equation, altho i get no ... i set it.....but it's still not giving me a number after i put in a equation, altho i get no error. was there anything else u saw wrong with mine? ugh this program is driving me up a wall. u said u got it to actually calculate numbers and display the answer correct. but I set type now........and it's not giving errors but it still wont work AGGHGGH here is what i have thus far. i was hoping to get this done by tonight.i was hoping to get this done by tonight.Code://Matt Smith //Cs 215 Section 2 //Program 5 #include "CalcTree.h" CalcTree::CalcTree() { root = NULL; } CalcTree::~CalcTree() { destHelper(root); } CalcTree::CalcTree(CalcTree& otherTree) //copy constructor { root = copyHelper(otherTree.root); } CTNode* CalcTree::copyHelper(CTNode *thatroot) { if(thatroot==NULL) return NULL; CTNode *pwned; pwned = new CTNode; pwned->type = thatroot->type; pwned->operand = thatroot->operand; pwned->left=NULL; pwned->right=NULL; if(( thatroot->left != NULL ) || ( thatroot->right != NULL )) { if( thatroot->left != NULL ) pwned->left = copyHelper(thatroot->left); if( thatroot->right != NULL ) pwned->right = copyHelper(thatroot->right); } return pwned; } void CalcTree::destHelper( CTNode *thisroot ) { if(thisroot==NULL) return; else if(( thisroot->left != NULL ) || ( thisroot->right != NULL )) { if( thisroot->left != NULL ) {destHelper(thisroot->left); thisroot->left=NULL;} if( thisroot->right != NULL ) {destHelper(thisroot->right); thisroot->right=NULL;} } delete thisroot; } void CalcTree::setRoot(NodeType type_, int operand_) { destHelper (root); CTNode *temp = NULL; temp= new CTNode; temp-> type=type_; temp-> operand=operand_; temp->left=NULL; temp->right=NULL; root=temp; delete temp; } void CalcTree::setLeft(CalcTree &otherTree) { // delete the old branch first destHelper(root->left); // copy the new tree as left branch root->left= copyHelper(otherTree.root); } void CalcTree::setRight(CalcTree &otherTree) { // delete the old branch first destHelper(root->right); // copy the new tree as left branch root->right= copyHelper(otherTree.root); } void CalcTree::printIN() { printINhelper(root); } void CalcTree::printINhelper(CTNode* thisroot) { if (thisroot == NULL) return; else if (thisroot->type == OPR) cout << thisroot->operand; else { cout << "( "; printINhelper (thisroot->left); switch (thisroot->type){ case ADD: cout << " + "; break; case SUB: cout << " - "; break; case MUT: cout << " * "; break; case DIV: cout << " / "; break; } printINhelper (thisroot->right); cout << " )"; } } void CalcTree::printPOST( ) { cout << "("; printPOSThelper(root); cout << ")"; } void CalcTree::printPOSThelper(CTNode *thisroot){ if (thisroot->type == OPR) cout << thisroot->operand; else { printPOSThelper (thisroot->left); printPOSThelper (thisroot->right); switch (thisroot->type){ case ADD: cout << " + "; break; case SUB: cout << " - "; break; case MUT: cout << " * "; break; case DIV: cout << " / "; break; } } } float CalcTree::evaluate( ){ return evalHelper(root); } float CalcTree::evalHelper( CTNode *thisroot ){ if (thisroot == NULL) return 0; if (thisroot->type == OPR) return (float (thisroot->operand)); else { switch (thisroot->type){ case ADD: return (float (evalHelper(thisroot->left) + evalHelper(thisroot->right))); case SUB: return (float (evalHelper(thisroot->left)- evalHelper(thisroot->right))); case MUT: return (float (evalHelper(thisroot->left) * evalHelper(thisroot->right))); case DIV:return (float (evalHelper(thisroot->left)/ evalHelper(thisroot->right))); default: return 0; } } } I don't have delete temp; at the bottom of setRoot. OMG IT WORKS NOW, but why?
http://cboard.cprogramming.com/cplusplus-programming/96518-cplusplus-tree-calculator-3.html
CC-MAIN-2016-18
refinedweb
560
62.78
WebReference.com - Excerpt from Inside XSLT, Chapter 2, Part 4 (4/4) Inside XSLT XML Base Support One of the additions to the XSLT 1.1 working draft was support for the W3C XML Base specification. As of this writing, the XML Base specification is in Proposed Recommendation form (dated 20 December 2000), and you can find the current version of this document at. [And as of this posting, the recommendation is dated June 27, 2001 - Ed.] This specification enables you to provide a base URI for XML and XSL documents, just like the HTML <BASE> element. (In fact, the HTML <BASE> element is the reason XBase exists-W3C is committed to giving XML all the power HTML 4.0 linking has, and then build on that.) As you recall, one of the properties of XSL elements is their base URI, and now you can use XML Base to set that URI. However, no XSLT processors that I know of support XML Base yet. You can find full coverage of XML Base in Inside XML. Here's how it works in overview: You can use the xml:base attribute in an XML document to set the document's base URI. The other URIs in the document are then resolved using that value as a base. Note that xml:base uses the xml namespace; the xml namespace is predefined in XML as "". The following example uses XML links (that is, XLinks, as also covered in Inside XML): <?xml version="1.0"?> <MOVIE_REVIEW xmlns: Mr. Blandings Builds His Dream House </MOVIE_REVIEW> Using the value assigned to the xml:base attribute, the URI in this example's xlink:href attribute, "reviews.xml", is resolved to the full URI "". In this way, you can use xml:base to provide a base URI for a document or a specific element. In the XSLT 1.1 working draft, every node has an associated URI called its base URI, which is used for resolving attribute values that represent relative URIs into absolute URIs. Here's how you determine the base URI: - The base URI for a root node is the URI of the document. - The base URI for an element node is the base URI specified by an xml:baseattribute in the element (if one exists), or the base URI of the element's parent element in the document or external entity (if one exists), or the base URI of the document entity or external entity that contains the element. - The base URI for a processing instruction node is the URI that would apply to a URI reference in the content of the processing instruction. According to the XML Base specification, the base URI for a URI reference appearing in the content of a processing instruction is the base URI of the parent element of the processing instruction (if one exists), within the document entity or external entity, or the base URI of the document entity or external entity containing the processing instruction. - The base URI for a text node, a comment node, or an attribute node is the base URI of the parent of the node. - The base URI for a namespace node, however, is implementation-dependent. Setting the base URI of documents and elements can be useful if you have an extensive set of documents to work with. If you reorganize that document set, you need to reset only the base URI as appropriate, not all individual URIs. As I said, however, no XSLT processors that I know of have any support for XML Base yet. Created: October 4, 2001 Revised: October 4, 2001 URL:
http://www.webreference.com/authoring/languages/xml/insidexslt/chap2/4/4.html
CC-MAIN-2014-41
refinedweb
600
60.35
/* maintainence of threads in response to team creation and termination. */ #include "libgomp.h" #include <stdlib.h> #include <string.h> /* This array manages threads spawned from the top level, which will return to the idle loop once the current PARALLEL construct ends. */ static struct gomp_thread **gomp_threads; static unsigned gomp_threads_size; static unsigned gomp_threads_used; /* This attribute contains PTHREAD_CREATE_DETACHED. */ pthread_attr_t gomp_thread_attr; /* This barrier holds and releases threads waiting in gomp_threads. */ static gomp_barrier_t gomp_threads_dock; /* This is the libgomp per-thread data structure. */ #ifdef HAVE_TLS __thread struct gomp_thread gomp_tls_data; #else pthread_key_t gomp_tls_key; #endif /* This structure is used to communicate across pthread_create. */ struct gomp_thread_start_data { struct gomp_team_state ts; void (*fn) (void *); void *fn_data; bool nested; }; /* This function is a pthread_create entry point. This contains the idle loop in which a thread waits to be called up to become part of a team. */ static void * gomp_thread_start (void *xdata) { struct gomp_thread_start_data *data = xdata; struct gomp_thread *thr; void (*local_fn) (void *); void *local_data; #ifdef HAVE_TLS thr = &gomp_tls_data; #else struct gomp_thread local_thr; thr = &local_thr; pthread_setspecific (gomp_tls_key, thr); #endif gomp_sem_init (&thr->release, 0); /* Extract what we need from data. */ local_fn = data->fn; local_data = data->fn_data; thr->ts = data->ts; thr->ts.team->ordered_release[thr->ts.team_id] = &thr->release; if (data->nested) { gomp_barrier_wait (&thr->ts.team->barrier); local_fn (local_data); gomp_barrier_wait (&thr->ts.team->barrier); } else { gomp_threads[thr->ts.team_id] = thr; gomp_barrier_wait (&gomp_threads_dock); do { struct gomp_team *team; local_fn (local_data); /* Clear out the team and function data. This is a debugging signal that we're in fact back in the dock. */ team = thr->ts.team; thr->fn = NULL; thr->data = NULL; thr->ts.team = NULL; thr->ts.work_share = NULL; thr->ts.team_id = 0; thr->ts.work_share_generation = 0; thr->ts.static_trip = 0; gomp_barrier_wait (&team->barrier); gomp_barrier_wait (&gomp_threads_dock); local_fn = thr->fn; local_data = thr->data; } while (local_fn); } return NULL; } /* Create a new team data structure. */ static struct gomp_team * new_team (unsigned nthreads, struct gomp_work_share *work_share) { struct gomp_team *team; size_t size; size = sizeof (*team) + nthreads * sizeof (team->ordered_release[0]); team = gomp_malloc (size); gomp_mutex_init (&team->work_share_lock); team->work_shares = gomp_malloc (4 * sizeof (struct gomp_work_share *)); team->generation_mask = 3; team->oldest_live_gen = work_share == NULL; team->num_live_gen = work_share != NULL; team->work_shares[0] = work_share; team->nthreads = nthreads; gomp_barrier_init (&team->barrier, nthreads); gomp_sem_init (&team->master_release, 0); team->ordered_release[0] = &team->master_release; return team; } /* Free a team data structure. */ static void free_team (struct gomp_team *team) { free (team->work_shares); gomp_mutex_destroy (&team->work_share_lock); gomp_barrier_destroy (&team->barrier); gomp_sem_destroy (&team->master_release); free (team); } /* Launch a team. */ void gomp_team_start (void (*fn) (void *), void *data, unsigned nthreads, struct gomp_work_share *work_share) { struct gomp_thread_start_data *start_data; struct gomp_thread *thr, *nthr; struct gomp_team *team; bool nested; unsigned i, n, old_threads_used = 0; thr = gomp_thread (); nested = thr->ts.team != NULL; team = new_team (nthreads, work_share); /* Always save the previous state, even if this isn't a nested team. In particular, we should save any work share state from an outer orphaned work share construct. */ team->prev_ts = thr->ts; thr->ts.team = team; thr->ts.work_share = work_share; thr->ts.team_id = 0; thr->ts.work_share_generation = 0; thr->ts.static_trip = 0; if (nthreads == 1) return; i = 1; /* We only allow the reuse of idle threads for non-nested PARALLEL regions. This appears to be implied by the semantics of threadprivate variables, but perhaps that's reading too much into things. Certainly it does prevent any locking problems, since only the initial program thread will modify gomp_threads. */ if (!nested) { old_threads_used = gomp_threads_used; if (nthreads <= old_threads_used) n = nthreads; else if (old_threads_used == 0) { n = 0; gomp_barrier_init (&gomp_threads_dock, nthreads); } else { n = old_threads_used; /* Increase the barrier threshold to make sure all new threads arrive before the team is released. */ gomp_barrier_reinit (&gomp_threads_dock, nthreads); } /* Not true yet, but soon will be. We're going to release all threads from the dock, and those that aren't part of the team will exit. */ gomp_threads_used = nthreads; /* Release existing idle threads. */ for (; i < n; ++i) { nthr = gomp_threads[i]; nthr->ts.team = team; nthr->ts.work_share = work_share; nthr->ts.team_id = i; nthr->ts.work_share_generation = 0; nthr->ts.static_trip = 0; nthr->fn = fn; nthr->data = data; team->ordered_release[i] = &nthr->release; } if (i == nthreads) goto do_release; /* If necessary, expand the size of the gomp_threads array. It is expected that changes in the number of threads is rare, thus we make no effort to expand gomp_threads_size geometrically. */ if (nthreads >= gomp_threads_size) { gomp_threads_size = nthreads + 1; gomp_threads = gomp_realloc (gomp_threads, gomp_threads_size * sizeof (struct gomp_thread_data *)); } } start_data = gomp_alloca (sizeof (struct gomp_thread_start_data) * (nthreads-i)); /* Launch new threads. */ for (; i < nthreads; ++i, ++start_data) { pthread_t pt; int err; start_data->ts.team = team; start_data->ts.work_share = work_share; start_data->ts.team_id = i; start_data->ts.work_share_generation = 0; start_data->ts.static_trip = 0; start_data->fn = fn; start_data->fn_data = data; start_data->nested = nested; err = pthread_create (&pt, &gomp_thread_attr, gomp_thread_start, start_data); if (err != 0) gomp_fatal ("Thread creation failed: %s", strerror (err)); } do_release: gomp_barrier_wait (nested ? &team->barrier : &gomp_threads_dock); /* Decrease the barrier threshold to match the number of threads that should arrive back at the end of this team. The extra threads should be exiting. Note that we arrange for this test to never be true for nested teams. */ if (nthreads < old_threads_used) gomp_barrier_reinit (&gomp_threads_dock, nthreads); } /* Terminate the current team. This is only to be called by the master thread. We assume that we must wait for the other threads. */ void gomp_team_end (void) { struct gomp_thread *thr = gomp_thread (); struct gomp_team *team = thr->ts.team; gomp_barrier_wait (&team->barrier); thr->ts = team->prev_ts; free_team (team); } /* Constructors for this file. */ static void __attribute__((constructor)) initialize_team (void) { struct gomp_thread *thr; #ifndef HAVE_TLS static struct gomp_thread initial_thread_tls_data; pthread_key_create (&gomp_tls_key, NULL); pthread_setspecific (gomp_tls_key, &initial_thread_tls_data); #endif #ifdef HAVE_TLS thr = &gomp_tls_data; #else thr = &initial_thread_tls_data; #endif gomp_sem_init (&thr->release, 0); }
http://opensource.apple.com/source/llvmgcc42/llvmgcc42-2118/libgomp/team.c
CC-MAIN-2014-52
refinedweb
899
50.84
dear support team: I’m trying to find a way to sign a PDF document which is built in adobe livecycle(the file save as “adobe dynamic xml form”),i found the sample code can’t sign the dynamic xml form ,but the code works good if the pdf is a static form! sample code: //“input.pdf” is a dynamic xml form PdfFileSignature pdfSign = new PdfFileSignature(@“input.pdf”, @“sign_output2.pdf”); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); PKCS1 signature = new PKCS1(@“test.pfx”, “mypassword”); pdfSign.Sign(1, “Signature Reason”, “Contact”, “Location”, true, rect, signature); pdfSign.Save(); pdfSign.Close(); i wonder the aspose.pdf(ver 7.4) don’t suport sign the dynamic xml form ? can you help me? in the end,i am sorry my english is poor,i hope you would understand what’s my opinion! dear support team: waiting for help! Hi Wang,<?xml:namespace prefix = o Thank you for the details. I am afraid; signing dynamic XML forms is not supported at the moment using Aspose.Pdf for .NET. I have added a new feature request as PDFNEWNET-34530 in our issue tracking system. Our development team will further analyze and see if it can be supported in future. We will notify you via this forum thread regarding any updates. Sorry for the inconvenience,
https://forum.aspose.com/t/how-to-sign-a-dynamic-xml-form-document/90239
CC-MAIN-2020-45
refinedweb
222
60.61
This post has been updated to reflect changes in the availability of the Wavefront data source plugin for Grafana Cloud users. Greetings! This is Eldin reporting from the Solutions Engineering team at Grafana Labs. In previous posts, you might have read about announcing ObservabilityCON or a quick peek inside the recent updates to the ServiceNow plugin. In this week’s post, I am introducing Mike, who will be covering our Wavefront plugin. – Eldin Hello! Mike J. from Solutions Engineering – one of the newer team members at Grafana Labs. I’m here to showcase another one of our latest favorite Enterprise plugins: Wavefront! Why Wavefront is special In early 2020, the Wavefront team was merged into the newly formed “Tanzu” portfolio under VMware’s Modern Applications business unit. Though it’s formally named “VMware Tanzu Observability by Wavefront,” most people still know the product simply as Wavefront, the high-scale, high query-speed metrics observability SaaS with best-in-class histogram support, best-in-class query language, and ease-of-use features for consuming distributed tracing data from Spring Boot applications. For organizations needing scale and speed, it’s really good at what it does. And now that it is a part of the Tanzu portfolio, it integrates with TMC, or Tanzu Mission Control, to manage your Kubernetes clusters. So all in all, very cool tech. With Grafana’s Wavefront plugin, you can leverage everything you love about Wavefront while still centrally visualizing your other data sources side-by-side. The outcome? That flexible, single-pane view of the underlying metrics that measure the health of your systems and applications to quickly correlate and debug for reduced MTTR. Out-of-the-box Kubernetes dashboards With the release, there are out-of-the-box Kubernetes dashboards. Keep in mind these dashboards are designed to support the Wavefront/Telegraf agent and not Prometheus or other methods of Kubernetes instrumentation (more about that in the “mixed estate” use case below). Below is a quick view of what my Kubernetes-based Wavefront data looks like in Grafana for my personal minikube Kubernetes cluster. First, a summary of the clusters, nodes, pods and containers: Drilling over to “Nodes,” I get node averages for a cluster as well as per-node metrics over time: Drilling down to “Pods,” I see more of the same: averages across the pods, and then individual pod details. Finally, I drill down to the containers and see container-based metrics (uptime per container has been clipped to save some space here). Wavefront usage dashboards Also included with the plugin are some usage dashboards. The first one shows scan rates, ingest, and proxy metrics. Ingest covers metrics, histograms, and distributed tracing. The second dashboard tracks specific ingest by type, source, account, and perhaps most importantly, policy. You’ll find it helpful if you have that one certain team that loves to run “hog wild” and wants to observe everything that emits metrics within their fiefdom. Use case: Mixed estate For those Wavefront+Grafana customers who love both: Perhaps Wavefront is not covering your entire estate, but you would still like a unified view. Then this use case is for you. Below, I show a “mixed estate” view of both Wavefront and open source Prometheus. In this view, I show the same Kubernetes cluster (since I only have one), but let’s say the data is coming from two different clusters. In the dashboard on the right, I have three different CPU graphs for our containers: one from a Wavefront data source, one from a Prometheus data source, and one that combines the two on the same time series graph. While data collection capture rates are different between the two out-of-the-box, you can see the values track each other very closely. Next is a picture of how to configure two different formulas from two different data sources: First, choose “–Mixed–” in your Query dropdown. Then, we have a Wavefront formula in query A using the Query Builder; and a Prometheus formula in query B. Finally, here is a picture where we show our containers’ memory working set from both data sources. Since the data returns with identical values, I am collecting data for namespace kube-system with Wavefront and namespace production with Prometheus. Getting started It is easy to get started. Once you’ve installed the Wavefront plugin into Grafana, configure Wavefront as a data source by going to Configuration > Data Sources > Add data source. Add your authentication details, and the data source is ready to query! Much like Wavefront itself, Grafana’s query editor supports two modes: Raw Queries and a point-and-click Query Builder. If you are not familiar with Wavefront, the Query Builder is definitely the way to go. If you are a Wavefront veteran, raw mode queries will make you feel right at home as they provide the same syntax to which you are accustomed. Dashboard variables Template variable setup with the Wavefront plugin is super powerful. Using variables enables a dynamic navigation experience for your end users. The Wavefront plugin supports a number of different types of variables, including metrics, data sources, sourceTags, matching sourceTags, tagNames, and tagValues. In the Kubernetes dashboards, variable type tagValues is used to allow the user to choose a combination of cluster, node, namespace, and pod, depending upon the specific Kubernetes dashboard. To set up a dashboard variable, the process is simple as well. The syntax used for tagValue is tagValues(<your_tag_name>): ts("<your_timeseries_of_interest>"). In the Kubernetes example for adding a nodename as a variable the syntax would be: tagValues(nodename): ts("kubernetes.pod.filesystem.usage"). Some quick tips - Click on the Permissions tab to enable data source permissions, an Enterprise feature that allows you to control who can see and query your specific Wavefront data sources. - If you need some help with remembering the names and branches of your metrics when forming a Wavefront query, use the plugin’s autocomplete support. - Definitely take advantage of the plugin’s support for annotations. Annotations are alert overlays on a time series graph. Annotations are displayed in a pop-up window, showing the alert name and a direct link to the alert in Wavefront. The Wavefront Enterprise plugin is available for users with a Grafana Cloud account or with a Grafana Enterprise license. For more information and to get started, check out the Wavefront solutions page or contact our team..
https://grafana.com/blog/2020/10/05/the-new-wavefront-enterprise-plugin-brings-the-high-scale-high-speed-saas-to-your-grafana-dashboards/
CC-MAIN-2022-27
refinedweb
1,068
60.45
Calling .NET Assembly from JavaScript... Discussion in 'ASP .Net Building Controls' started by arc,: Calling .NET Assembly from JavaScript...Steve C. Orr, MCSD, Jul 22, 2003, in forum: ASP .Net - Replies: - 0 - Views: - 2,393 - Steve C. Orr, MCSD - Jul 22, 2003 Re: Calling .NET Assembly from JavaScript...Ken Dopierala Jr., Jul 22, 2003, in forum: ASP .Net - Replies: - 0 - Views: - 621 - Ken Dopierala Jr. - Jul 22, 2003 ASP.NET 2.0: What is the namespace and assembly name of generated assemblySA, Aug 9, 2004, in forum: ASP .Net - Replies: - 0 - Views: - 582 - SA - Aug 9, 2004 Problem calling assembly which references another assembly from an asp page, Mar 3, 2006, in forum: ASP .Net - Replies: - 3 - Views: - 1,978 reference .NET assembly in JAVA assembly, Jan 24, 2007, in forum: Java - Replies: - 5 - Views: - 788 - Vitaly - Jan 28, 2007
http://www.thecodingforums.com/threads/calling-net-assembly-from-javascript.755583/
CC-MAIN-2015-35
refinedweb
140
79.87
Build Tools Software Showing page 1 of 1. WhiteSnake Editor WhiteSnake is professional script editor for many script languages myApps xApps,an enterprise universal platform(BPM),facilitates non IT user to build IT solution flexibly by form desinger,workflow designer & report builder etc.(We moved this prject to a new place.1 weekly downloads SAP RFC/BAPI Proxy Builder "SAP RFC Proxy Builder" is the easy way to generate the C# Proxy classes of SAP RFC/BAPI functions. Last Update, Please visit: weekly downloads TFS Extra Build A set of libraries and tools to enhance the build process for Team Foundation Server Freeform II Freeform II is a visual GUI editor for Liberty BASIC0 weekly downloads PHP++ PHP++ is a new programming language with a syntax similar to PHP, but it's completly rewritten in C++ and comes with a lot of new features like namespaces and a own, easy extendable object oriented framework fxtool The Open Source part of the product fxtool. Over time, more functions will move over to being Open Source plug-ins or modules. Visit the site for more information
http://sourceforge.net/directory/development/build/natlanguage:english/os:mswin_server2003/
CC-MAIN-2015-06
refinedweb
184
54.66
This guide extends on code examples found in the Output Management guide. Progressive Web Applications (or PWAs) are web apps that deliver an experience similar to native applications. There are many things that can contribute to that. Of these, the most significant is the ability for an app to be able to function when offline. This is achieved through the use of a web technology called Service Workers. This section will focus on adding an offline experience to our app. We'll achieve this using a Google project called Workbox which provides tools that help make offline support for web apps easier to setup. So far, we've been viewing the output by going directly to the local file system. Typically though, a real user accesses a web app over a network; their browser talking to a server which will serve up the required assets (e.g. .html, .js, and .css files). So let's test what the current experience is like using a simple server. Let's use the http-server package: npm install http-server --save-dev. We'll also amend the scripts section of our package.json to add in a start script: package.json { ... "scripts": { - "build": "webpack" + "build": "webpack", + "start": "http-server dist" }, ... } If you haven't previously done so, run the command npm run build to build your project. Then run the command npm start. This should produce the following output: > http-server dist Starting up http-server, serving dist Available on: Hit CTRL-C to stop the server If you open your browser to (i.e.) you should see your webpack application being served up from the dist directory. If you stop the server and refresh, the webpack application is no longer available. This is what we aim to change. Once we reach the end of this module we should be able to stop the server, hit refresh and still see our application. Let's add the Workbox webpack plugin and adjust the webpack.config.js file: npm install workbox-webpack-plugin --save-dev webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); + const WorkboxPlugin = require('workbox-webpack-plugin'); module.exports = { entry: { app: './src/index.js', print: './src/print.js' }, plugins: [ new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ - title: 'Output Management' + title: 'Progressive Web Application' - }) + }), + new WorkboxPlugin.GenerateSW({ + // these options encourage the ServiceWorkers to get in there fast + // and not allow any straggling "old" SWs to hang around + clientsClaim: true, + skipWaiting: true + }) ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } }; With that in place, let's see what happens when we do an npm run build: ... Asset Size Chunks Chunk Names app.bundle.js 545 kB 0, 1 [emitted] [big] app print.bundle.js 2.74 kB 1 [emitted] print index.html 254 bytes [emitted] precache-manifest.b5ca1c555e832d6fbf9462efd29d27eb.js 268 bytes [emitted] service-worker.js 1 kB [emitted] ... As you can see, we now have 2 extra files being generated; service-worker.js and the more verbose precache-manifest.b5ca1c555e832d6fbf9462efd29d27eb.js. service-worker.js is the Service Worker file and precache-manifest.b5ca1c555e832d6fbf9462efd29d27eb.js is a file that service-worker.js requires so it can run. Your own generated files will likely be different; but you should have an service-worker.js file there. So we're now at the happy point of having produced a Service Worker. What's next? Let's allow our Service Worker to come out and play by registering it. We'll do that by adding the registration code below: index.js import _ from 'lodash'; import printMe from './print.js'; + if ('serviceWorker' in navigator) { + window.addEventListener('load', () => { + navigator.serviceWorker.register('/service-worker.js').then(registration => { + console.log('SW registered: ', registration); + }).catch(registrationError => { + console.log('SW registration failed: ', registrationError); + }); + }); + } Once more npm run build to build a version of the app including the registration code. Then serve it with npm start. Navigate to and take a look at the console. Somewhere in there you should see: SW registered Now to test it. Stop your server and refresh your page. If your browser supports Service Workers then you should still be looking at your application. However, it has been served up by your Service Worker and not by the server. You have built an offline app using the Workbox project. You've started the journey of turning your web app into a PWA. You may now want to think about taking things further. A good resource to help you with that can be found here.
https://webpack.js.org/guides/progressive-web-application/
CC-MAIN-2018-43
refinedweb
755
60.11
Using Virtualenv and PasteScript [ID:785] (1/3) in series: Agile Development Tools in Python video tutorial by percious, added 07/08 Our authors tell us that feedback from you is a big motivator. Please take a few moments to let them know what you think of their work. Here I go through how to create a virtual environment, and create a package for development. Got any questions? Get answers in the ShowMeDo Learners Google Group. Video statistics: - Video's rank shown in the most popular listing - Video plays: 4922 (since July 30th) - Plays in last week:<< Brilliant! Clear and to the point. Good work. Here's a formula i learned in Toastmasters: 1. Tell me what you're going to tell me 2. Tell me 3. Tell me what you told me. This helps when people's minds are wandering in and out. :-) Thanks for the video. Very nice video, thank you. It was very helpful for me. Thanks! The only detail that you might have included is the explanation of the behind the scenes fact that when you created the package (I think), it registered it with site-packages, which is why the import step that you demo then works. But I could see that in the output when I went back to look for it. With your demo I have saved some much time understanding the utility of those two tools. Thank you alot ! Found the video great - many thanks! Thank you for this video, it has helped me to learn about this two great tools. Regards, Jose Great tutorial, thanks! Great tutorial! Thanks for the clear, concise demo! Great tutorial! Nice demo! Thank you to percious Thanx! It was my first lesson with python :) BR, Arthur Great! Very helpful, thanks a lot. Here was a transcript of what I typed to get the same results on a Windows D: drive (Scripts replaces bin and pongg replaces myproject): d:\curl\curl | python d:\python25\lib\scripts\easy_install virtualenv .\Scripts\virtualenv.exe pongg --no-site-packages .\Scripts\activate.bat .\Scripts\easy_install.exe pastescript paster create pongg cd pongg paster help python setup.py develop python import pongg dir(pongg) good pace Very helpful, giving answers to immediate questions I had. thanks. (Love to see source control implemented as well) steamlined genesis and distribution facilities too in python: coool! Great, crisp, succinct delivery. I came across this link to your demo while trying to find info on how to use virtualenv to enable the use of more than one python version on a system. ie. Current Ubuntu and Fedora systems come with python 2.6.xx . But I want to experiment with Zope (Zope 3) which seems to like python 2.5 better. As a very new programmer, I am realizing I am probably jacking up libraries that Fedora needs to function properly by installing every web application framework out there willy-nilly. Probably why my former Ubuntu install got so ginchy. Would you consider demoing the proper way for a new programmer like me to set up a sandbox with virtualenv - and perhaps even how best to tear it back down once one is finished playing with a library/alternative python version. (another example being creating a sandbox to play around with Python 3.) Once again - Thanks for sharing your skill! Eric Very useful, since the online doc on paster is rather complicated and I found it difficult to understand how paster can be used the simple way. Any in-depth discussion on packaging , paster ,etc would be of much interest. Thanks Great tutorials. Thank you very much! Really nice effort! I am new to Sphinx and I was glad you outlined each step perfectly well although the fonts and Windows were little small since I have MacBoook 13.3 inch. Kudos for helping fellow geeks. Wow ... really helpful tips! Thanks for the video. I think I needed to understand more about egg packaging before I watched this. Very nice. Thanks percious. I thought I'd know everything but you have some good ideas there. This was helpful. I have heard about virtualenv and paster but had never actually used them. This was a nice intro. Thank you. I was helpful. Great video. Interesting topic. That was what i was looking for. Thx Lukas Thanks! Nice intro to pastescript. I hadn't realised what it did. Very useful to know.
http://showmedo.com/videotutorials/video?name=2910000
CC-MAIN-2015-11
refinedweb
732
76.52
1. Which two methods of name resolution are available on a Microsoft Windows Server 2003 network? a. WINS b. TCP/IP c. DNS d. DHCP 2. Host name resolution on a Microsoft Windows Server 2003 network uses DNS to map which two items to one another? a. Host name to IP address b. FQDN to MAC address c. Host name to MAC address d. FQDN to IP address 3. Which are four key benefits of using DNS for name resolution? a. Scalability b. Constancy c. Fault tolerance d. Ease of use e. Simplicity 4. Internet namespace has a hierarchical structure with the root domain located at the top of the structure. What is used to represent the root domain? a. .com b. .edu c. .net d. dot (.) 5. True or false: When you install Microsoft Windows Server 2003, DNS is installed automatically? 6. There are two types of DNS zones. One type is used to look up FQDNs, and the other is used to look up IP addresses. What are the two types of zones? a. Forward lookup zones b. Reverse lookup zones c. Standard lookup zones d. Secondary lookup zones 7. What are the four types of standard DNS zones? a. Standard primary b. Stub c. Standard secondary d. Active Directory–integrated e. in-addr.arpa 8. A host must communicate with a server on the same network. The host has the IP address of the server. What process will DNS use to obtain the name of the server? a. Standard lookup b. Forward lookup c. Reverse lookup d. Inverse lookup 9. Your Microsoft Windows Server 2003 network is running DNS. The network has a DNS server with a standard primary zone and two DNS servers hosting standard secondary zones. You must make a manual entry in the DNS database, and you would like this entry to replicate to all other DNS servers on the network. You must make the entry on which DNS server? a. You can make the entry on any of the DNS servers. b. You can make the entry on one of the servers that hosts a standard secondary DNS zone. c. You can make the entry on only the server that hosts the primary DNS zone. d. The update must be made on both secondary servers. 10. You are the administrator of a Microsoft Windows Server 2003 domain. Your domain has three DNS servers, which are located on domain controllers. Currently, you can create updates on only one of the DNS servers. You would like to be able to make changes to the DNS database on any of the three DNS servers, and you want these changes to replicate to all other DNS servers in your domain. You should make which configuration change? a. Convert all DNS servers to primary DNS servers. b. Convert all DNS server zones to Active Directory–integrated zones. c. This cannot be accomplished. d. Create forwarding entries on the DNS servers with secondary zone files. 11. Microsoft Windows Server 2003 has three options for Active Directory–integrated zone replication. Which of the following is not available as a replication option in Windows Server 2003? a. Replicate to all DNS servers in the forest. b. Replicate to all domain controllers in the domain. c. Replicate to all domain controllers that are DNS servers in the same domain. d. Replicate to all domain controllers that are also DNS servers in the entire forest. 12. You are the administrator at Lucerne Publishing. You administer the books.lucernepublishing.com Microsoft Windows Server 2003 Active Directory domain. Active Directory–integrated DNS is configured on all domain controllers in the domain. You configure a member server, ServerA, to host an internal Web site for the intranet. You want employees to access this Web site using the URL books.internal.lucernepublishing.com. What should you do? a. Create a CNAME resource record called books, and specify internal.lucernepublishing.com as the target host. b. Create a new zone called internal.lucernepublishing.com. Create a CNAME resource record called books in that new zone, and specify ServerA.books.lucernepublishing.com as the target host. c. Create a CNAME resource record called books.internal, and specify ServerA.books.lucernepublishing.com as the target host. d. Create a CNAME resource record called internal, and specify ServerA.books.lucernepublishing.com as the target host. 13. When a client queries a DNS server and requests the best answer that the DNS server can provide using only its own database, which type of query has been performed? a. Recursive b. Standard c. Iterative d. Secondary 14. To perform a recursive query, the DNS server must have the location of the root level DNS servers. By default, Microsoft Windows Server 2003 stores the root hints in which file? a. Root.dns b. Roothints.dns c. Forwarders.dns d. Cache.dns 15. When a DNS server that is configured to perform recursive queries cannot resolve a name or is not authoritative for the namespace, it must contact a higher-level DNS server. What will the DNS server use to locate DNS servers that are higher in the DNS hierarchy? a. Root hints b. WINS c. SMTP d. Recursion 16. What are the four DNS server types? a. Primary name server b. Master name server c. Caching-only name server d. Replicating name server e. Secondary name server 17. Which type of DNS server does not contain a copy of a zone file but is capable of responding to client queries? a. Primary name server b. Secondary name server c. Master name server d. Caching-only name server 18. Which type of DNS server contains a copy of the zone file and can respond to client queries but cannot be directly updated? a. Primary name server b. Secondary name server c. Master name server d. Caching-only name server 19. Your company uses a Microsoft Windows Server 2003 network that runs DNS. You would like to improve name resolution, but you do not want to increase replication traffic. What can you do to accomplish this? a. Add an additional primary name server b. Add an additional secondary name server c. Add a caching-only name server d. Add a WINS server 20. While viewing your DNS database, you see the following resource record: na.contoso.com. IN NS nadcl.na.contoso.com. What is the purpose of this resource record? a. To identify a name server b. To identify an Internet server c. To identify an individual host d. To identify an entire domain 21. For communication to exist on a TCP/IP network using DNS, each host must be identified by a resource record in the DNS database. Which type of DNS resource record is used to identify individual hosts? a. PTR records b. A records c. NS records d. SOA records 22. You must configure DNS to hide detailed information about your network but to still provide name resolution and access to your resources. What step can you take to accomplish this? a. Disable DNS and use WINS. b. Delete the DNS database and create a host file on all domain controllers. c. Use CNAME records in DNS to hide the identity of resources. d. DNS cannot hide the identity of network resources. 23. A ______________ record is the A record in the parent zone for an authoritative DNS server hosting the child zone for the delegated subdomain. a. Glue b. PTR c. SOA d. Host 24. True or false: Host computers typically use iterative queries? 25. A DNS query can result in four possible response types. Which four of the following are valid query response options? a. Negative answer b. Referral answer c. False answer d. Authoritative answer e. Positive answer CHAPTER 4 1. Which DNS management tools can be used to examine the contents of DNS zone information to verify existing and proper configuration of resource records? a. DNSLint b. Ipconfig c. WINS d. Nslookup 2. Which DNS tool can be used from the command line to perform most DNS management functions? a. DNScmd b. Nslookup c. DNSLint d. Ipconfig 3. Which two types of queries can a client request a DNS server to perform? a. One-way b. Recursive c. Cumulative d. Iterative 4. You are the administrator for a Microsoft Windows 2003 network. Users complain that they can access local resources but have difficulty accessing Internet resources. Which type of test should you run from the DNS console to troubleshoot this problem? a. Recursive query to another DNS server b. Iterative query to a local DNS server c. Forward lookup query to the WINS server d. Ping your local DNS server 5. One of your Microsoft Windows XP clients issues an unsuccessful query for a remote domain. You suspect that the Cache.dns file that contains the root hints for your DNS server might contain inaccurate entries. What could you do to test and verify that your DNS server is configured with the correct root hints? a. Issue an iterative query to your local DNS server. b. Open the folder named Root Hints and verify each IP address. c. Issue a recursive query to another DNS server. d. Query your WINS server for the address of the root server. 6. Which DNS management tool can be used to verify the consistency of a particular group of DNS resource records on multiple DNS servers? a. DNSLint b. Dnscmd c. Nslookup d. Ipconfig 7. Which two statements are true regarding DNS and WINS name resolution? a. WINS is used to resolve host names to IP addresses. b. DNS is used to resolve NetBIOS names to IP addresses. c. DNS is used to resolve host names to IP addresses. d. WINS is used to resolve NetBIOS names to IP addresses. 8. You are the network administrator for contoso.com, which uses the default settings for clients running Microsoft Windows XP and Microsoft Windows NT 4. Your Windows XP clients are configured to use DNS for name resolution, and your Windows NT 4 clients are configured to register with a WINS server. Your Windows XP clients cannot communicate with the Windows NT 4 clients by NetBIOS name. What could you do so that your Windows XP clients can communicate with the Windows NT 4 clients by NetBIOS name? a. Configure your WINS server to forward name queries to the DNS server for name resolution. b. Configure a HOSTS file on the WINS server with the NetBIOS names to IP address mapping for each Windows NT 4 client. c. Install a secondary DNS server for the Windows NT 4 clients. d. Configure your DNS server to forward name queries to the WINS server for name resolution. 9. Which command would you enter at the command prompt to display the contents of the DNS resolver cache? a. Ipconfig /all b. Ipconfig /dns c. Ipconfig /displaydns d. Ipconfig /show 10. Replication Monitor is a tool that monitors Active Directory replication. Which command is issued at the command prompt to start the Replication Monitor? a. Replmon b. Start c. Repl d. Replication Monitor cannot be started from the command prompt. 11. Which command can be issued at the command prompt to purge the DNS resolver cache? a. Ipconfig /clearcache b. Ipconfig /deletecache c. Ipconfig /flushdns d. Ipconfig /flushcache 12. Which of the following is not a DNS management tool? a. Nslookup b. Dnscmd c. DNSLint d. DNSmgt 13. You are an assistant network administrator and have been asked to perform a manual test on your main DNS server. Which two types of tests can you perform? a. Resolver query b. Iterative query c. Complete query d. Recursive query 14. As a system administrator, you perform a manual test on your DNS server. The results indicate that the iterative query was successful, but the recursive query failed. Which of the following is most likely the problem? a. Invalid root hints. b. The DNS server service is stopped. c. All root hints are valid. d. DNS monitoring is disabled. 15. You are a network administrator and you have been asked to determine the FQDN associated with 207.1.1.19. Which command will provide the requested information? a. Nslookup FQDN 207.1.1.19. b. Nslookup domain. c. Nslookup 207.1.1.19. d. Nslookup cannot perform this function. 16. You are a network administrator of a Microsoft Windows Server 2003 network. Your primary DNS server runs on a Windows Server 2003 server named DNS1. To allow fault tolerance, you have a secondary DNS server that runs on a UNIX server named DNS2. To perform maintenance, you take the primary DNS server offline. While the primary DNS server is offline, users complain that they cannot access resources on your network. What should you do to correct this problem? a. Enable round robin on DNS1. b. Enable netmask ordering on DNS2. c. Select the BIND Secondaries option on the DNS Advanced Server Properties page on DNS1. d. Select the BIND Secondaries option on the DNS Advanced Server Properties page on DNS2. 17. You are the network administrator for Wingtip Toys. Your internal DNS server runs on a Microsoft Windows Server 2003 server. Your company maintains three Web servers that handle catalog sales. All three Web servers maintain identical content and respond to the host name. You would like to ensure that load balancing occurs among the three Web servers. Which action should you take to accomplish this? a. Enable round robin on the three Web servers. b. Enable round robin on the Advanced DNS Server Properties page of the DNS server. c. Configure each of the three Web servers with unique host names. d. Windows Server 2003 does not contain a load-balancing feature. 18. Your network consists of only Microsoft Windows Server 2003 servers and Microsoft Windows XP clients. To provide fault tolerance, your network has a primary DNS server and a secondary DNS server, both of which use default configurations. While loading a zone file, your primary DNS server detects errors in the file. The DNS server will take which action? a. The zone file will be loaded, but the DNS Server service will not start. b. The zone file will be loaded. The errors will be logged and ignored. c. The zone file will not be loaded. The DNS server will answer queries using cached information only. d. The DNS server will not load the zone file, but will continue to attempt to load the file at five-minute intervals. 19. Your network consists of only Microsoft Windows Server 2003 servers and Microsoft Windows XP clients. To provide fault tolerance, your network has a primary DNS server and a secondary DNS server, both of which use default configurations. Which action can you take to prevent your DNS server from loading a zone file that contains errors? a. On the Advanced DNS Server Properties page, select the Fail To Load If Bad Zone Data option. b. No action is required. The DNS server will not, by default, load a file containing errors. c. Install all DNS servers as secondary DNS servers. d. On the Advanced DNS Server Properties page, select the Do Not Load Zone File With Errors option. 20. When clients query your DNS server, instead of receiving a definitive answer, they receive referrals to other DNS servers. You would like your DNS server to return a definitive answer to client queries. Which action should you take to accomplish this? a. This cannot be accomplished; DNS servers always return referrals to other DNS servers to clients. b. Update the Cache.dns file. c. Select the option to disable iterative queries on the Advanced DNS Server Properties page. d. Clear the Disable Recursion option on the Advanced DNS Server Properties page. 21. A DNS server running on a Microsoft Windows Server 2003 network is, by default, configured to load zone data on startup from which locations? a. File and registry b. Disk and registry c. Active Directory directory service and registry d. Registry only 22. A DNS server running on a Microsoft Windows Server 2003 network is, by default, configured to load zone data on startup from the Active Directory directory service and the registry. Which two additional options are available for this setting? a. File b. Disk c. Secondary DNS Server d. Registry 23. Your Microsoft Windows Server 2003 network has Microsoft Windows 2000 Professional and Microsoft Windows XP Professional clients. Your DNS server is configured to allow dynamic updates. Your DNS database appears to have many outdated records, and you suspect that they are a result of mobile users not properly shutting down their client computers. Which process should you use to automatically cleanse your DNS database of stale resource records? a. Run the Ipconfig /flushdns command. b. Enable aging and scavenging of DNS resource records. c. Run DNSclean from the command prompt. d. Run the Jetpack utility. 24. Which of the following is not a typical DNS security threat? a. Foot printing b. Denial of Service (DoS) attack c. Data modification d. Redirection e. Redistribution 25. Your Microsoft Windows Server 2003 network has three DNS servers running on Windows Server 2003 member servers. All DNS servers are configured to use forwarders to resolve external names and to allow zone transfers only to servers listed in the NS resource records in their zone. Which level of DNS security is in use on this network? a. Low-level security b. Medium-level security c. High-level security d. Active Directory–integrated security 26. You are the network administrator of contoso.com. Your network has a connection to the Internet, and all of the DNS servers run on domain controllers. Your DNS zones are all Active Directory–integrated zones. Which level of DNS security is in use on this network? a. Low-level security b. Medium-level security c. High-level security d. Active Directory–integrated security
https://de.scribd.com/document/53897278/Test-Bank-Ch3-Ch4
CC-MAIN-2019-30
refinedweb
2,979
69.07
Changes between Initial Version and Version 3 of Ticket #11115 - Timestamp: - 04/10/11 08:44:26 (5 years ago) - Author: - SimonKing - Comment: It took a bit longer than I originally expected, but I think it was worth it. New Features - An instance of a class deriving from Parent or Element can inherit a cached_method from its category, without breaking the cache, even if it does not allow attribute assignment. - The cached_method decorator can, to some extent, be used in Cython code. - Cached_method is a lot faster now. In fact, using the cached_method decorator on a Python class is faster than a hand-written cache for a Python method, provided that the arguments are given by name and not by position. Examples Python The following code defines a category, and a Parent class that has a method with a hand-written cache and a corresponding cached method inherited from the category: from sage.all import cached_method, Category, Objects, Parent class MyCategory(Category): def super_categories(self): return [Objects()] class ParentMethods: @cached_method def cached_by_category(self, x=100, y=-1): return x*y class MyPythonClass(Parent): def __init__(self): self._cache = {} Parent.__init__(self, category=MyCategory()) def cached_by_python(self, x=100, y=-1): try: return self._cache[x,y] except KeyError: out = self._cache[x,y] = x*y return out We do some sanity tests, and then show that the cached method is faster than the hand-written cache, unless we provide arguments by name: sage: O = MyPythonClass() sage: O.cached_by_category() is O.cached_by_category(100) is O.cached_by_category(x=100) is O.cached_by_category(100,-1) True sage: O.cached_by_python(y=1) == O.cached_by_category(y=1) True sage: O.cached_by_python() == O.cached_by_category() True sage: O.cached_by_python() is O.cached_by_python(100) is O.cached_by_python(x=100) is O.cached_by_python(100,-1) True Here are timings for the hand-knitted cache: sage: timeit("O.cached_by_python()", number=10^6) 1000000 loops, best of 3: 630 ns per loop sage: timeit("O.cached_by_python(100)", number=10^6) 1000000 loops, best of 3: 970 ns per loop sage: timeit("O.cached_by_python(y=-1)", number=10^6) 1000000 loops, best of 3: 1.1 µs per loop sage: timeit("O.cached_by_python(100,-1)", number=10^6) 1000000 loops, best of 3: 1.31 µs per loop and here are the corresponding timings for the cached method inherited from the category: sage: timeit("O.cached_by_category()", number=10^6) 1000000 loops, best of 3: 314 ns per loop sage: timeit("O.cached_by_category(100)", number=10^6) 1000000 loops, best of 3: 954 ns per loop sage: timeit("O.cached_by_category(y=-1)", number=10^6) 1000000 loops, best of 3: 1.93 µs per loop sage: timeit("O.cached_by_category(100,-1)", number=10^6) 1000000 loops, best of 3: 1.06 µs per loop Cython You can not use arbitrary decorators in Cython. But it is now possible to wrap a Cython function by the cached_method and assign it as a method - one needs to explicitly provide its name, though. In addition, we provide a hand-written cache programmed in Cython. from sage.structure.parent cimport Parent from sage.all import cached_method cpdef test_func(self,x=100, y=-1): return x*y cdef class MyCythonClass(Parent): cdef dict _cache def __init__(self, category): self._cache={} Parent.__init__(self,category=category) cached_by_decorator = cached_method(test_func, name="cached_by_decorator") cpdef cached_by_cython(self,x=100,y=-1): try: return self._cache[x,y] except KeyError: out = self._cache[x,y] = x*y return out It is a Parent class, and thus it can inherit parent methods from a category. Without the patch, the cache of an inherited cached_method would break, but now it is fine: sage: C = MyCythonClass(MyCategory()) sage: C.cached_by_category(y=-1) is C.cached_by_category(100,-1) True sage: C.cached_by_decorator(y=-1) is C.cached_by_decorator(100,-1) True sage: C.cached_by_decorator(y=-1) == C.cached_by_category(100,-1) True The trick is that I introduced an attribute __cached_methodsfor Parent and Element, in which a cached method can be stored. The cache is (since #8611) stored as an attribute of the bound cached method. While it is nice that cached_method works at all in Cython, the performance is not as good as I wish. Here are the times for the hand-knitted cache written in Cython: sage: timeit("C.cached_by_cython()", number=10^6) 1000000 loops, best of 3: 242 ns per loop sage: timeit("C.cached_by_cython(100)", number=10^6) 1000000 loops, best of 3: 538 ns per loop sage: timeit("C.cached_by_cython(y=-1)", number=10^6) 1000000 loops, best of 3: 750 ns per loop sage: timeit("C.cached_by_cython(100,-1)", number=10^6) 1000000 loops, best of 3: 882 ns per loop Here for the cached_method inherited from the category: sage: timeit("C.cached_by_category()", number=10^6) 1000000 loops, best of 3: 754 ns per loop sage: timeit("C.cached_by_category(100)", number=10^6) 1000000 loops, best of 3: 1.62 µs per loop sage: timeit("C.cached_by_category(y=-1)", number=10^6) 1000000 loops, best of 3: 2.77 µs per loop sage: timeit("C.cached_by_category(100,-1)", number=10^6) 1000000 loops, best of 3: 1.76 µs per loop And here using the decorator in Cython code: sage: timeit("C.cached_by_decorator()", number=10^6) 1000000 loops, best of 3: 421 ns per loop sage: timeit("C.cached_by_decorator(100)", number=10^6) 1000000 loops, best of 3: 1.02 µs per loop sage: timeit("C.cached_by_decorator(y=-1)", number=10^6) 1000000 loops, best of 3: 1.96 µs per loop sage: timeit("C.cached_by_decorator(100,-1)", number=10^6) 1000000 loops, best of 3: 1.07 µs per loop Conclusion The patch provides a considerable speed-up in a case where cached_method used before, so that cached_method is not only convenient but efficient. Also, it enables to use cached_method in a broader context; here, it is not particularly efficient, but it is convenient. We want that decorated (in particular, cached) methods appear nicely in introspection and in the reference manual. Therefore, I like to have: Legend: - Unmodified - Added - Removed - Modified Ticket #11115 - Property Status changed from newto needs_review - Property Authors changed from to Simon King Ticket #11115 – Description
https://trac.sagemath.org/ticket/11115?action=diff&version=3
CC-MAIN-2016-40
refinedweb
1,027
59.6
! Maybe I'm just not in sync with the docs (haven't read them in a while) but when I tried to install the newest CVS version the distutils script tried to install pyxrc in /etc -- where I don't have write access. If I tried to use --root (as per the comment in the code) that seemed to place other things in strange places (although I may have fouled that up ;) Commenting out the pyxrc stuff entirely worked well, though... -- Magnus Lie Hetland "Canned Bread: The greatest thing since sliced bread!" [from a can in Spongebob Squarepants] Hi! Just threw together a little geometry module to illustrate some ideas I've had; it's rather small, so I've attached it to this email. (Not quite sure if the list lets attachments through, but...) The main point isn't the geometry in itself (quite trivial) but the laziness; because there are lazy points that are calculated from other points on demand it is possible to emulate the equations of MetaPost (even though the emulation is one-way and functional, as opposed to the general equations in MetaPost). The API is a bit verbose at present (i.e. having to explicitly instantiate LazyPoint with the relevant points), lots of room for expansion (e.g. in-place methods, allowing the addition of two-tuples to points, ...) and the API isn't very PyX-like, I guess; I can have a look and see if I can make it fit more with the standard decorator paradigm used in PyX (along with the naming convention). For example, one could do a = point(b, [shifted(x, y), rotated(a)]) or something like that. I think that would work just nicely. With the current (quick scribble) API, the following would draw a triangle, shifted into the page: """ from geom import * from pyx import * from math import pi # Order is important here: a = Point(0, 0) b = a + Point(10, 0) c = a + LazyPoint(rotated, (Point(10, 0), pi/3)) # This will shift all the points: a.x += 10 a.y += 10 # Order is not important here: p = path.path(path.moveto(c.x, c.y), path.lineto(a.x, a.y), path.lineto(b.x, b.y), path.closepath()) c = canvas.canvas() c.stroke(p) c.writeEPSfile('test.eps') """ The following finds the midway point between two other points: """ from geom import * a = Point(0, 0) b = Point(0, 0) c = a + (b-a)/2 # a += (10, 10) etc. might be nice (and easy) here: a.x = 10 a.y = 10 b.x = 20 b.y = 20 print c.x, c.y """ What do you think? With a little polish, the basic scheme could work, couldn't it? -- Magnus Lie Hetland "Canned Bread: The greatest thing since sliced bread!" [from a can in Spongebob Squarepants] Andre Wobst <wobsta@...>: > > Hi, >=20 [snip] > As I said, I think none of the existing classes should be (miss-)used > for your needs. I see. Now that I think about it I believe I actually considered writing some geometry code (including support for points etc.) for Pyx (or, in fact, in general) a while back... Never got around to it, but it might be worth a second look, I guess. My need then was also MetaPost-like features, but more specifically equations (or something as similar to that as possible) and affine transforms of points (also usable in the equations). [snip] > So, in the end, we might think about introducing a point class and > numerics on points. Especially when we want create some features found > in MetaPost. I'm quite open to this discussion. I might throw together some really basic code and we can see how well it works, maybe? (Provided I get around to it; not necessarily a top priority and I'm currently on vacation :) > I was asked about MetaPost like features several times already. I'm > also willing to spend time on developing the fundamentals, but I > think we should start with independend classes in the first. Sure. I'm sure there are several packates for geometry available already; worth investigating, although starting a special-purpose module probably carries a very low cost (and it will most likely have to be integrated with PyX at some point anyway). Using numarray or the like might be useful, perhaps... (Maybe not; but at least they have support for vectors and matrices.) Are the affine transforms in PyX usable for this sort of thing or would one be better off writing a new transform system for the point module? > ... I agree. But that could, perhaps be done as a later step? > Andr=E9 --=20 Magnus Lie Hetland "Canned Bread: The greatest thing since sliced bread!" [from a can in Spongebob Squarepants] Hi, On 23.07.04, Magnus Lie Hetland wrote: > [...] It seems to me that > having a point type (class) would be useful (I'm used to the MetaPost > way ;) but I guess maybe there is a way of doing this gracefully in > Pyx as well... As we started PyX we decided to not introduce a point data type in order to lower the users overhead. Thus you directly use plain numbers (or a PyX length) at various places like in path.moveto() or text.text() instead of first constructing points. We not even started to group together coordinates in tuples (you could think of path.line((x1, y1), (x2, y2)), but we actually decided to use path.line(x1, y1, x2, y2)). So we do not have a proper representation of a point. A path, however, is a pure mathematical object. Especially the normpath (any path can converted to) supports quite some numerical operations (splitting, calcuation of intersection points, etc.). Futhermore the (affine) transformations are mathematical objects. While they also support the transformation of a point by the apply method didn't we introduce a point class here either. > Should I fiddle with the numbers directly? Use a path element? Perhaps > gather the points in a path? Use boxes with zero extent? What's the > 'Pyx Way' here? As I said, I think none of the existing classes should be (miss-)used for your needs. They all do not fit well. A path element is a path element, not a point. Sometimes it might be usefull as a return value, but it still is not a point. You might build up a path, when you want to construct a path in the end, but its not the correct representation of a list of points, because a path also defines, what's "in between" the points. The boxes are something very different (at least I think we'll move them towards the following): A box is an ordinary canvas having a predefined boundary. In the end, boxes will be the primary source for performing clipping operations. Of course, the aligment functionality will be usefull for objects with any kind of border as it is today already for the boxes we have. The connector functionality might become less restricted to boxes in the future. We'll see. So, in the end, we might think about introducing a point class and numerics on points. Especially when we want create some features found in MetaPost. I'm quite open to this discussion. I was asked about MetaPost like features several times already. I'm also willing to spend time on developing the fundamentals, but I think we should start with independend classes in the first. ... André -- by _ _ _ Dr. André Wobst / \ \ / ) wobsta@..., / _ \ \/\/ / PyX - High quality PostScript figures with Python & TeX (_/ \_)_/\_/ visit
https://sourceforge.net/p/pyx/mailman/pyx-user/?viewmonth=200407&viewday=26
CC-MAIN-2018-17
refinedweb
1,266
73.58
Please, ever get sent too close together. Example We can take advantage of Design Pattern: Associated Items and Design Pattern: Encoding and Accessing Values in Rules to make a generic solution. Note: The code below depends on the the WirelessDevice Items to be persisted. Items Group WirelessDevices Switch WirelessDevice_xxxxx_1 (WirelessDevices) Switch WirelessDevice_xxxxx_2 (WirelessDevices) Rules Python For the Python version I’ve created a reusable class I hope to submit to the Helper Library so you don’t have to copy and paste the code. I’m providing it here to see a version of this DP using Python. This is not the only way you can implement this DP. Unlike with Rules DSL, Python doesn’t have the same problem with long running Rules so you could implement this with a Rule and a lock. But I wanted to have an implementation that could be reused rather than requiring the user to create Rules, and I wanted the ability to have more than one Gatekeeper running at a time. """ A class to implement the gatekeeper DP """ from collections import deque from core.actions import ScriptExecution from org.joda.time import DateTime from core.log import log_traceback from Queue import Queue class gatekeeper(object): """ Keeps a queue of commands and makes sure that the commands to not get sent to the same device too quickly """ @log_traceback def __init__(self, log): self.commands = Queue() self.timer = None self.log = log @log_traceback def __proc_command__(self): # No more commands if self.commands.empty(): self.log.info("Done processing commands") self.timer = None return # Pop the next command and run it self.log.info("Processing a command") cmd = self.commands.get() funct = cmd[1] self.log.debug("Executing the command") before = DateTime.now().millis funct() after = DateTime.now().millis # Calculate how long to sleep delta = after - before pause = cmd[0] delay = pause - delta trigger_time = DateTime.now().plusMillis(delay if delay > 0 else 0) self.log.debug("Command took {} msec, sleeping for {} msec, next command to process at {}".format(delta, delay, trigger_time)) # Create/reschedule the Timer if not self.timer: self.timer = ScriptExecution.createTimer(trigger_time, self.__proc_command__) else: self.timer.reschedule(trigger_time) @log_traceback def add_command(self, pause, command): self.commands.put((pause, command)) if self.timer is None or self.timer.hasTerminated(): self.__proc_command__() @log_traceback def cancel_all(self): self.log.debug("Clearing out all enqueued commands") while not self.commands.empty(): self.commands.get(false) Theory of Operation: When a user has one or more Rules that need to use a Gatekeeper between commands, create an instance of gatekeeper. Instead of sending the command (or doing whatever activity) call add_command(lambda: <some actions>) which will add the command to the queue. As long as there are commands on the Queue, there is a looping timer that will pop a command, run it, then sleep (schedule/reschedule a Timer) before running the next command. Usage: just copy the above to your automation/lib/python/personal folder unchanged. Usage example: import personal.gatekeeper reload(personal.gatekeeper) from personal.gatekeeper import gatekeeper from core.log import logging, LOG_PREFIX log = logging.getLogger("{}.TEST".format(LOG_PREFIX)) gk = gatekeeper(log) gk.add_command(5000,lambda: log.info("one")) gk.add_command(4000, lambda: log.info("two")) gk.add_command(3000, lambda: log.info("three")) Define the gk variable so it is in scope to all of the Rules that need to use it. This can be done by putting all the Rules in the same file and making it a global in that file, or putting it in a library file and importing the variable. Rules DSL. Related Design Patterns Edit: Removed all the examples that require a Reentrant lock as I deem them unsafe to use under any circumstances. Edit: Updated the Python version so each command can have it’s own delay. This works better with the say Action.
https://community.openhab.org/t/design-pattern-gate-keeper/36483
CC-MAIN-2020-24
refinedweb
636
51.34
README ¶ Spaghetti: a dependency analysis tool for Go packages Spaghetti is an interactive web-based tool to help you understand the dependencies of a Go program, and to explore and evaluate various possible efforts to eliminate dependencies. It displays the complete dependencies of the initial packages, organized into a tree based on the directory structure of the package/module namespace. Clicking on a package node displays information about it, including an arbitrary path to it from one of the initial packages. Each edge in the path may be "broken", causing it to be removed from the graph and the view recomputed. The broken edges are tabulated, and each can be restored if you change your mind or try another approach. In this manner, you can explore how your overall dependencies would change as you work to remove specific imports. Once you are happy with the overall dependencies, the set of broken edges becomes your task list for a clean-up project. Run it like so: $ go install github.com/adonovan/spaghetti@latest # install in $HOME/go/bin $ ~/go/bin/spaghetti [package] & # run the server $ open # open in chrome, firefox, etc where package is or more Go packages, or a pattern understood by go list. Then point your browser at the insecure single-user web server at localhost:18080. This tool is a rewrite from scratch of a tool I wrote while at Google for exploring the dependency graphs used by the Blaze build system. The basic design could be easily be generalized to support any kind of dependency graph, independent of language or domain, or turned into a secure multi-user web service that operates on graph data uploaded from the client program that generates it. You can probably tell that web UIs are not my expertise. PRs that provide cosmetic improvements are most welcome!
https://pkg.go.dev/github.com/adonovan/spaghetti
CC-MAIN-2021-39
refinedweb
305
50.36
I am using python 3.4 , tweepy API to extract tweets to a text file but instead of only tweets the entire source of the page is being extracted. If there is a way to get the tweets only not entire source code . The tweets come in formatted as JSON. So include simple JSON into your script to encode them. (btw this is python 2.7 so you will have to do the print differently) from tweepy.utils import import_simplejson json = import_simplejson() Load each tweet with python, make sure that the data['entities]['hashtags] field is not empty (so it has a hashtag) data_temp = json.loads(data) if data_temp['entities']['hashtags']: tweet_text = data_temp["text"].encode('utf-8') then print it out to file print(tweet_text, file=write_file) These are only snippets, use this guys script to help you get going and source the tweets. Big ups to him:
https://codedump.io/share/K82Ogx2Q1t4/1/extracting-only-tweets-of-a-particular--hastag
CC-MAIN-2018-26
refinedweb
148
76.11
DIY Music players are fun to build, and we previously built a few music players using Arduino and a dedicated MP3 module. Now we are using ESP32 to build an interesting audio player, in which you can sound effects by just connecting an extra speaker to ESP32. Here we will use LM386 and a speaker with ESP32 to play music files. The audio output may not be loud but this application shows the ability of the ESP32 board to play audio files. Components Required - ESP32 - LM386 Amplifier Module - 8 ohm Speaker - Jumper Wires Circuit Diagram Circuit Diagram for ESP32 Music Player is given below- To play sound on ESP32, we need a speaker. The speaker is connected through the LM386 Audio Amplifier module. Vcc and GND pins of the Amplifier Module are connected to VIN and GND of ESP32 while IN pin of the Amplifier module is connected to GPIO 25 pin of ESP32. GPIO 25 is one of the 2 DAC (Digital to Analog Converter) pins. This is how the complete setup for ESP32 Music Player will look: LM386 is an audio amplifier IC, you can learn more about LM386 by following the link. Getting Ready with Audio Files To play audio sounds on the ESP32 board, we need audio files in .wav format because ESP32 can play an audio file in .wav format only. So the first step will be getting the file that you want to play on ESP32. After that, download and install the Audacity Audio Editor App. This app will be used to change the file type, Sample Rate, and other properties. Once the installation is complete, open the Audacity app and then go to file > Open and select the audio file to edit. The first thing that needed to be changed is the sampling rate. Editor app to generate Hex codes for the audio file. So download and install the Hex Editor (HxD) from the given link. After that, open the app, then go to File > open and open the .wav file. This will generate the Hex code for the .wav file. Then use ctrl+A to select the complete code and then go to Edit > Copy as > C to copy the code in C Language format. Then paste this code into Arduino IDE. Code Explanation The complete code for Contactless ESP32 Audio Player is given at the end of the page. Here we are explaining some important parts of code. In this program, we are going to use the XT DAC Audio library from XTronical. The XT DAC Audio library can be downloaded from here. So as usual, start the code by including all the required libraries. SoundData.h file contains the Hex code for the .Wav file that is to be played. #include "SoundData.h" #include "XT_DAC_Audio.h" In the next line, create an object of type XT_Wav_Class that is used by the DAC audio class passing .wav data as a parameter. DacAudio, the main player class object in which 25 is the DAC pin number where the amplifier pin is connected. XT_Wav_Class Sound(sample); XT_DAC_Audio_Class DacAudio(25,0); Inside the setup() function, initialize the Serial Monitor at a baud rate of 115200 for debugging purposes. void setup() { Serial.begin(115200); Inside the loop() function, fill the sound buffer with data and check if the sound is playing or not, if not, play the sound in the loop. void loop() { DacAudio.FillBuffer(); if(Sound.Playing==false) DacAudio.Play(&Sound); Serial.println(DemoCounter++); } Testing the ESP32 Audio Player Once the code is ready, connect the speaker to GPIO 25 of ESP32 through LM386 or any other amplifier module. Now connect the ESP32 to Laptop and upload the code. Once the code is uploaded, ESP32 starts playing the Audio. Sound quality can be changed using the potentiometer of the Amplifier module. Hope you enjoyed the project. A working video and complete code are given below, SoundData.h header file can be downloaded from here. If you have any doubts, leave them in the comment section. #include "SoundData.h" #include "XT_DAC_Audio.h" XT_Wav_Class Sound(sample); XT_DAC_Audio_Class DacAudio(25,0); uint32_t DemoCounter=0; void setup() { Serial.begin(115200); } void loop() { DacAudio.FillBuffer(); if(Sound.Playing==false) DacAudio.Play(&Sound); Serial.println(DemoCounter++); }
https://circuitdigest.com/microcontroller-projects/esp32-based-audio-player
CC-MAIN-2020-50
refinedweb
706
66.03
... Next › Last » venjo commented on 2017-07-16 13:09 2017-07-15 10:36:06,535|MainThread|acestream|error during startup Traceback (most recent call last): File "core.c", line 1590, in File "core.c", line 144, in File "core.c", line 2, in ImportError: cannot import name __m2crypto venjo commented on 2017-07-16 13:03 Still not working after installing that package! Trying to launch it form kodi... no go! error acestream not installed zezinho commented on 2017-07-15 15:02 Temporary fix: Don't touch package, it's bulding ok. Instead simply install m2crypto 0.23. Version 0.24 might work, too. pacman -U positron commented on 2017-05-27 18:31 Zerobit, it works for me. Do you still have problems with it? Maybe it wasn't only python2-m2crypto that was from testing in my system, but also openssl-1.0. ZeroBit commented on 2017-05-23 18:07 @positron Your PKGBUILD doesn't work I installed python2-m2crypto from testing pacman -Qi python2-m2crypto Name : python2-m2crypto Version : 0.24.0-4 Description : A crypto and SSL toolkit for Python Architecture : x86_64 URL : Licenses : BSD Groups : None Provides : None Depends On : python2 openssl-1.0 Optional Deps : None Required By : acestream-engine Optional For : None Conflicts With : None Replaces : None Installed Size : 1294.00 KiB Packager : Antonio Rojas <arojas@archlinux.org> Build Date : Fri May 19 20:27:23 2017 Install Date : Tue May 23 21:02:47 2017 Install Reason : Installed as a dependency for another package Install Script : No Validated By : None Then I installed acestream-engine with your version of PKGBUILD and now the situation is: sudo systemctl status acestream-engine.service ● acestream-engine.service - AceStream Engine (console) Loaded: loaded (/usr/lib/systemd/system/acestream-engine.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Tue 2017-05-23 21:02:53 EEST; 5min ago Process: 8498 ExecStart=/usr/bin/acestreamengine --client-console --bind-all (code=exited, status=1/FAILURE) Main PID: 8498 (code=exited, status=1/FAILURE) May 23 21:02:53 zenbook systemd[1]: Started AceStream Engine (console). May 23 21:02:53 zenbook acestreamengine[8498]: xx Cannot load libraries: path /opt/acestream/lib May 23 21:02:53 zenbook acestreamengine[8498]: Traceback (most recent call last): May 23 21:02:53 zenbook acestreamengine[8498]: File "<entry>", line 9, in <module> May 23 21:02:53 zenbook acestreamengine[8498]: File "core.c", line 132, in May 23 21:02:53 zenbook acestreamengine[8498]: ImportError: /opt/acestream/lib/libcrypto.so.1.0.0: version `OPENSSL_1.0.0' not found (required by /opt/acestream/lib/acestreamengine/pycompat.so) May 23 21:02:53 zenbook systemd[1]: acestream-engine.service: Main process exited, code=exited, status=1/FAILURE May 23 21:02:53 zenbook systemd[1]: acestream-engine.service: Unit entered failed state. May 23 21:02:53 zenbook systemd[1]: acestream-engine.service: Failed with result 'exit-code'. koskal commented on 2017-05-22 16:48 I thought there was problem with python2-2.7.13-2 and python2-m2crypto 0.24.0-3,so I downgraded the packages and and worked again. Today I decided to update again and still working with no errors. The only change I've made was that I change the owner of the acestream folder in opt from root to my user, otherwise the gtk version cant start. So no problem here!! Thanks positron commented on 2017-05-20 08:18 Here's working, what kind of recent updates you're talking about? EDIT: Since libopenssl-1.0-compat has been orphaned I tried to do the trick using openssl-1.0 and it worked. Here's an updated PKGBUILD: EDIT2: Works only with python2-m2crypto from testing. koskal commented on 2017-05-15 16:06 After recent updates doesn't work: 2017-05-15 19:05:39,035|MainThread|acestream|error during startup Traceback (most recent call last): File "core.c", line 1590, in File "core.c", line 144, in File "core.c", line 86, in File "/usr/lib/python2.7/site-packages/M2Crypto/__init__.py", line 26, in <module> from M2Crypto import (ASN1, AuthCookie, BIO, BN, DH, DSA, EVP, Engine, Err, File "/usr/lib/python2.7/site-packages/M2Crypto/ASN1.py", line 14, in <module> from M2Crypto import BIO, m2 File "/usr/lib/python2.7/site-packages/M2Crypto/BIO.py", line 7, in <module> from M2Crypto import m2 File "/usr/lib/python2.7/site-packages/M2Crypto/m2.py", line 30, in <module> from M2Crypto._m2crypto import * File "/usr/lib/python2.7/site-packages/M2Crypto/_m2crypto.py", line 17, in <module> __m2crypto = swig_import_helper() File "/usr/lib/python2.7/site-packages/M2Crypto/_m2crypto.py", line 16, in swig_import_helper return importlib.import_module('__m2crypto') File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named __m2crypto positron commented on 2017-05-01 20:54 Here's a PKGBUILD with the modifications mentioned by dieghen89: dieghen89 commented on 2017-05-01 10:51 Why not making libopenssl-1.0-compat a dependency and adding the symlink inside the package? Having symlinks in the / that are untracked by the package manager is not a great idea.
https://aur.archlinux.org/packages/acestream-engine/?O=40&PP=10
CC-MAIN-2020-45
refinedweb
868
51.04
0 Hello, I am trying to work learn thread programming in C. I have my turbo C installed and its working fine. I tried to get the library "pthread.h" and relater STLport package by searching online and managed to get them and copied them in my include directory. But while compiling a simple program stated as follows, a number of errors occur. Am I installing the POSIX files in the wrong directory or is there some other way to work with threads in C. I have also checked the options->directories in C options but even that is set properly. Please do shed some light on how to configure my Turbo C to work with threads. Thank you. #include <pthread.h> #include <stdio.h> #include <stdlib); } } pthread_exit(NULL); } Edited by katwalatapan: n/a
https://www.daniweb.com/programming/software-development/threads/220908/problem-working-with-posix-threads
CC-MAIN-2017-26
refinedweb
134
75.4
Show the console over top of a fullscreen presentation? Looking in the console module, I see the console.hide_output() function, but no console.show_output()...is it possible to slide the console in on top of a view being presented fullscreen? I want to be able to show/hide the console for debugging purposes without closing my fullscreen presentation window. @shinyformica see here @shinyformica Try this quick and dirty script from objc_util import * import ui def GetConsoleText(cv): win = ObjCClass('UIApplication').sharedApplication().keyWindow() main_view = win.rootViewController().view() ret = '' next_is_console = False def analyze(v,indent): global next_is_console ret = None for sv in v.subviews(): #print(indent,sv._get_objc_classname()) if 'OMTextView' in str(sv._get_objc_classname()): if 'line in console 0' in str(sv.text()): cv.text = str(sv.text()) #print(sv.text()) ret = analyze(sv,indent+' ') if ret: return ret ret = analyze(main_view,'') return ret if __name__ == '__main__': for i in range(0,10): print('line in console '+str(i)) v =ui.View() v.background_color = 'white' b = ui.ButtonItem() b.title = 'show console' def b_action(sender): if 'show' in sender.title: cv = ui.TextView(name='console') cv.frame = v.frame v.add_subview(cv) GetConsoleText(cv) sender.title = 'hide console' else: v.remove_subview(v['console']) sender.title = 'show console' b.action = b_action v.right_button_items = (b,) v.present() @cvp interesting...I'm not super psyched about hunting for and grabbing the contents of the console text view, seems a bit fragile. I like the idea in that thread you pointed to, of showing the console, but presenting a button to hide it...but I don't see a way of just "presenting" the console? hide_output() will hide the console...but how do I just make it pop up? Do I have to "show_image()" with an empty path or empty image or something? @shinyformica Ask @jonb how he saw that... @JonB you can blame @cvp for the ping...in the thread referenced here: you mentioned showing the console, but I don't see a way to just make the console pop/slide up? Is there some trick which will bring the console up, even if a view is being presented full screen? @shinyformica You could not do shorter and more robust, I think 😇 (perhaps @ccc excepted ) import ui #========================= module: begin from objc_util import * main_view = ObjCClass('UIApplication').sharedApplication().keyWindow().rootViewController().view() def GetConsoleText(v=main_view): for sv in v.subviews(): if 'OMTextView' in str(sv._get_objc_classname()): if 'OMTextEditorView' not in str(sv.superview()._get_objc_classname()): # not the script it-self return str(sv.text()) ret = GetConsoleText(sv) if ret: return ret #========================= module: end if __name__ == '__main__': v =ui.View() v.background_color = 'white' console_view = ui.TextView(name='console_view') console_view.border_width = 1 console_view.border_color = 'blue' console_view.hidden = True console_view.frame = v.frame console_view.flex = 'wh' v.add_subview(console_view) b = ui.ButtonItem() b.title = 'show console' def b_action(sender): if 'show' in sender.title: console_view.text = GetConsoleText() # <============= usage console_view.hidden = False sender.title = 'hide console' else: sender.title = 'show console' console_view.hidden = True b.action = b_action v.right_button_items = (b,) v.present() print('example of something in console').
https://forum.omz-software.com/topic/5787/show-the-console-over-top-of-a-fullscreen-presentation
CC-MAIN-2021-25
refinedweb
506
55
07 October 2010 11:51 [Source: ICIS news] By Anu Agarwal ?xml:namespace> SINGAPORE “We see very strong growth in Shell’s largest presence in the Asian lubricant market is in Shell has a capacity to produce around 1.6m tonnes of finished lubricants across Asia, Meanwhile, Ford is upbeat about “Demand is growing for lower viscosity and fuel efficient oils,” Ford said. Ford said he does not expect a supply glut when Shell’s gas-to-liquid (GTL) facility in The Pearl GTL project would be produce more than 1m tonnes of group III base oils. “We don’t see a crisis with increased group III supply with the start
http://www.icis.com/Articles/2010/10/07/9399338/shell-eyes-strong-growth-in-asia-lubes-market--executive.html
CC-MAIN-2013-48
refinedweb
111
67.49
jGuru Forums Posted By: Gautam_Mehta Posted On: Wednesday, July 4, 2001 03:32 AM Hi, I am having two different type of nodes 1.which are always leaf i.e. can not have children. 2. Which can have children and may be leaf. So i want to distinguish these 2 type of nodes so that the user may know which can have children and which can not. This difference can be either with a color or icon or anything. I have set setAllowsChildren(true/false), correspondingly also.DefaultTreeCellRenderer won't work ciz that too will set the color of all the leaves same. SO if anybody can help me out, i'll be thankful regards Gautam Re: Setting a Leaf in JTree(Urgent Please) Posted By: Aparna_Chaturvedi Posted On: Wednesday, July 4, 2001 06:08 AM what u can do is create a class in which u have the infrmation of nodes with that class u can define a treenode with 2 parameters in which one is the name of node and the other is the type of node .so for the 2 nodes u have 2 types.all child nodes have of a particular typ eof tree will be of same type as that of parent so while creating child nodes the first parameter that is the name of node changes while the type remains same as that of the parent .so by mentioning the type u can add child nodes only to that particular node.for example create class node public class Nodes public String strNodeType; public String strNodeName; public Nodes(String NodeName,String NodeType) { strNodeType = NodeType; strNodeName = NodeName; } then when ur creating the nodes in tree class create them as follows DefaultMutableTreeNode node1 = new DefaultMutableTreeNode ("name1","nodeType1"); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode ("name1","nodeType2"); if (strNodeType == nodeType1) setIcon(img); by this if node1 has child nodes all child nides will have the same icon as that of node1 provided if u create the child nodes as follows DefaultMutableTreeNode child1= new DefaultMutableTreeNode ("child1","nodeType1"); DefaultMutableTreeNode child2= new DefaultMutableTreeNode ("child1","nodeType1"); can u give me reply if this reply worked or not
http://www.jguru.com/forums/view.jsp?EID=449508
CC-MAIN-2013-48
refinedweb
352
53.95