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
.Net Framework is the first step to enter in to the .Net world. A framework can be defined as building blocks. Similarly .Net Framework can be defined as Building blocks of any .Net application. The .Net framework contains set of assemblies (in .Net we call all the DLLs as Assemblies) to support different kind of .Net applications (may be windows based, web based and other applications). Depending upon the kind of application we would like to develop we can use the corresponding Assemblies available in the .Net Framework. .Net Framework also contains some Assemblies to execute the .Net application. So .Net Framework is the collection of Assemblies to support the .Net application development and .Net application execution. We know that .Net Framework is a collection of Assemblies. Now let us know what does the word .Net mean? There is no reason given by Microsoft for the word ".Net", but you can see some definitions over the web saying that it is "Network of all technologies", "Next Generation Technology" and so. We have so many technologies available over the world. Now why do we need one more technology called .Net? Why should I go for .Net? The answer for this question can be Let's look on each briefly, The most expensive problem the current VC++ programmers are facing would be 'memory leak'. To be clear, every new operator we use in our program should be matched with a delete operator. i.e. if we allocate memory for an object using new keyword then it should be deallocated using the delete operator. If we forget to apply delete operator then the memory allocated using the new operator cannot be used for other purposes. This is called memory leak. In .net there is no place for the term memory leak, because we don't have to use delete operator on any object. We can use the new keyword, and forget about delete. .Net will automatically delete the object when that particular object is no longer used or referenced. Web Services are standardized way to communicate between two entities/processes over web. This uses XML(eXtensible Markup Language), WSDL (Web Service Description Language), SOAP (Simple Object Access Protocol), and UDDI (Universal Description, Discovery and Integration). We can think of this web services as similar to windows services but this web services can also be accessed from any where over web. .Net has full support to the web services comparing other technologies. In case of .Net applications, the deployment is just a copy and paste. Because all the .Net assemblies are 'self describing'. We don't need to depend on any header file or registry (like COM components) or others. Just by copying the files and pasting it in a different machine will complete the deployment. (However any shared assemblies should be installed into a special folder called 'assembly'). Interoperability can be defined as the ability of a hardware/software to share data between two applications on different/same machine. Consider we have two applications one is developed in VC++ and other one is developed in VB. It is not possible to share the data (with out any special mechanism) from one application to another application as the data type used in one language cannot be understood by other application. Most of the applications running now a day were developed using C, C++, COM etc. Moving towards .Net technology, it is not possible to recreate all the application developed in other technologies so far. For that purpose .Net has provided a full support for .Net applications to interact with other applications and vice versa. Any COM component or Win32 application can be communicated easily with .Net application. Consider you are creating a DLL using VC++. Now what if you want use this DLL in VB application, we cannot use the DLL in VB, i.e. cross language interoperability is not supported. But in case of .Net languages you can create a DLL using C#.Net and use that DLL in VB.Net application. Similarly you can cross with any .Net languages. Note that only .Net languages can be crossed. VC++.Net and VC++ are not same (we will see the difference later). So what is .Net? It is not a Language. It is not an operating system. It is a platform to execute .Net applications. We saw that .Net is platform to execute the .Net applications. Let's now look at the architecture of the .Net The above diagram summarizes the architecture; let's look at the each item from the bottom, Processor: Needless to say all the applications should run in processor. Operating System: similarly all the application can get the processor time only through the operating system. Common Language Runtime: It is usually called as CLR, which is a new layer added for .Net architecture. This new layer differentiates .Net applications from other applications. Normal windows applications run directly under the operating system, but any .Net application cannot run directly under the operating system, all the .Net applications require CLR to be there to get executed. .Net Framework Assemblies: These are the set of assemblies can be used by our application. .Net has provided a lot of inbuilt classes and methods which can be used by our application. These classes and the methods are packed in different assemblies. All these assemblies are collectively called .Net framework assemblies. ASP.Net, WinForms, WebServics, Others: These are kind of application we usually develop. ASP.Net refers to the web based applications, Winforms refers to the Windows based application, WebServices as seen earlier. And there are other kinds of application we can develop as per the requirement. Each kind of application uses respective .Net framework assemblies. Not all applications use all assemblies. Each application uses related or corresponding assemblies from the .Net framework. .Net Languages: These are the programming languages we use to develop our application. We can choose between any languages as per our comfort. All the languages have the full access to the .Net framework. (However some .Net features are specially designed for C#). We saw that .Net architecture contains a new layer called CLR, without this layer any .Net application can not be executed. Now let us see the steps involved in a program execution. Before starting with .Net application execution let's recollect how a normal C program works. We write our C code in plain ASCII code, the C compiler converts the ASCII code to binary code (.exe), this binary code will be executed by the operating system. But in case of .Net, the compiler will not generate binary code from the ASCII code, instead the compliers will generate only the MSIL (MicroSoft Intermediate Language) from the ASCII code. This MSIL will then be converted to binary or native code by the CLR depending upon the target OS. That is why we need CLR to execute any .Net application as the processor cannot understand the MSIL code they understand only the binary code. Why? Why do we want to convert the ASCII to MSIL first then to Native? What is the advantage do we get? The reason why do we go for the MSIL step is that, we are getting most of the benefits of .Net through this MSIL, for e.g. resource management, object lifetime management, reflection, type safe, some debugging support, etc. To avail these benefits we go for the MSIL step. And these benefits make the developer's life very easy. Finally we, the developers are rewarded with this MSIL. Before answering this question let's recollect what is platform independence. It can be defined as 'compile the code in one platform and run it in any platform'. To be clear the compiler should not generate any platform specific code as compiler output. How java is platform independent? Java compiler generates byte code as complier output. This byte code is platform independent. And java has JVM for different platform, the byte code can run on any JVM i.e. any platform. Thus the generated byte code is platform independent. Coming back to .Net, as we saw, our .Net compliers generates the MSIL code and this MSIL will run on CLR. This MSIL is not platform specific i.e. it can run on any platform if CLR for the platform is available. But Microsoft has not provided CLR other than Windows platform. So .Net technology is platform independent but we don't have CLR for other platforms from Microsoft. We saw that we need CLR to run any .Net application. Consider you have two EXEs. One is .Net exe and other one is normal windows application exe. Both are located in your C drive. When you double click on an exe the OS (Windows) will handle the click event and will run the exe in the processor. But incase of .Net exe the CLR has to be loaded to execute the .Net application. So how does the OS know to load CLR incase of .Net application? To answer this question let's understand the parts of a .Net assembly/exe. Any .Net assembly/exe has the following four sections. PE Header is a normal COFF header used by the operating system. When we double click on any exe the instruction inside this section will be executed by the OS. In our case, for .Net applications this section will redirect the OS to the CLR header section. CLR Header, this is a different section which we have only in .Net assemblies. This section contains some instructions to load the CLR. This part of header section is responsible to load the CLR (if not been loaded already) when we try to execute a .Net application. Till now the control is in the hands of OS, after the CLR is loaded the CLR will take the control of the application from the OS and the CLR will execute the .Net application. Now the CLR will execute the application from the Main method available in the MSIL section. Metadata, initially we saw that all the .Net assemblies are 'self describing'. This metadata section is responsible self description. This section will contains all the information about the assembly like list of namespaces, classes it has and methods in each class, parameters, etc. MSIL, implementation of all the methods, classes, etc. available in the assembly will be there in this section in MSIL format. As we saw this is not in binary format. MSIL is like another assembly language. We have VB.Net, C#, VC++.Net, J#, etc. languages. Does choosing a language for an application affects the performance or usability of framework? The answer is NO. All the compliers generate the MSIL code. Microsoft has provided these many languages to support different syntax. If you are familiar with VB syntax then you can go for the VB.Net language, if you are familiar with VC++ syntax you can go for the VC++ language. Choosing a language does not affect the usage of .Net framework. Al the framework libraries are available for all the languages. And as all the compliers generate the MSIL it doesn't have any impact on the runtime too. If you are new to any syntax it is good to use C# as it has got more features. As we saw we have many .Net languages but all the languages produce the MSIL as output. This MSIL is common. So the target types are shared by all the languages. These target type are the types that is defined in the MISL. And all the languages have to obey some rules for generating the MSIL like syntax and types. The rules that should be followed by any .Net languages are called CLS or Common Language Specification. And there are some set of types in the MSIL that should be supported by any language as a minimum requirement. These set of types are called CTS or Common Type System. There are some types outside the CTS, but these type are optional may be supported by a language. Each language will have its own boundary like the following diagram. In the above diagram we could see that all the languages supports the CTS minimally and some extra types. And diagram also shows all the languages obey the rules defined in the CLS. We achieve the interoperability through this CTS. Since all the .Net languages are expected to support CTS it is guaranteed that types inside this CTS are fully interoperable. Having said about CTS/CLS it is also possible to write your own .Net language which will have your own syntax. But while developing the complier you should keep in mind that you support all the CTS Types and obey the rules specified in CL.
http://www.codeproject.com/Articles/20694/Net-Framework?fid=467181&df=10000&mpp=10&sort=Position&spc=Relaxed&tid=4141480
CC-MAIN-2016-18
refinedweb
2,121
68.36
Back in October I received an email from the Sam Bass Community Theatre, inviting people to audition for a part in their holiday production of The Best Christmas Pageant Ever. I had no particular desire to act, but I went to volunteer as a stage hand or some such. They gratefully accepted my offer, and a few weeks later called to tell me they were ready for me to start. I had spoken to the stage manager briefly and was waiting for instructions when the director approached me and asked if I’d consider taking over the role of an actor who had to leave unexpectedly. Having read the script, I knew that the role she was offering had only one scene with five lines of dialogue. She didn’t even ask me to audition; just gave me a script and pushed me backstage. Seeing as how I only had that one scene, I also played stage hand: doing some minor set construction, arranging the set before each performance and during intermission, and riding herd on 20 children aged from about eight to sixteen. I thought it would be a struggle not to strangle a couple of those kids before the play had finished its run, but once they got into costume, they were very well behaved. Even young children know when it’s time to quit being childish and get to work. Debra volunteered, too, but her schedule was already pretty full. She did manage to paint a custom backdrop based on the director’s sketch. That turned out great. Even though it’d been nearly 50 years since the last time I was in a play (I was Dr. Dolittle in a production for my kindergarten class back in … 1967), stage fright wasn’t a problem. I’ve done enough public speaking that getting up in front of an audience of 50 people isn’t particularly daunting. Memorizing five lines of dialogue and delivering it reasonably well isn’t terribly difficult. By the time the first performance rolled around, I’d done the scene often enough that I felt very comfortable with it. Even so, I did manage to fumble a line during one or two performances. Fortunately, the woman with whom I did the scene is much more experienced than I and was able to make it look like nothing was amiss. It was a big time commitment: about three hours a night for four or five nights per week, for about eight weeks. But I can’t remember the last time I had so much fun. I especially can’t remember the last time I had that much fun without having to spend any money. And I learned a bit about theater, more about myself, and met a lot of good people who I hope to work with again. I’ve already volunteered to help as a stage hand with their next production, and I’m planning to audition for a part in one of their upcoming productions in the spring. It was altogether a thoroughly enjoyable experience. If you’ve ever wanted to give acting a try, find when your local community theater is having auditions and go audition! You don’t need any experience. They like new faces and inexperienced actors. Many of the people who produce and direct at community theater are teachers at heart. If you go in with a sincere desire to learn, they will welcome you and help you learn to act and to appreciate the art of theatre. I can’t say enough good things about the director, stage manager, the other actors, and everybody else who I met there. Every one of them was friendly, welcoming, and helpful. The theatre is the people, and the people I met at Sam Bass Community Theatre are among the best ever. I’ve uploaded the source code for my Merge LINQ extensions. This also includes the source for my DHeap class and for the TopBy extension method. The code is supplied in a .zip file and includes a Visual Studio 2013 project file. If you have an earlier version of Visual Studio, you probably won’t be able to read the project file, but it’s easy enough to recreate one from the source files provided. The code is all MIT License, meaning you can do with it what you like. I request that you let me know if it’s useful to you, but there’s no requirement. Download: EnumerableExtensions.zip Getting back to my discussion of merging multiple lists. Testing relative performance of the different merge algorithms turned out to be more involved than I had originally thought it would be. I found the results somewhat surprising. The short version is that in a normal procedural implementation, the pairwise merge is faster than the heap based merge, except in rare cases of many lists with very large differences in the lists’ lengths. But when it comes to LINQ implementation, the heap based merge is faster due to complications in the way that multiple criteria are handled. I found the first result very surprising because the heap-based merge is provably optimum from a theoretical standpoint. But it turns out that managing the heap is expensive compared to just iterating lists. Even more surprising is that the difference in speed increases as the number of lists grows. That is, when merging five lists that are the same size the pairwise merge is perhaps 10% faster than the heap based merge. When merging 10 lists, it will be 15 to 20 percent faster. I found that result surprising. At first I thought the difference was because my heap based merge implementation made use of my generic DHeap class, which adds some overhead. So I rewrote the merge to use a custom heap that’s optimized for this application. That made the heap merge faster, but not faster enough to overtake the pairwise merge. The relative speed of the two implementations is somewhat sensitive to the keys being compared. As key comparisons become more expensive the heap based merge begins to outperform the pairwise merge. When merging strings, for example, the heap based merge is closer to the same speed as the pairwise merge. With very expensive comparisons, the heap based merge is clearly the faster of the two. The reason for this is simple. The runtime complexity of the algorithms is based on the number of comparisons. The heap based merge will never do more than n log k comparisons, so when comparison speed becomes the limiting factor the algorithm that does the fewest comparisons will be the fastest. After testing performance of the algorithms as standard method calls, I began creating LINQ-callable methods called MergeBy and PairwiseMergeBy. The heap based merge conversion was straightforward and doesn’t look fundamentally different from the MergeWithBy extension method that I presented a while back. MergeBy PairwiseMergeBy The pairwise merge works by creating a merging network that does multiple merges in parallel. That is, given eight lists to merge, labeled ListA through ListH, it creates the following merge operations: Merge A and B to create AB Merge C and D to create CD Merge E and F to create EF Merge G and H to create GH Merge AB and CD to create ABCD Merge EF and GH to create EFGH Merge ABCD and EFGH to create ABCDEFGH It creates an inverted tree of merges that looks like this: A B C D E F G H | | | | | | | | +--+--+ +--+--+ +--+--+ +--+--+ | | | | +----+----+ +----+----+ | | +---------+---------+ | Output So I have seven different merges running concurrently. The first problem is that this requires twice as much memory as the heap based merge. The heap based merge requires memory proportional to the number of lists (N) times the number of keys (K). That is, N*K memory. The pairwise merge has N-1 merges running in parallel, each of which requires (2 * K). So the pairwise merge memory requirement is (2 * (N-1) * K) for the keys, and (N – 1) for the iterators. That’s not a huge deal, because the number of lists and the number of keys are both typically small. If we were merging millions of lists this might be a concern. Still, the additional memory is a drawback. The bigger problem turned out to be structuring the code so that it worked and was understandable. If you’ve been following along, you know that implementing the IOrderedEnumerable interface is complicated enough. Adding this complexity on top of it made things really convoluted. And by the time I got it all working, the pairwise merge just wasn’t consistently faster enough to justify the complexity. So I junked the idea. The final code uses the heap based merge. IOrderedEnumerable The resulting MergeBy method is not an extension method. Rather, it’s a static method in the LinqExtensions namespace. LinqExtensions public static IOrderedEnumerable MergeBy( IEnumerable> lists, Func keyExtractor, IComparer comparer = null); There is also a MergeByDescending method, and you can use the ThenBy and ThenByDescending methods to add multiple merge keys. MergeByDescending ThenBy ThenByDescending I’ll publish the final code in the next posting. That will contain all of the merging code I’ve developed in this series. One of the machines our software controls builds oligonucleotides by pushing various chemicals through a fine glass mesh. To do that, the machine dispenses the chemical into a common line and then pumps it to the destination. Logically, the machine looks like this: |--------| |-----------------| +-----------+------+--------+- PUMP -+----+---------+------*---- Column ---- |----+ | | | |--------| | | |-----------------| | Neutral A B | | | | | | +-------+-------+-----+ +-----------------------------+---- Waste | | | Argon S O Flow is from left to right. The chemicals at the top are delivered by turning the pump. If we want to push 100 microliters of A through the column, we first open the Neutral valve and run the pump until the entire line through the column is filled with the Neutral solution. Then, the software closes the Neutral valve and switches the output to target waste rather than the column. Then the A valve is opened and the pump is turned long enough to inject 100 ?l into the line. Then, the output valve is switched to target the column, valve A is closed, Neutral is opened, and the pump turns to push the chemical through the column. It’s a little more complicated than what I describe, of course, but that’s the gist of it. Pump delivery is relatively easy because we know the length (more importantly, the volumes) of each tube segment, and we know very precisely how much liquid is moved with each revolution of the pump. If we want 100 ?l and the pump moves 20 ?l per revolution, then we run the pump for five revolutions. The pump is operated by a stepper motor, so we can vary the pump speed by controlling the rate at which we issue step commands to the motor. All we have to do is tell the pump controller, “do X revolutions in Y seconds.” The controller takes care of it and reports back when it’s finished. If we want to deliver 20 ?l in three minutes, we tell the pump to do one revolution in 3,000 milliseconds. The motor controller figures out how many microsteps that is, and sends the motor pulses as required. For reasons I won’t go into, some chemicals are better delivered by pushing with an inert gas (Argon, in this case). Each of the bottles on the bottom is sourced from a bottle that’s under positive pressure. If the S valve is opened, liquid starts flowing, and continues to flow until the valve is closed. We know that at our standard operating pressure, the liquid will flow at a rate of about one microliter every seven milliseconds. So if we want to inject 20 ?l of S, we open the S valve for 140 milliseconds. We can then close the S valve and open the Argon valve long enough to push the chemical through the column. The problem comes when we want to vary the speed of Argon delivery. With the pump, all we have to do is slow the pump speed. But we can’t vary the bottle pressure so we have to toggle the Argon valve to simulate pumping. And that’s where things get kind of tricky. Imagine, for example, that you want to deliver 20 ?l of S smoothly over three seconds, rather than at the standard rate of 140 ms. If we could switch the valve on and off quickly enough, that wouldn’t be too difficult. We already know that we can pump 1/7 ?l in a millisecond, so if we could toggle the valve every millisecond we could have 140 pulses of 1 ms each, with a 20 ms wait between each pulse. That would deliver in 2,940 ms. Unfortunately, those valves don’t turn on and off instantly. It takes about 25 milliseconds for a valve to open after it’s energized. And it takes another 25 milliseconds for the valve to close completely after we cut power to it. So we can’t switch the valve faster than once every 50 milliseconds. And during at least part of that time the valve is partially open. So some liquid flows before the 25 ms is up. We can measure that, of course, and we could calibrate each valve if we wanted to. In practice, that calibration isn’t all that helpful. We can do almost as well by taking an average of all the valves in the system. If you’re wondering how long 50 milliseconds is, a typical eye blink is between 300 and 400 milliseconds. So, whereas you can blink your eyes maybe three times per second, I can toggle these valves on and off 20 times per second. The other problem is that the computer controlling the valve doesn’t have infinite resolution. Wait precision is typically about five milliseconds. If I want a seven millisecond wait, I’ll typically get something between 7 and 12 ms. All those uncertainties mean that if I want to open the valve for what I think is 7 ms to dispense 1 ?l, it takes 57 ms and I could end up with 2 ?l flowing from the valve. This is what we end up calibrating. The tube volume from the farthest Argon-propelled valve to the waste is, say, 4,000 ?l. We’ll clear the line (blow it out with Argon), and then start toggling the S valve in one-?l pulses until liquid flows from the waste. If it takes 2,500 pulses, then we know that one pulse dispenses an average of 1.6 ?l. If it takes 5,000 pulses, we know that one pulse is, on average, 0.8 ?l. That’s the number we’ll use in our calculations. Interfacing with the real world presents a lot of challenges, but it’s incredibly rewarding. I worked on this machine’s software for several months before I got to see one of them in operation; all my work had been against a simulator. It was very rewarding when I finally got to watch one of these machines work in response to user input, knowing that my software had converted the user’s commands into commands that make the machine switch valves and pump liquid through the system. Controlling hardware like that is the most rewarding type of programming I’ve ever done. I did it years ago, and I’m re-discovering just how much fun it can.
http://blog.mischel.com/2014/12/
CC-MAIN-2017-22
refinedweb
2,592
71.34
Plotting > 10k random 3D points Hi, First of all, I am new to SAGE, and only started using it today. I want to plot 100 000 random 3D points in SAGE, and it takes a LOT of time just to plot 10 000 points. This is the code I have: def random_point(): return (random(), random(), random()) l = [random_point() for k in [1 .. 10000]] s = point3d(l, size=5) show(s, aspect_ratio=1) I noticed that the last two lines take incredibly long each. Then, after the show, when I try to interact with the graphic, it is blank. I can even show the boundbox and axes, but the plot is nowhere to be seen. If I change to [1 .. 100], everything works as intended, but this amount of points is not enough. What should I do to accomplish effectively my goal? I am using SAGE 8.1, installed on macOS via brew, after running notebook() on the command line and using the browser-based notebook. Thank you! Maybe I'm naive but I can imagine it takes a while to plot 'just' 10,000 points in 3d. Your code works on my installation. Maybe try a different viewer: e.g. s.show(viewer='threejs') @rburing : even the construction of stakes time, not only the jmol plotting.
https://ask.sagemath.org/question/44286/plotting-10k-random-3d-points/
CC-MAIN-2019-30
refinedweb
216
83.05
Hello I passed to functions and I have the next exercise. you are expected to write a program that computes the sum of all the integers in a range specified by the user. In addition to the main function, there should be a function that accepts two parameters that specify a lower and upper bound. It should compute the sum of all the integers between those bounds, inclusive, and display that sum. The main function should prompt the user for the two bounds and call that function passing in those values. It should then allow the user to compute another interval sum or to quit. A sample dialog for this program looks as follows: Enter a lower and upper bound: 2 4 Sum = 9 Enter 0 to quit, 1 to continue: 0 I have written this #include<iostream> using namespace std; void sum ( int value, int& count); int main() { int value1, value2,i,sum=0; cout<<"Enter a lower and upper"; cin>>value1>>value2; system("pause"); return 0; } but I do not know how to determine how many numbers are between the start and the end value.
https://www.daniweb.com/programming/software-development/threads/310945/exercise3
CC-MAIN-2018-47
refinedweb
187
62.41
? Kinda. You have two options really. Command Palette. If you can't remember a specific shortcut, most commands are available from the command palette, which is essentially just a dropdown of commands. If a specific command isn't in the palette, you can add them with a sublime-commands file. Key Sequences. You can assign multiple commands to the same initial key in a sequence. For example, you could have a key sequence set to "ctrl+b","ctrl+m" and then another key sequence set to "ctrl+b","ctrl+n." Keysequencing allows for using multiple, easy to remember shortcuts instead of longer, more complex shortcuts. Something interesting, though, is key sequences don't require modifiers. So feel free to set the following to a sequence: "ctrl+u",f. P.S. the keybindings I gave you are not valid because they already of a non-sequenced keybinding attached. You can also do something like that: class YourCommand(sublime_plugin.WindowCommand): def run(self): self.menu = "1. Checkout", "2. New branch", "3. Rename branch", "4. Delete branch" ...] self.window.show_quick_panel(menu, self.command_selected) def command_selected(self, selected_index): ... Then you bind a hotkey to your_command et voila. I prefixed the commands with numbers, because this works well with fuzzy matching implemented in Sublime's quick panels. So, to checkout a branch, I just press my shortcut, then 1, then Enter. In addition, you can add your regrouped commands in the command palette with a common starting description: { "caption": "Code Folding: web_todo_excl", "command": "reg_replace", "args": {"replacements": "web_todo_excl"], "action": "fold"} }, { "caption": "Code Folding: web_log_filter", "command": "reg_replace", "args": {"replacements": "web_log_filter"], "action": "fold"} } And add a keybinding that open the command palette with the same starting description, filtering everything else: { "keys": "ctrl+alt+shift+f"], "command": "show_overlay", "args": {"overlay": "command_palette", "text": "Code Folding: "} }, Thanks so much guys really apprechiate the tips... COD312 I was looking at key sequences in the documentation for version 1... I can't find anything for v2... I'm still not exactly sure how this is supposed to work... could you elaborate a little more? Sure thing. Key sequences work exactly like regular keybindings. So you can place the following in your User Keybindings file: [pre=#2A2A2A]{ "keys": "ctrl+j","p"], "command": "some_command"}[/pre] Then you trigger it by pressing control + j followed by p. Important: there is a restriction on key sequences. You cannot assign a key sequence if the initial key already has a binding. For example. If you have { "keys": "ctrl+j"], "command": "some_command" } , you can't have { "keys": "ctrl+j","p"], "command": "some_command" } Which makes sense because sublime will trigger the keybinding first before a sequence can be created (if that makes any sense). Let me know if you have any other questions.
https://forum.sublimetext.com/t/multiple-key-bindings-to-one-key-w-dropdown/5716/1
CC-MAIN-2017-22
refinedweb
453
56.35
Some smart people told me once, that knowing your tools well is one of the best ways to keep productive and focus on what really matters - delivering value to your customers. Craftsmen are successful only when they know how to use their tools. But do we? Do we know their true potential? How many times did you just blindly added .idea to .gitignore? I’m working at a company which has multiple GIT repositories and I see how developers spend hours configuring their PhpStorm, or just using defaults and wasting time fixing simple mistakes reported in a code review, which could’ve been fixed automatically. It made me wonder how can my tool help me? I’ve been using PhpStorm since the beginning of time, and the official JetBrains documentation recommends adding .idea folder into VCS, but adding it without understanding implications seemed odd. So I’ve set out to research and experiment with it, see what each of the files does and how can it benefit me and my teammates. Here’s what I’ve found! In short I feel these are the main benefits of versioning PhpStorm configuration: - Increase the productivity of all your teams - Save time in PRs by focusing only on important bits - Be easily informed of updated code guidelines - Bring more clarity to difficult projects using scopes - Mark directories as a specific type - Save time for new joiners - Set up new tools only once - Allow different projects with unique configurations If any of these looks interesting for you, read on! Not using PhpStorm? Maybe your IDE has similar ways of sharing configuration? Increase the productivity of all your teams You won’t be frustrated and will save brain power when working together with your peers because you will have the same IDE setup! When pairing with fellow developers, I have a problem, that our PhpStorm inspection settings are different. For example, they have default inspections enabled, which are not customised for the given project but I have it otherwise, changed a few things so I can safely rely on PhpStorm showing no problem markers in my window. When I see yellow - it makes it hard to focus on what design problem are we solving, instead - I’m looking what are the mistakes the code. It would be solved by having the same set-up. The example above provides the difference between a file with problems and without. Which one would you prefer to see in your IDE? Additionally, you can always rely on PhpStorm’s “Perform code analysis” check before commit - it will warn if any of the files included in the commit have problems found by inspections, allowing you to safely fix them before. It’s a possibility to even fix them automatically! I like this feature, because it acts as a double-check for every commit I make, saving me the time to get back and fix my mistakes, or worse - let the SAT (Static Analysis Tool) or any other CI checks to find it 😓. It just makes everything faster. And finally, there will be an understanding that everyone sees their IDE in the same way, thus no need to double-check for problems or issues that your IDE can detect automatically for you, leaving that precious brain power for more interesting problems! Save time in PRs focusing only on important bits When reviewing a pull request, I’ve caught myself multiple times writing comments like “please make this compatible with our code style guidelines”, “this is not PSR4 compatible” or “you don’t need this closing tag here”, together with more important comments about design choices or bugs. This always felt like a waste of time and my brain power. Most of these cases can be caught automatically if you share a good PhpStorm set-up together. They will be caught by your CI tool or automated SAT too, but that involves waiting and feels unproductive. You can ask others to update their configuration, but if you work with 50 developers around you, everyone will start asking everyone? That would feel like a waste of time. You can utilise the powerful inspections engine in PhpStorm, which can be customised and set to have different profiles. For example, you can enable “PHP Code Sniffer” inspection with your custom ruleset, and it will mark only important bits that you care about in the problem sidebar of PhpStorm. You can go as detailed as writing custom regexp rules for all your naming schemes in the code. There is a ton of inspections, and you can add more by using plugins like Php Inspections (EA Extended), all of which can be turned on/off, be set to different reporting level or even scoped to be checkded in one place and skipped in another. Be easily informed of updated code guidelines Things change constantly in our world. Say you need to upgrade from PHP 5.6 to PHP 7.0, which comes with new features and removes some old ones. Of course, your agreement on code style and coding standards will change with this too. Now we all know people don’t like change and it’s very hard to remember these things, especially when you’re coding for a long time in an old convention, but if your configuration is shared between all of your developers, this would be avoided! By versioning your PhpStorm’s settings, you can just enable any new inspections for those new features and commit it, and everyone eventually will have them. Do you have a code style change too? Maybe some new plugin settings were added? Commit them too! This saves you from adding additional documentation somewhere else (we know it gets outdated very fast), gathering everyone in a meeting to announce these changes or sending mass emails which no one reads. This change will be always in your Git history, and as long as you have clear commit messages, that can serve as your documentation and reasoning for the change. If there is an opinionated change - pull request can be a place where everyone can have a discussion, the same place, where you’re discussing code too. Note 1 - unfortunately currently there is no possibility to share installed plugins via .idea folder and has to be done by each developer separately, the good news is that you can version configuration of those plugins regardless if it’s installed in PhpStorm or not. Note 2 - Only the inspections that are “Stored in Project” are saved in .idea and can be shared. Bring more clarity to difficult projects using scopes If you work on a big project - most likely you will have a mix and match of a codebase that has a different levels of quality. Or perhaps you have different rules for your tests? Controllers? Maybe you have a “legacy” folder that contains unmaintainable code and you want to ignore it? Then probably you also don’t want to rely on PhpStorm to check all of your files, since it will report on a lot of problems in those areas which will be only noise, hiding important problems. That kind of beats the purpose of utilising this awesome IDE right? Did you know that you can create different scopes and then apply different rules to those scopes? You can use scopes in search, inspections with an addition of adding different colours to them! “A scope is a subset of files, and/or directories in your project, to which you can limit the application of specific operations, e.g. search, code inspection, etc.” Read more about scopes at PhpStorm help. I’m using scopes to help me find my way around the project and set up different inspection settings for them. First, I am using them to add colours to different file types. If you have your filenames formatted like FrontpageController.php or AddCommentCommand.php or let’s say you keep all of your controllers in the Controller directory, you can define different colours for them. This helps me very quickly identify what I’m looking for in a big list of files or in the search. You can see I’ve coloured my Commands in blue and Controllers in red so now I can easily distinguish between them without reading actual names. Their background will be the same in search also. Another use for scopes is inspections. You can define different levels for inspections (or completely disable them) for different kind of scopes. Here I disabled the warning for an undefined class constant in my Controllers scope. This helps me to customise my project setup even further and allow specific checks to be disabled for problematic or opinionated pieces of the code. For example, sometimes my tests don’t have proper references set-up, so I can disable those checks only for tests scope (not that it’s a good practice, but it removes noise from signal). Or I have a very old code stored in a separate directory, I can disable the check for PSR4 class names there because I know, we won’t be changing them anytime soon, so why to train our brain to ignore those warnings? This way it will ignore the important ones too. You can go to any extent you want with this customisation, with the goal being not to miss important bits, remove noisy warnings and have PhpStorm inspections always reporting green 💚. Note - Don’t forget to create “Shared” scope in order for it to end up in .idea folder. Mark directories as a specific type Have you created a lot of new files using PhpStorm and wondered how could you save time by not retyping the namespace constantly? Well did you know about marking folders as different types? Here’s an excerpt from documentation about Content Roots: ”. This can save a tiny bit of your computer resources and minimise the noise you are seeing when searching or looking up by symbol/filename/class. If you have composer integration enabled, recent versions of PhpStorm have the ability to mark Source directories automatically by understanding PSR-0 and PSR-4 paths from composer.json. I find a couple of things very useful for marking directories as source or test. First of all, I can set up proper namespaces for those directories (sometimes in complex projects PhpStorm can’t detect them automatically) which helps me with creating new classes or moving them around - I don’t need to retype them every time. Automation FTW! Additionally, I can set up test directories and have PhpStorm automatically detect where to create a new test (or a new class from a test) when navigating to test/to class. I spend less time navigating in my directory tree and just jump forward/ backwards between a test and the implementation. You can see here how my src directory has a Donis\Phwitch namespace set by default, also PhpStorm ignoring all of the composer dependencies, because they are added in the include path. Save time for new joiners It’s your first day on a job, you got your fresh Macbook out of the box, the credentials in your email and you’re ready to go. Wouldn’t it be awesome if you could submit your first PR by the end of the day and deploy it to production instead of spending that day customising your PhpStorm? I would love this! This could be true if you share your PhpStorm configuration with everyone and commit that .idea directory into VCS. As a newly joined developer, I would love to have necessary inspections set up for different projects, so I can refer to them (which is few keystrokes away) instead of trying to find that documentation link someone mentioned somewhere in a Slack channel and also added that it might be outdated. How terrible is that? And what if that company has more than one repository with different level of codebases you’ll have to work on? That would save days of configuration tinkering, not to mention you’d have to do this all again after your MacBook would break down. Let me give you a different example - you work in a place where you work not only with PHP but also with Node.js, tiny bits of Python and JS for your UI. Those different codebases have different rules and styles to follow. How can you make sure, that you commit and ask to review only the code that follows the rules of that project? For me, the fastest way would be to receive that feedback right inside my PhpStorm (WebStorm or PyCharm) window instead of humans finding them in a PR I submitted. Another addition to your shared configuration might be File and Code Templates. These allow customising how newly created files, code snippets or parts of files look like. For example, don’t like the default comment PhpStorm adds when creating a new PHP file? Just remove it from “Project” scheme and everyone in the future will save a second or two by not constantly removing it. Do you have a specific type of controller that extends or implements something special? Create it as a template, share it and new joiners won’t have to learn by heart how to create it, they can just “Create a new controller” in PhpStorm and be done with it. Every bit that can be automated for newly joined people will help them focus on learning your domain and business instead of learning your toolset. Do you have a custom deployment to the remote server or something similar? This can be also shared with everyone because it will end up in .idea directory! Set up new tools only once If you share PhpStorm configuration, only one developer has to add a new tool configuration into their PhpStorm. Let’s say you have added Behat setup to your project. PhpStorm has a very nice integration with it and you can set up one or more run configurations to easily run all your Behat tests from within PhpStorm. PHPSpec? Jest? Docker? Any of these tools have some kind of configuration, which, if needed, can be customised to suit your needs. I am assuming, you want all of your fellow developers to have the benefit from these new tools and save their time and fuss when setting them up? Imagine the disaster when someone will misconfigure PHPUnit and skip running half of the tests! Run Configuration of all of these tools can be shared with your .idea directory. Note 1 - When creating “Run Configuration” don’t forget to mark “Shared” checkbox, otherwise it won’t end up in .idea. Note 2 - If you use a lot of external tools, this might not help you, looks like they can’t be shared between projects. Allow different projects with unique configurations If you’re working on multiple projects - I guess not all of them are equal. Perhaps one is written in some old custom framework, another one is using Symfony 4? For sure they will need different inspections, run different tools and have different scopes. If you have your PhpStorm configured to your liking or generic company guidelines, the amount of noise and frustration will soon teach your brain to ignore all the warnings and notices PhpStorm is reporting to you, since both of those projects can’t fit into just one configuration. Blindly ignoring problems reported from PhpStorm is probably one of worst things that can happen to a developer Why are you paying for the tool and ignoring it then? Those problems will be caught, but by a human instead of a machine, which in my opinion is much more costly. By sharing .idea directory with customised configuration for each project, you’ll keep following the guidelines specific to that project, not necessarily only the generic ones. At the same time, it gives some room for experimentation of new or different tools in smaller projects, perhaps a different code style standard, different testing framework. And flexibility is the key, right? You will also be able to easily contribute to projects of other teams without learning how their project is set up, you’ll receive all the needed feedback from within PhpStorm. Quick start If you’re working with a small team or just by yourself you can just use the default official .gitignore from GitHub. This is crafted based on this knowledge base article by JetBrains. This will exclude sensitive information like data source info (database connections), user-specific files, like workspace setup, tasks, and dictionaries (if you do have specific dictionaries for your project, definitely add them!). Also, some plugin settings, build outputs and others that are deemed not needed to be shared with the project. If you have a larger group - start by discussing how PhpStorm can help you guys in your situation. Code style? Default inspections? Maybe just scopes? Pick a few volounteers and let them checkout a branch with .idea commited inside, see how they transition or if they have any feedback. Some considerations & quirks If you see that some of your configuration settings didn’t end up inside of .idea folder - make sure you have created a “Shared” setting! Sometimes these are easily missed. Also, they have a different name in some cases (code style, inspections) and they should be set to “Stored in Project”. Settings which are marked “For current project” will also end up inside of .idea. PhpStorm takes time to show you the changes inside of .idea folder inside of “Version control” window. You might want to click “Refresh VCS changes” to update the list and you’ll see the updated files. Some of the files are updated quite often. In PhpStorm’s case - *.iml and php.xml are the most ones updated because they contain the list of all composer dependencies (since they’re added as libraries by default). They are either forgotten to commit (didn’t see the change) or are outdated if a developer forgot to run composer install. This might be fixed in the future PhpStorm versions, but keep an eye on that, especially when composer packages have changed. Not completely all of the settings can be shared. For example - user created live templates can’t be shared (must be deemed too personal). Conclusion PhpStorm is a beast 🐻! It has so much functionality, but sometimes we use it only as a text editor, not an IDE. I hope you are going to start sharing your PhpStorm configuration with everyone inside your company/team too! Please let me know in the comments below if you’ve learned something new from this or if I can update this article in any way or if you have just any feedback. In the next post related to PhpStorm, I will dive deeper into some of the files that are contained inside of shared .idea directory and explain what they’re responsible for, so you can fine-tune your setup of what are you adding into VCS and what not. Thanks for reading & happy coding! P. S. I’m not a native English speaker, nor I am a good writer. If you seem some mistakes or improvements, please let me know! Discussion (1) I was so mad on the missing Code Style settings on my project, for years, that I ended up writing a small tip post on the subject. I see you also noted that on your quirks section! Ha! Hope they make this a bit simpler (like the rest of the settings which are "shared") soon :)
https://dev.to/donis/the-benefits-of-versioning-phpstorm-configuration-29bm
CC-MAIN-2021-31
refinedweb
3,258
60.85
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 André, On 8/10/2010 5:31 PM, André Warnier wrote: > It is just that 3000 MB is *a lot* of bytes (3,145,728,000 of them). Yup. 3000MiB is even bigger (3,221,225,472 of them), and what you'll get from the JVM. (See below) > Which means that each time one of these users hits the system, > Tomcat would need to read and load 1 MB of data just to retrieve > this user's previous session data, without even having done anything > yet for this user and his present request. Maybe, but maybe not: the Java heap is usually entirely in memory, so in-memory session data is very quickly accessed (or ignored, depending on how the request is handled). There is no penalty for loading this session data in this case. Unless otherwise configured, all session data stays in-memory during the lifetime of the context. This isn't like PHP (or Perl?) where the sessions are serialized every time a request completes and de-serialized when a request begins (and the session data must be fetched). In the case where the session data is stored on disk or in a database, the penalty for accessing data is highly dependent upon the strategy for storage and retrieval: if the entire session must be fetched from storage unconditionally, then yes, it is a giant waste of time if that data is not used every time. Heck, it's a giant waste of time no matter what. On the other hand, if session attributes are stored and accessed individually, one may be able to get away with little to no overhead for session attributes that one actually uses (and no overhead if the session is not used). > One may wonder how fast this server is expected to be, if it handles > 3,000 user sessions simultaneously ? 3000 sessions isn't really that crazy when you think about it. 3000 simultaneous requests might be a bit heavy on a single, modest server. > So let's say that I am just curious as to what the application is. Agreed. > Where I do object : > > Christopher Schultz wrote: ... >> >> 2. Caches. This may be something that is often not considered for a >> Perl hacker such as yourself, where webapps tend to be scripts that >> run once and then terminate. > > Wrong. I am also a mod_perl hacker. In a mod_perl environment, > scripts (or handlers) do not "terminate", and memory is not recycled > (this is even an inconvenient of mod_perl, and something to watch > when designing mod_perl applications). Apologies. I was thinking the .cgi-style scripts that I'm pretty sure /do/ terminate. Use of mod_perl is outside the scope of my argument :) > A secondary motive for my question to the OP, was to find out > whether this size was really the result of a rational calculation > (or experience), or just some number plucked out of the air. RAM > prices are fickle, but let's say that for server-quality RAM, one > currently pays 25 US$ per GB. And we do not know who the OP works > for, but say he is talking about 1,000 Tomcat servers. That's 3TiB of RAM. Sweet. > Saving 1 GB of > Heap to run his applications would thus mean saving 25,000 US$. I > believe it is worth asking the question. Agreed. - -chris N.B. I was unable to get a predictable maximum heap size when running with -Xmx: public class MemoryInfo { public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); System.out.printf("total=%10db (%4dMiB)", rt.totalMemory(), (rt.totalMemory() / (1024*1024))); System.out.println(); System.out.printf(" max=%10db (%4dMiB)", rt.maxMemory(), (rt.maxMemory() / (1024*1024))); System.out.println(); System.out.printf(" free=%10db (%4dMiB)", rt.freeMemory(), (rt.freeMemory() / (1024*1024))); System.out.println(); } } $ java -Xmx10M MemoryInfo total= 9961472b ( 9MiB) max= 9961472b ( 9MiB) free= 9731320b ( 9MiB) Note that 9437184 (1024 * 1024 * 9) < 9961472, so I'm not sure why the extra memory. The code above doesn't necessarily get /only/ heap memory, but you get an extra 5% for some reason. $ java -Xmx100M MemoryInfo total= 64356352b ( 61MiB) max= 93257728b ( 88MiB) free= 64019480b ( 61MiB) That's weird: the JVM gives me less than I requested this time: only 88% of what I requested. $ java -showversion -Xmx1000M MemoryInfo java version "1.6.0_20" Java(TM) SE Runtime Environment (build 1.6.0_20-b02) Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode) total= 64356352b ( 61MiB) max= 932118528b ( 888MiB) free= 64019480b ( 61MiB) ... and again: less than I requested. Odd. Even when I use 1MB = 1024 * 1000, I'm still being stiffed by the JVM. - -chris -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (MingW32) Comment: Using GnuPG with Mozilla - iEYEARECAAYFAkxhztUACgkQ9CaO5/Lv0PAXeACeP4uhSfDmw/GedynYNMvBqKUY YdcAn09WBlQS8e16CUjo/wQQy+jqMP7x =ENGs -----END PGP SIGNATURE----- --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org For additional commands, e-mail: users-help@tomcat.apache.org
http://mail-archives.apache.org/mod_mbox/tomcat-users/201008.mbox/%3C4C61CED5.1060201@christopherschultz.net%3E
CC-MAIN-2014-23
refinedweb
819
63.7
: Hi! I tried to write the second exercise without bool like this and it works for numbers with 10 digits, but for the bigger numbers it outputs only "You entered an even number". Can you please explain whats wrong with it? If you input a number that’s too large, you’ll overflow integer variable x and the value won’t be what you expect. If you print the value of x, you should be able to see this happening. I guess I overcomplicated mine a bit, but I like having separate functions. Hi; please tell me what’s wrong with my writeAnswer() function. isEven evaluates correctly, but writeAnswer thinks evertything is even, even when isEven returns false. I have a feeling I’m being really dumb and not seeing something simple. functions.h functions.cpp source.cpp This will always evaluate to true. This says, “if the isEven function has an address greater than 0” (which will be always if the isEven function exists). Here’s what you wanted: This says, “if the return value of the isEven function is true”, which is what you actually wanted. Tried this previously and got the compile error “function does not take 0 arguements”. Oh, you need to pass function isEven() an argument: Also tried that but compiler says "identifier "x" is undefined" (using visual studio) That’s because your writeAnswer() function is missing parameter x, which should be passed in from main(). Hi Alex. Thanks for the great tutorials. I have a few doubts. 1) In this piece of code: You’ve used the same name for a function and a variable in it. Doesn’t that cause a naming conflict? 2) Here, can’t we do instead of 1) No. The local variable name shadows the function name. We discuss shadowing in chapter 4. 2) No. That does integer division on x / y and then casts the result to a double. We want to do double division, which means at least one of the operands must be a double before the division operation takes place. Got it, thanks! it would be less confusing if the hint in quiz #2 linked to section 2.6 instead 2.7 Agreed. Thanks for pointing this out! After reading this multiple times, I still have no idea how the modulus (remainder) works. Could you explain it differently or post a link that explains it in depth? EDIT: Even though I’m not quite understanding the modulus, I managed to complete the second quiz haha 😀 [code]#include using namespace std; bool isEven(int number) { if (number % 2 == 0) return true; else return false; } int main() { cout <> number; if (isEven(number)) cout << number << " is even.n"; else cout << number << " is odd.n"; return 0; }[code] Modulus is just another name for the remainder left over after doing an integer division. So, 7 / 4 = 1, because the fraction is dropped. 7 % 4 = 3, because 7 / 4 is 1, leaving a remainder of 3. That 3 is the result of the modulus. The output was 1 when val was equal to 9. Can you explain me how? 1/2 does integer division and results in 0 (1/2 is 0.5, but integer division drops the fractional portion, so you’re left with 0). Any number to the 0th power is 1. You probably meant to do 1.0/2.0 instead of 1/2, so you get floating point division. Why can’t we use integers in the place of chars? To do what? I’m not clear on the context of your question. In every case. Chars serve the same purpose as that of integers. So, why not use int. They don’t serve the same purpose. * Chars are only 8-bits, where integers are minimum 16 bits. * Chars print as ASCII characters, whereas integers print as numbers. * Strings contain chars, not integers. Well this was my first attempt at question 2, but I think I missed the point about having a function return true 😛 great tutorial again! Couldn’t the isEven function be simplified further? bool isEven(int x) { return (x % 2); } It still returns the correct true/false information. It could be simplified to the following: Why This? Can you explain me, please! If x is even, then x % 2 = 0, which the ! flips to a 1, which becomes boolean true. If x is odd, then x % 2 = 1, which the ! flips to a 0, which becomes boolean false. Hi Alex and I thanks you for your reply, but: It seems like i the function below !(x % 2) evaluates to 1 as function return value. Consequently By default, a bool function return 0(false) while I think the opposite Enlighten me, please! I’m not sure I follow. !(x % 2) only evaluates to 1 if x is even. For integer to boolean conversions, 0 becomes false, and any non-zero values becomes true. Excuse me, I wanted to mean why compilers interpret to implicitly? I’m sorry, I don’t understand what you’re asking. Hi Alex, here’s a code, can you tell me if the code is pretty , a good code factorized and commented if no, how do I do for ameliorating it? main() and continueOrStop() are pretty redundant -- you could consolidate them. I’d also put the comments on the actual functions rather than the forward declarations. Other than that, I don’t see anything particularly noteworthy. Name (required) Website
http://www.learncpp.com/cpp-tutorial/32-arithmetic-operators/comment-page-2/
CC-MAIN-2018-05
refinedweb
909
76.42
Okay, I confess to never having gotten around to testing beta3. :( So I am just now dealing with the "final" way of handling namespaces, particularly with namespaced antlibs. I have custom tasks that take nested elements of "normal" Ant types such as fileset... pretty common, of course. Now, adding my antlib's namespace to <fileset> or <mapper> i.e. <mylib:fileset>, <mylib:mapper> seems to work but is counterintuitive to my eye. Is it an accident that this works? Should I be using Ant's default/core namespace? What is that? I know I've seen some messages that alluded to it but I can't find them now in the archives... -Matt __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
https://mail-archives.eu.apache.org/mod_mbox/ant-dev/200312.mbox/%3C20031219231648.96948.qmail@web20420.mail.yahoo.com%3E
CC-MAIN-2021-39
refinedweb
143
70.9
How do we or can we use node modules via npm with Meteor? Or is that something that will be dependent on the packaging API? Or is there a prescribed method that is recommended? Note that this answer applies to versions of Meteor prior to 0.6.0, which was released in April 2013 and added direct npmintegration Install modules as you normally would through npm and then use var require = __meteor_bootstrap__.require, pd = require("pd"), after = require("after") // etc Load any modules you want I did a complete write-up on this on Meteorpedia: The article covers how to use npm in both your app and/or packages, and common patterns for wrapping regular callbacks and event emmitter callbacks to work properly in Meteor and Fibers, and include's references to Arunoda's async-utilities and additional resources. I wrote a Gist on how to do this as of Meteor 0.6.5, How to add Node.js npms to your Meteor.js project. I am using such a script which nicely install all Node.js dependencies. It behaves similar to the official support in the Meteor engine branch (it installs dependencies at runtime), but it also supports installing from Git repositories and similar goodies. Meteor 1.3, released on March 28, 2016, gives apps full ES6 (ES2015) modules support and out of the box NPM support. Apps and packages can now load NPM modules directly and easily on the client and on the server. If you can use 1.3, then check. For example, to use moment.js: meteor npm install --save moment Then in your code: import moment from 'moment'; // this is equivalent to the standard node require: const moment = require('moment'); If you need to use an older version of Meteor, read the rest of the answer below. Pre-Meteor 1.3: Since v0.6.0, Meteor integrates directly with NPM modules with the help of a 3rd party package. For example, to use a module like ws, sudo npm install -g ws(or for local installs, see this) In your sever JavaScript file, var Websocket = Npm.require('ws'); var myws = new Websocket('url'); To use a core Node module, just make the corresponding Npm.require() call, e.g. var Readable = Npm.require('stream').Readable. You can use any of the more than 230,000 NPM modules directly with Meteor thanks to the NPM package developed by Arunoda. You can also define dependencies on Npm packages from smart packages - from the initial announcement of npm support: Your smart package can now define dependencies directly, by adding a call to Npm.depends in package.js: Npm.depends({ "awssum": "0.12.2", "underscore.string": "2.3.1" }); All of this works well with hot code reload, just like the rest of Meteor. When you make changes, the bundler will automatically download missing npm packages and re-pin its dependencies. To use an NPM module within server code, use Npm.require as you would normally use plain require. Notably, __meteor_bootstrap__.require has been eliminated and all of its uses have been converted to Npm.require. There is a small example of using an NPM module in your application. You could use the Meteor Npm package meteor add meteorhacks:npm Then create a packages.json file in your project's root directory with the NPM module's info. { "redis": "0.8.2", "github": "0.1.8" } Then as simple as (server side) var github = Meteor.npmRequire("github"); var redis = Meteor.npmRequire("redis"); So you just use Meteor.npmRequire instead of require
https://javascriptinfo.com/view/53577/how-do-we-or-can-we-use-node-modules-via-npm-with-meteor
CC-MAIN-2020-50
refinedweb
591
57.98
This is your resource to discuss support topics with your peers, and learn from each other. 11-07-2010 06:01 PM - edited 11-07-2010 06:08 PM import com.gskinner.GTween. Again BB SDK is not a special version of AIR, it is simply AIR 2.5 which runs the standard Flash runtime. QNX has added a few pure AS3 components, that's about it. Forget about the mx transition **bleep**, they are just proxies for a true tween engine. You can tween any property of any display object..anything on the stage, flex or not, is just a display object at heart. 11-07-2010 06:29 PM Thanks, I will give the 3rd party library a shot since effects are natively supported yet. (). Not all of 2.5 is supported in the BB SDK. Maybe just the flash.* namespace, but not all components in the spark.* or mx.* namespace are supported. For example, spark.components.Button, will not compile, you have to use the qnx button control. 11-07-2010 07:52 PM Spark button compiles fine over here using command line... To answer the original question, Flash is not multithreaded so it can't emulate those Java API's, but you can use setTimeout(), setInterval() or Timer API's to do what you need. Also, most tween libraries support a delay timer, so it might be easiest to just create all your animations at one, setting the delay's progressivley.
https://supportforums.blackberry.com/t5/Adobe-AIR-Development/How-can-I-make-a-sleep-function-work-in-Actionscript-on-the/m-p/631557
CC-MAIN-2016-50
refinedweb
245
76.62
NAME Create an IO port. SYNOPSIS #include <zircon/syscalls.h> zx_status_t zx_port_create(uint32_t options, zx_handle_t* out); DESCRIPTION zx_port_create() creates a port: a waitable object that can be used to read packets queued by kernel or by user-mode. If you need this port to be bound to an interrupt, pass ZX_PORT_BIND_TO_INTERRUPT to options, otherwise it should be 0. In the case where a port is bound to an interrupt, the interrupt packets are delivered via a dedicated queue on ports and are higher priority than other non-interrupt packets. The returned handle will have: ZX_RIGHT_TRANSFER: allowing them to be sent to another process through zx_channel_write(). ZX_RIGHT_WRITE: allowing packets to be queued. ZX_RIGHT_READ: allowing packets to be read. ZX_RIGHT_DUPLICATE: allowing them to be duplicated. RIGHTS TODO(ZX-2399) RETURN VALUE zx_port_create() returns ZX_OK and a valid IO port handle via out on success. In the event of failure, an error value is returned. ERRORS ZX_ERR_INVALID_ARGS options has an invalid value, or out is an invalid pointer or NULL. ZX_ERR_NO_MEMORY Failure due to lack of memory. There is no good way for userspace to handle this (unlikely) error. In a future builds this error will no longer occur.
https://fuchsia.dev/fuchsia-src/reference/syscalls/port_create
CC-MAIN-2020-29
refinedweb
196
58.69
userlog(3c) Name userlog() - write a message to the BEA Tuxedo system central event log Synopsis #include "userlog.h" extern char *proc_name; int userlog (format [ ,arg] . . .) char *format; Description userlog() accepts a printf(3S) style format specification, with a fixed output file-the BEA Tuxedo system central event log. The central event log is an ordinary UNIX file whose pathname is composed as follows: If the shell variable ULOGPFX is set, its value is used as the prefix for the filename. If ULOGPFX is not set, ULOG is used. The prefix is determined the first time userlog() is called. Each time userlog() is called the date is determined, and the month, day, and year are concatenated to the prefix as mmddyy to set the name for the file. The first time a process writes to the userlog, it first writes an additional message indicating the associated BEA Tuxedo system version. The message is then appended to the file. With this scheme, processes that call userlog() on successive days will write into different files. Messages are appended to the log file with a tag made up of the time (hhmmss), system name, process name, and process ID, thread ID, and context ID of the calling process. The tag is terminated with a colon (:). The name of the process is taken from the pathname of the external variable proc_name. If proc_name has value NULL, the printed name is set to ?proc. BEA Tuxedo system-generated error messages in the log file are prefixed by a unique identification string of the form: <catalog>:number>: This string gives the name of the internationalized catalog containing the message string, plus the message number. By convention, BEA Tuxedo system-generated error messages are used only once, so the string uniquely identifies a location in the source code. If the last character of the format specification is not a newline character, userlog() appends one. If the first character of the shell variable ULOGDEBUG is 1 or y, the message sent to userlog() is also written to the standard error of the calling process, using the fprintf(3S) function. userlog() is used by the BEA Tuxedo system to record a variety of events. The userlog mechanism is entirely independent of any database transaction logging mechanism. A thread in a multithreaded application may issue a call to userlog() while running in any context state, including TPINVALIDCONTEXT. Portability The userlog() interface is supported on UNIX and MS-DOS operating systems. The system name produced as part of the log message is not available on MS-DOS systems; therefore, the value PC is used as the system name for MS-DOS systems. Examples If the variable ULOGPFX is set to /application/logs/log and if the first call to userlog() occurred on 9/7/90, the log file created is named /application/logs/log.090790. If the call: userlog("UNKNOWN USER '%s' (UID=%d)", usrname, UID); is made at 4:22:14pm on the UNIX System file named m1 by the sec program, whose process-id is 23431, and the variable usrname contains the string "sxx", and the variable UID contains the integer 123, the following line appears in the log file: 162214.m1!sec.23431: UNKNOWN USER 'sxx' (UID=123) If the message is sent to the central event log while the process is in transaction mode, the user log entry has additional components in the tag. These components consist of the literal gtrid followed by three long hexadecimal integers. The integers uniquely identify the global transaction and make up what is referred to as the global transaction identifier. This identifier is used mainly for administrative purposes, but it does make an appearance in the tag that prefixes the messages in the central event log. If the foregoing message is written to the central event log in transaction mode, the resulting log entry will look like this: 162214.logsys!security.23431: gtrid x2 x24e1b803 x239: UNKNOWN USER 'sxx' (UID=123) If the shell variable ULOGDEBUG has a value of y, the log message is also written to the standard error of the program named security. Errors userlog() hangs if the message sent to it is larger than BUFSIZ as defined in stdio.h Diagnostics userlog() returns the number of characters output, or a negative value if an output error was encountered. Output errors include the inability to open, or write to the current log file. Inability to write to the standard error, when ULOGDEBUG is set, is not considered an error. Notices It is recommended that applications' use of userlog() messages be limited to messages that can be used to help debug application errors; flooding the log with incidental information can make it hard to spot actual errors. See Also printf(3S) in a UNIX system reference manual
https://docs.oracle.com/cd/E13203_01/tuxedo/tux71/html/rf3c99.htm
CC-MAIN-2021-49
refinedweb
798
58.92
Follow-up Comment #31, bug #54572 (project octave): Works here. This __signbit() function. Wouldn't it give better chance of optimization as an "inline"? Or am I missing something here in the fact that the instantiation of the int64_t integer type uses "inline"? Also, in C/C++ doesn't the standard ensure the following // Returns 1 for negative number, 0 otherwise. static T __signbit (T x) { return (x < 0); } is sufficient (or perhaps a cast to T is needed. Sure the optimizing compiler will probably figure that out have the same code, but still. Also, the signum routine: +verbatun+ static T signum (T x) { // With modest optimizations, this will compile without a jump. return ((x > 0) ? 1 : 0) - __signbit (x); } Why even call the __signbit routine? And garden-variety optimization would still do two comparisons with the above, x > 0 and x < 0 because of the subtraction operator. How about: return ((x < 0) ? -1 : (x > 0)); which on average might cut the comparisons to 1.5. Or, one could make the argument that the more prevalent case is someone having mostly x > 0, so "return ((x > 0) ? 1 : (x == 0) ? 0 : -1)" would work. The thing about avoiding the use of addition and subtraction is that sometimes the processor could have an instruction that loads a value into a register where that value is encoded as part of the instruction and not coming from a separate register which would need an additional load. Here's a changeset you can pick and choose from or disregard. (file #44897) _______________________________________________________ Additional Item Attachment: File name: octave-inline_some_int_arithmetic-djs2018aug29.patch Size:3 KB _______________________________________________________ Reply to this item at: <> _______________________________________________ Message sent via Savannah
https://lists.gnu.org/archive/html/octave-bug-tracker/2018-08/msg00680.html
CC-MAIN-2019-35
refinedweb
281
66.23
Working with a LED strip The following applies to image version 0.18 and up. See previous version of the article for older images. Clever drone kits contain addressable LED strips based on ws281x drivers. Each LED may be set to any one of 16 million possible colors (each color is encoded by a 24-bit number). This allows making the Clever flight more spectacular, as well as show flight modes, display stages of current user program, and notify the pilot of other events. Our Raspberry Pi image contains preinstalled modules for interfacing with the LED strip. They allow the user to: - manage LED strip effects and animations (high-level control); - control individual LED colors (low-level control); - configure the strip to display flight events. LED strip can consume a lot of power! Powering it from a Raspyerry Pi may overload the computer's power circuitry. Consider using a separate BEC as a power source. High-level control - Connect the +5v and GND leads of your LED to a power source and the DIN (data in) lead to GPIO21. Consult the assembly instructions for details. Enable LED strip support in ~/catkin_ws/src/clever/clever/launch/clever.launch: <arg name="led" default="true"/> Configure the ws281x parameters in ~/catkin_ws/src/clever/clever/launch/led.launch. Change the number of addressable LEDs and the GPIO pin used for control to match your configuration: <param name="led_count" value="30"/> <!-- Number of LEDs in the strip --> <param name="gpio_pin" value="21"/> <!-- GPIO data pin --> High-level interface allows changing current effect (or animation) on the strip. It is exposed as the /led/set_effect service. It has the following arguments: effectis the name of requested effect. r, g, bare RGB components of effect color. Each component is an integer in a 0 to 255 range. Currently available effects are: fill(or an empty string) fills the whole strip with the requested color; blinkturns the strip on and off, setting it to the requested color; blink_fastis the same, but faster; fadefades smoothly to the requested color; wipefills the strip with the requested color one LED at a time; flashblinks twice and returns to the previous effect; rainbowcreates a rainbow-like shifting effect; rainbow_fillcycles the strip through rainbow colors, filling the whole strip with the same color. Python example: import rospy from clever.srv import SetLEDEffect # ... set_effect = rospy.ServiceProxy('led/set_effect', SetLEDEffect) # define proxy to ROS-service # .. set_effect(r=255, g=0, b=0) # fill strip with red color rospy.sleep(2) set_effect(r=0, g=100, b=0) # fill strip with green color rospy.sleep(2) set_effect(effect='fade', r=0, g=0, b=255) # fade to blue color rospy.sleep(2) set_effect(effect='flash', r=255, g=0, b=0) # flash twice with red color rospy.sleep(5) set_effect(effect='blink', r=255, g=255, b=255) # blink with white color rospy.sleep(5) set_effect(effect='rainbow') # show rainbow You can also set colors from your Bash shell: rosservice call /led/set_effect "{effect: 'fade', r: 0, g: 0, b: 255}" rosservice call /led/set_effect "{effect: 'rainbow'}" Configuring event visualizations It is possible to display current flight controller status and notify the user about some events with the LED strip. This is configured in the ~/catkin_ws/src/clever/clever/launch/led.launch file in the events effects table section. Here is a sample configuration: startup: { r: 255, g: 255, b: 255 } connected: { effect: rainbow } disconnected: { effect: blink, r: 255, g: 50, b: 50 } <!-- ... --> The left part is one of the possible events that the strip reacts to. The right part contains the effect description that you want to execute for this event. Here is the list of supported events: startup– Clever system startup; connected– successful connection to the flight controller; disconnected– connection to the flight controller lost; armed– flight controller transitioned to armed state; disarmed– flight controller transitioned to disarmed state; stabilized, acro, rattitude, altctl, posctl, offboard, mission, rtl, land– transition to said flight mode; error– an error occured in one of ROS nodes or in the flight controller (ERROR message in /rosout); low_battery– low battery (threshold is set in the thresholdparameter). You need to calibrate the power sensor for the low_batteryevent to work properly. In order to disable LED strip notifications set led_notify argument in ~/catkin_ws/src/clever/clever/launch/led.launch to false: <arg name="led_notify" default="false"/> Low-level control You can use the /led/set_leds ROS service to control individual LEDs. It accepts an array of LED indices and desired colors. Python example: import rospy from led_msgs.srv import SetLEDs from led_msgs.msg import LEDStateArray, LEDState # ... set_leds = rospy.ServiceProxy('led/set_leds', SetLEDs) # define proxy to ROS service # ... # switch LEDs number 0, 1 and 2 to red, green and blue color: set_leds([LEDState(0, 255, 0, 0), LEDState(1, 0, 255, 0), LEDState(2, 0, 0, 255)]) You can also use this service from the your Bash shell: rosservice call /led/set_leds "leds: - index: 0 r: 50 g: 100 b: 200" Current LED strip state is published in the /led/state ROS topic. You can view the contents of this topic from your Bash shell: rostopic echo /led/state
https://clever.coex.tech/en/leds.html
CC-MAIN-2020-05
refinedweb
856
55.44
[solved] XmlListModel parse local xml file @ XmlListModel { id: xmlModel source:"local.xml" query: "/feed/entry" namespaceDeclarations: "declare default element namespace '';" XmlRole { name: "title"; query: "content/string()"} } Component { id: xmlModelDelegate Text { width: 350 text: title wrapMode:Text.Wrap } } ListView { id:parseHtmlListview width: parent.width height: parent.height - 40 clip: true model: xmlModel delegate: xmlModelDelegate } //local.xml such as follow <feed> <entry> <content type="html"> <div id="Intro"><p>Hello World.</p> ></div> </content> </entry> </feed> @ hi, when i use XmlListModel parse loacl xml file, i can't get data, please help me, thanks~~~ I guess you have correct namespace in xml (code-tags seems to remove the namespace...) If you want hello world text: @XmlListModel { ... XmlRole { name: "title"; query: "content/div/p/string()"} }@ Hi Diph, Thanks for your reply. I am sorry i did't describe the problem exactly. I can phase the xml file when it is in server. But after i downloaded it from server to my computer, I can't phase it from local. As the same file content, I don't know why it doesn't work. Do u have any idea about this? [quote author="Diph" date="1313584756"]I guess you have correct namespace in xml (code-tags seems to remove the namespace...) If you want hello world text: @XmlListModel { ... XmlRole { name: "title"; query: "content/div/p/string()"} }@[/quote] - DenisKormalev Maybe it is located in another place? Not where qml looks for it? Maybe you can set your own QNetworkAccessManager which uses cache? the problem have been resolved. encoding caused the problem. the file must be unicode format. thanks for all your reply.
https://forum.qt.io/topic/8663/solved-xmllistmodel-parse-local-xml-file
CC-MAIN-2018-26
refinedweb
267
61.02
In February I did a blog post called My "First Look at Orcas" Presentation. It provided a good summary of some of the cool web development features coming with Visual Studio "Orcas". If you haven't had a chance to read it, I recommend checking it out here. Javascript intellisense will be a God send! I dont know if this is the right place to ask, but seems as good as any, but is there any documentation for the JavaScriptCommentStripper.dll that ships with the AJAX Control Toolkit? I can't seem to find any anywhere! :( This is nice...really nice! I was awaiting for this feature. Between this and LINQ to SQL I seriously can not wait for this upgrade. Nice work! wow, Thats a really Herculean effort by the orcas team Finally I won't have to use a second editor just to write my JavaScript. I've been waiting patiently for this. Scott, Any ideas as to when Orcas B1 will be available for those of us without MSDN subs? Thanks for your time. Really Excelent!!!! :) Typically, I found out how to include the JavascriptCommentStripper in a build process after posting... <UsingTask AssemblyFile="..\Support\JavaScriptCommentStripper.dll" TaskName="JavaScriptCommentStripperTask" /> <Target Name="AfterBuild"> <JavaScriptCommentStripperTask SourceFiles="$(Configuration)\scripts\ForgottenPassword.js" DestinationFiles="$(Configuration)\scripts\ForgottenPassword.js"></JavaScriptCommentStripperTask> etc... </Target> Typical! :) FINALLY! I hope it works well enough when assigning variables as well, for example var obj = document.getElementById('test') in previous releases intellisense would not work after obj. but would work if typing document.getElementById('test'). thanks! Reading through the WebDevTools' "JavaScript Intellisense in Visual Studio Orcas" post linked to above, several people ask about Intellisense support for external Javascript libs. Ayende re-iterates the question but the only reply is along the "let us know what you want" lines. The ability to support external Javascript libraries would be a huge plus for Orcas... in another arena I might even go so far to call it a "Killer Feature" of the IDE. So, my question is - who (and where) do we contact to with our list of "must support" libraries? Should we use the MS Connection site? Oh... and as usual - solid work and thanks for keeping us informed. finally, some intellisense for JS :-D but will they have the background compiling lag? please make sure you get all that performance thing fixed before release. Hi Steve, I know the team has been testing out Prototype and Dojo with the Javascript Intellisense feature. Prototype works reasonably well with Beta1 - the only challange with it is that it uses dynamic methods/constructors in a few places (meaning code executes somewhere to dynamically add these members to the object at runtime). This makes it pretty tricky/impossible for a tool to infer the Intellisense for these members without sometype of documentation hints file. Bertrand is now on the OpenAjax group (see this post for details:). One of the things the group is talking about right now is ways to standardize doc comments for tools to further help with Intellisense. If the group gets to consensus on this, then we'll be able to have a common format that all AJAX libraries will implement, in which case VS should be able to provide full Intellisense for every AJAX library (regardless of any dynamic member code generation they do). Thanks for the update Scott - now let's just hope the OpenAjax group can come to a consensus in time for the results to make it into Orcas. :) Uh, didn't Visual Interdev 6.0 from 1999-2000 contain this feature? Add it was removed for .Net. I tried the javascript intellisense on a simple javascript custom object that has one property and one method. I can't get the intellisense to work at all. Is there something else in VS Orcas that needs to be configured in order for this to work? About standardizing on doc format, what about JSDOC? It was there (here actually:) for the taking, so why didn't you take it? Was it NIH? How to you get intellisense on a simple custom javascript object? I can't get it to work. Hi: You can read this post in spanish. Responding to person who thinks MSDN subscribers only has access: Visual Studio Orcas Beta 1 is available to anyone. Josh A MSDN Subscriber Orcas is looking really nice. Between this, the AJAX Library and LINQ I am really looking forward to the new release. Besides the intellisense, being able to place javascript breakpoints right in VS will be very nice. Hi Stephen, Visual Interdev had intellisense against known objects (like html elements), but not against arbitrary Javascript or against Javascript functions you added yourself. The support in VS Orcas goes much, much farther than this. Thanks, Hi jsp3536, If you can send me a sample that isn't working for you with Beta1 of "Orcas", I can loop you in with someone on the team to investigate. Regarding the Intellisense seemingly not working, I had the same issue when I tried it using a 'Web Application' project. Then I tried it using a 'Web Site' file system based web application, and that seemed to convince it to work as advertised... I have not had a chance to download the beta yet, but I really hope the new editor supports collapsible sections within javascript code. I wouldn't even mind having to use some specific comment lines to get it to work (like #region in c#). Also, a list of the objects/functions within the .js file would really help as well in order to jump within the file faster. Maybe it already has these in it... Something people like me (ASP.NET developers and early AJAX birds) really needed to become comfortable with MS AJAX JavaScript. Keep up the good work. Mike, re "JSDOC" - I've had a quick browse through the spec but I guess the biggest issue is explained by the linked article () as JSDOC seems to put comments outside functions which means they're not thus available at runtime. Of course, I could be wrong - it has been known to happen! ;) Hey Scott, great stuff over there, looks like we'll need nothing but Visual Studio ! Will you write about projections ? It's freaking amazing stuff, I'd like to read more about it. thx ! -- Anderson Fantastic, an IDE with intellisense support for javascript is a dream come true. You guys seam to be moving in the right dxn lately !! I always frustrated when have to write some typical JavaScript, but my life is going to easy with this great enhancement. I hope it will improve my productivity. I've been using Aptana (a free utility) which provides intellinse for Javascript. Having it in Orcas sounds great. It will be nice to have everything under the one IDE! Hi Scott, Does orca beta 1 (or next versions? ) suppose to support intellisence for ASP.NET AJAX namespaces, classes and interfaces ? Hi Dan, Yes - Beta1 supports intellisense for the ASP.NET AJAX namespaces, classes and interfaces. If the entire JS object model is available and if it identifies all the aspx form elements with TypeAHead feature that will be great? What about defacto code snippets like the one visual studio? Is there any more advances in debugging the Javascript code in ORCAS? I stay bit relactuant on promises made until I try it out. Look forward for more posts. First of all, the JavaScript support in Orcas is _amazing_. I'm currently looking into how to use Orcas for Gadget development. If I've understood correctly you can add "references" like this (both to JS files, and assemblies). /// <reference path="Library.js" /> Is there a way to get intellisense support for the Windows Vista Sidebar Object Model when writing Sidebar gadgets? That would just be totally awsome! Best regards, Jonas Follesø Second batch of feedback: I just read through the JavaScript article in the May issue of MSDN Magazine. Excellent article on OOP in BLOCKED SCRIPT How ever, I can't the "true" intellisense for none of the examples. For instance:"); If i go new MSDNMagNS, i can't see Examples. The same is true for the other examples. I can see the objects, but not the methods. Microsoft Regional Director, Norway I bumped into this error when I tried to do a Release Mode compile of the Ajax Control Toolkit project Does anyone know if the new Javascript intellisense will support old-school COM/ActiveX type introspection as Visual InterDev did? Pingback from My Learning Todo List « Spontaneous Publicity Lazy Blog Entry Visual Studio 2008 (Codname ORCA) has intorduced a new feature to aid with Web development, official I am simply amazed at the JavaScript debugging with Visual Studio 2008. The really cool part is that Pingback from 20 AJAX and CSS Tips
http://weblogs.asp.net/scottgu/archive/2007/04/24/javascript-intellisense-in-visual-studio-orcas.aspx
crawl-002
refinedweb
1,474
65.42
Produce a program that reports whether or not an input integer is odd or even. <? // generate a random number $number = mt_rand(1, 100); // divide the number by two and see if anything is left // if so, it must be an odd number, because even numbers can always be divided by two perfectly if ($number % 2) // show that the number is odd echo $number . ' is odd.'; else // show that the number is even echo $number . ' is even.'; ?> Which produces: 35 is odd. Here's a c++ solution: #include <iostream.h> int main () { int i; cout << "Type a number or 0 to exit\n>"; cin >> i; if (i%2) cout << "That number is odd.\n"; else cout << "That number is even.\n"; return 0; }
http://iceyboard.no-ip.org/projects/littleredbook/4/1
CC-MAIN-2018-26
refinedweb
122
82.24
I was wondering how to call the "press any key to continue" display in c++ using visual c++. This is a discussion on Press any key within the C++ Programming forums, part of the General Programming Boards category; I was wondering how to call the "press any key to continue" display in c++ using visual c++.... I was wondering how to call the "press any key to continue" display in c++ using visual c++. in a console application, you can do #include <stdlib.h> system("pause"); or, a little more drawn out, but useful if the above code doesnt work: #include <iostream.h> int x; cout << "Press any key to continue..."; cin >> x; I came up with a cool phrase to put down here, but i forgot it... Well here it is. If you use stdio.h and conio.h, printf("Press any key to continue"); ch = getche(); \\ ch must be defined, its a variable if you use iostream, cout<<"Press any key to continue"; cin>>ch; \\ ch must be defined, its a variable I havent tried it but I'm pretty sure that worksI havent tried it but I'm pretty sure that worksCode:#include <iostream.h> #include <conio.h> //I think... int main() { cout<<"Press any key to continue..."<<endl; if(!kbhit()) { exit(0); } return 0; } +++ ++ + Sekti ++ +++ Quoting Homer Simpson: "Where's the any key?" Yeah I know...dumb...but I couldn't resist. - purple - just so you know, the cin >> variable method wont work cause that one waill wait until it gets an input before it's done so if you click enter before having written anything the only thing that happens is that it moves to the next line. some body wrote a thing like this i think: Dunno if it works....Dunno if it works....Code:#include <conio.h> void pause() { while(!kbhit()); getch(); } The bad thing is that conio.h is generally screwed up. The eziest way is: #include <stdlib.h> ... system("PAUSE"); OR #include <iostream.h> #include <conio.h> ... cout << "Press any key to continue..."; getch(); dont use pause - its very pooor programming practice for various reasons - go with kbhit - its the best way you couls also use int wait; cout<<"Any key to continue!\n"; wait=getch(); You don't have to use return values, so you don't need wait.You don't have to use return values, so you don't need wait.wait=getch(); Code:cout<<"Any key to continue!\n"; getch(); All spelling mistakes, syntatical errors and stupid comments are intentional. #include <iostream> using namespace std; int main() { printf( "Press any key to continue..." ); fflush( stdin ); getchar(); return ( 0 ); } Or you could not... >fflush( stdin ); UN-DE-FINED. You cannot use fflush on input streams. Here's a run down of this thread, summarized into neato little Prelude comments for your enjoyment. >how to call the "press any key to continue" display in c++ Ask the user for input >system("pause"); Godawful slow, only use in extreme cases of need. >cin >> x; This is good, but you don't need a variable since all you're asking the user to do is enter 'something'. >ch = getche(); \\ ch must be defined, its a variable ch is not needed, getche is not standard and may not exist >if(!kbhit()) Once again not standard and may not exist, so why bother if you don't have to have it? >Quoting Homer Simpson: "Where's the any key?" Ctrl+Alt+ >getch(); I wonder how many programmer's heads will pop if we broadcast across the world that conio is not standard C or C++. >system("PAUSE"); Easy, yes. Bad idea, oh yea. >its very pooor programming practice for various reasons Depends on what you are doing >getch(); C_Coder...you're excused since everyone else was suggesting this. I'll assume you were going with the flow >fflush( stdin ); Wrong, very wrong >getchar(); Standard, effective, efficient...this is the best solution offered in this thread. I would have suggested it if Unregistered didn't. cin.get() would also work well. -Prelude My best code is written with the delete key.
http://cboard.cprogramming.com/cplusplus-programming/12955-press-any-key.html
CC-MAIN-2014-41
refinedweb
687
76.22
GhPython in Rhino WIP ships with an all-Rhino Python compiler that can be used to create .Net compiled assemblies containing compiled instructions. Unlike other methods that are based on embedding a Python code string in a C# component, this speeds up code execution and makes reverse engineering more difficult. There are two options for the process of making a component, #1 is extremely simplified and #2 is more advanced. The component is able to pick up names, descriptions and help from the original Grasshopper component, and turn it into an executable dll file. To perform this operation, the compiler makes heavy use of the facilities provided by clr.CompileModules(), which is a IronPython module devoted to creation of compiled assemblies, and is also what pyc.py in IronPython uses to produce standalone executable files. Note: this is for Rhino WIP #6.0.16313.01411 and greater! 1. Compiling a single component in an assembly with the wizard We will start by compiling a single component with the all-automated wizard. 1.1. For this sample, we will start by placing a GhPython component on the canvas, and by setting the first hint to Point3d. The compiler will write code that is dependent on type hints. 1.2. Then we can remove an input for this sample. We do not need it. The compiler will write code that is dependent on the amount of inputs and outputs. We also remove the “out” output. 1.2.1. You need to zoom in to see the "-" (minus) control. 1.3. Then we can rename the input to “P” for this sample. This will have an influence on the way we write code. We and the compiler will have to write code that is dependent on the naming of inputs and outputs. 1.3.1. Right-click to see this context menu. 1.4. Next, we will write the code that forms our logic for this component. We can provide the user with a good amount of information by placing docstrings at the beginning of our module, and then we can write code that references our variables. Here is the full text written in the image below. """Draws a graphic symbol parallel to world XYZ showing orientations. Inputs: P: The point where the symbol should be drawn Output: X: The symbol, drawn as three lines""" __author__ = "piac" import rhinoscriptsyntax as rs from Rhino.Geometry import Point3d as p3 if P: X = [] line_EW = rs.AddLine(P - p3(10,0,0), P + p3(10,0,0)) X.append(line_EW) line_NS =rs.AddLine(P - p3(0,10,0), P + p3(0,10,0)) X.append(line_NS) line_UD =rs.AddLine(P - p3(0,0,10), P + p3(0,0,10)) X.append(line_UD) You can also download the readily-made file. compiling.gh (2.7 KB) 1.5. The code works in procedural mode. We switch to SDK mode. 1.5.1. Click the jigsaw puzzle icon and switch to GH_Component SDK Mode. 1.6. A few adjustments are necessary to make our code robust. The automatic conversion, though, will work out-of-the-box most of the times or will give a good idea about a starting point. Remember to declare more component _def_s, rather than nesting all your functions inside the RunScript function. This will improve runtime behavior. 1.7. We draw this icon in an image processor. We should draw a 24x24 pixel icon and save it, as best practice, as PNG. We use a transparent background and some good antialiasing if possible. 1.8. We apply the image. Drag-and-drop of the image on top of the component will work. 1.8.1. This is the appearance of the component after applying the image. 1.9. Compile… If the option is grayed out, you need to remove the “out” output. Printing should not have effects in compiled components. 1.9.1. Let the "magic" begin. 1.10. We still need to set a few details. This form should pop-up. Particularly important is the Guid. If we use the same Guid from an old version of our add-on, we will replace its behavior once the file is swapped and the new assembly is loaded. However, we need to delete the old version of the add-on first. Grasshopper uses Guids to uniquely identify component types. 1.10.1. We need to write down or select the Category, the Subcategory, give the component a Name and a Nickname. 1.11. You will be prompted a save location. The default is also the automatically-watched folder of Grasshopper. Saving here will cause the assembly to be immediately loaded. 1.12. If we did not modify the defaults, the assembly will be placed in the Libraries folder, and automatically loaded into the Grasshopper ribbon. We created our first GHPY file! A few notes on this name: - Axes is the name of the assembly - There is an underscore, and then the assembly ID follows You can remove the assembly ID, but this is the full name of the module that IronPython will load: Axes_7af034972e964ca4b11ac1b9209267f7. This long name ensures that no other add-on or module mistakenly uses your same name. You can rename this part to anything that pleases you. However, this ID will always be the ID by which Grasshopper identifies your add-on. You should write it down or you can discover it again later. Ready downloads for part #1 - compiling.gh (2.7 KB) Component in procedural mode. - compiling-sdk.gh (2.7 KB) Component in Grasshopper SDK mode. 2. Advanced compiling: multiple components, projects with modules, updating Sometimes, there is a need of a setup that is more advanced than one component, as in #1 on this page. We will now cover the creation of an update to the assembly above, making sure that it loads the previous component, and we will add a new “battery” as well, that uses functionality from another private module. This should cover a larger ground of user cases. 2.1. Using the code from the component above, we choose the other option, copy compilable code. 2.1.1. 2.2. We get the same panel as in 1.10, but this time it will copy the result to the clipboard. 2.2.1. 2.3. We get the same panel as in 1.10, but this time it will copy the result to the clipboard. 2.3.1. 2.4. We paste the result from the clipboard into a new _EditPythonScript form. We can remove docstrings, because they are no longer needed. Their content was copied by the wizard into the Grasshopper SDK instantiation code. We save this file as Axes.py, in a new, empty folder. 2.5. We also create two new Python files: Main.py and Axes_helper.py. The content of main.py is then: import clr clr.CompileModules("Axes.p2.7.5.0.ghpy", "Axes.py", "Axes_helper.py") 2.6. The content of Axes_helper.py is then: import rhinoscriptsyntax as rs class SphereArtist(object): def __init__(self, radius): self.radius = radius def Draw(self, location): """Retuns new spheres""" return rs.AddSphere(location, self.radius) 2.7. We then follow the instructions from 2.1 to 2.3, with this code: import Axes_helper class MyComponent(component): def __init__(self): self.artist = Axes_helper.SphereArtist(5) def RunScript(self, P): return self.artist.Draw(P) It will again create a large class with more boilerplate code: the wizard takes care of every need of the Grasshopper SDK. We then add the result to axes.py. – 2.8. In total, we have two components, and one assembly information class. They need to have different names, otherwise, the Python interpreter will override one declaration with the other. All component declarations need to be in the file which is the second argument to the ###This is the folder to be compiled at this point: compiling_display.zip (7.9 KB) We run the main.py file, and we get a new axes.p2.7.5.0.ghpy file. This contains our entire code, in compiled instructions. HURRAY! 2.8.2. Our compiled file. – 2.9. To have Grasshopper load this, we can copy this file to the Grasshopper Components Folder. Open Grasshopper, then go to File -> Special Folders -> Components Folder. Move the file there. Immediately, Grasshopper will load this file and we will be ready to use our new components. 2.9.1. Done! Axes.p2.7.5.0.ghpy (34 KB) Some few last words of caution: - Remember to always save your source code in the original form! It is really difficult to get it back once compiled. - This is new functionality in Rhino WIP. It can change and you might need to re-compile. Happy coding!
https://discourse.mcneel.com/t/tutorial-creating-a-grasshopper-component-with-the-python-ghpy-compiler/38552
CC-MAIN-2018-22
refinedweb
1,460
68.06
Parent Directory | Revision Log *** empty log message *** package Sprout; use Data::Dumper; use strict; use Carp; use DBKernel; use XML::Simple; use DBQuery; use DBObject; use ERDB; use Tracer; use FIGRules; use Stats; use POSIX qw(strftime); >. C<<na_seq> returns the DNA sequence for a specified genome location. =cut #: Constructor SFXlate->new_sprout_only(); =head2 Public Methods =head3 new C<< C<root/>) * B<port> connection port (default C<0>) * B<maxSegmentLength> maximum number of residues per feature segment, (default C<4500>) * B<maxSequenceLength> maximum number of residues per sequence, (default C<8000>) ) = @_; # Compute the options. We do this by starting with a table of defaults and overwriting with # the incoming data. my $optionTable = Tracer::GetOptions({ dbType => 'mysql', # database type dataDir => 'Data', # data file directory xmlFileName => 'SproutDBD.xml', # database definition file name userData => 'root/', # user name and password port => 0, # database connection port maxSegmentLength => 4500, # maximum feature segment length maxSequenceLength => 8000, # maximum contig sequence length }, $options); # Get the data directory. my $dataDir = $optionTable->{dataDir}; # Extract the user ID and password. $optionTable->{userData} =~ m!([^/]*)/(.*)$!; my ($userName, $password) = ($1, $2); # Connect to the database. my $dbh = DBKernel->new($optionTable->{dbType}, $dbName, $userName, $password, $optionTable->{port}); # Create the ERDB object. my $xmlFileName = "$optionTable->{xmlFileName}"; my $erdb = ERDB->new($dbh, $xmlFileName); # Create this object. my $self = { _erdb => $erdb, _options => $optionTable, _xmlName => $xmlFileName }; # Bless and return it. bless $self; return $self; } =head3 MaxSegment C<< C<< Get C<< my $query = $sprout->Get(\@objectNames, $filterClause, \@parameterList); >> This method allows a general query against the Sprout data using a specified filter clause. = $sprout->Get(['Genome'], "Genome(genus) = ?", [$genus]); >> The WHERE clause contains a single question mark, so there is a single additional parameter representing the parameter value. It would also be possible to code C<< $query = $sprout- = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >> This query returns all the genomes for a particular genus and allows access to the sources from which they came. The join clauses to go from Genome to Source are generated automatically. Finally, the filter clause can contain sort information. To do this, simply put an C<ORDER BY> clause at the end of the filter. Field references in the ORDER BY section follow the same rules as they do in the filter itself; in other words, each one must be of the form B<I<objectName>(I<fieldName>)>. For example, the following filter string gets all genomes for a particular genus and sorts them by species name. C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ? ORDER BY Genome(species)", [$genus]); >> It is also permissible to specify I<only> an ORDER BY clause. For example, the following invocation gets all genomes ordered by genus and species. C<< $query = $sprout->Get(['Genome'], "ORDER BY Genome(genus), Genome(species)"); >> Odd things may happen if one of the ORDER BY fields is in a secondary relation. So, for example, an attempt to order B<Feature>s by alias may (depending on the underlying database engine used) cause a single feature to appear more than once. If multiple names are specified, then the query processor will automatically determine a join path between the entities and relationships. The algorithm used is very simplistic. In particular, you can't specify any entity or relationship more than once, and RETURN Returns a B<DBQuery> that can be used to iterate through all of the results. =back =cut sub Get { # Get the parameters. my ($self, $objectNames, $filterClause, $parameterList) = @_; # We differ from the ERDB Get method in that the parameter list is passed in as a list reference # rather than a list of parameters. The next step is to convert the parameters from a reference # to a real list. We can only do this if the parameters have been specified. my @parameters; if ($parameterList) { @parameters = @{$parameterList}; } return $self->{_erdb}->Get($objectNames, $filterClause, @parameters); } =head3 GetEntity C<< my $entityObject = $sprout-) = @_; # Call the ERDB method. return $self->{_erdb}->GetEntity($entityType, $ID); } =head3 GetEntityValues C<< my @values = #: Return Type @; sub GetEntityValues { # Get the parameters. my ($self, $entityType, $ID, $fields) = @_; # Call the ERDB method. return $self->{_erdb}->GetEntityValues($entityType, $ID, $fields); } =head3 ShowMetaData C<< $sprout->ShowMetaData($fileName); >> This method outputs a description of the database to an HTML file in the data directory. =over 4 =item fileName Fully-qualified name to give to the output file. =back =cut sub ShowMetaData { # Get the parameters. my ($self, $fileName) = @_; # Compute the file name. my $options = $self->{_options}; # Call the show method on the underlying ERDB object. $self->{_erdb}->ShowMetaData($fileName); } =head3 Load C<< ) = @_; # Get the database object. my $erdb = $self->{_erdb}; # Load the tables from the data directory. my $retVal = $erdb->LoadTables($self->{_options}->{dataDir}, $rebuild); # Return the statistics. return $retVal; } =head3 LoadUpdate C<<) = @_; # Get the database object. my $erdb = $self->{_erdb}; # Declare the return value. my $retVal = Stats->new(); # Get the data directory. my $optionTable = $self->{_options}; my $dataDir = $optionTable->{dataDir}; # Loop through the incoming table names. for my $tableName (@{$tableList}) { # Find the table's file. my $fileName = "$dataDir/$tableName"; if (! -e $fileName) { $fileName = "$fileName.dtx"; } # Attempt to load this table. my $result = $erdb->LoadTable($fileName, $tableName, $truncateFlag); # Accumulate the resulting statistics. $retVal->Accumulate($result); } # Return the statistics. return $retVal; } =head3 Build C<< ->{_erdb}->CreateTables; } =head3 Genomes C<< C<< C<< C<< space-delimited string in a scalar context. == $prevBeg - $prevLen) || ($dir eq "+" && $beg == $prevBeg + $prevLen)) { # Here we need to merge two segments.); # Add the specifier to the list. push @retVal, "${contigID}_$beg$dir$len"; } # Return the list in the format indicated by the context. return (wantarray ? @retVal : join(' ', @retVal)); } =head3 ParseLocation C<< #: Return Type @; C<< #: Return Type $; C<<>. =over 4 =item locationList List of location specifiers, each in the form I<contigID>C<_>I<begin>I<dir); if ($dir eq "+") { $start = $beg; $stop = $beg + $len - 1; } else { $start = $beg + $len + 1; $stop = $beg; }; # Figure out the start point and length of the relevant section. my $pos1 = ($start < $startPosition ? 0 : $start - $startPosition); my $len = ($stopPosition <= $stop ? $stopPosition : $stop) - $startPosition - $pos1; # Add the relevant data to the location data. $locationDNA .= substr($sequenceData, $pos1, $len); } # Add this location's data to the return string. Note that we may need to reverse it. if ($dir eq '+') { $retVal .= $locationDNA; } else { $locationDNA = join('', reverse split //, $locationDNA); $retVal .= $locationDNA; } } # Return the result. return $retVal; } =head3 AllContigs C<< ContigLength C<<; } # Return the result. return $retVal; } =head3 GenesInRegion<< my @descriptors = $sprout->FeatureAnnotations($featureID); >> Return the annotations of a feature. =over 4 =item featureID ID of the feature whose annotations are desired. =item RETURN Returns a list of annotation descriptors. Each descriptor is a hash with the following fields. * B<featureID> ID of the relevant feature. * B<timeStamp> time the annotation was made, in user-friendly format. * B<user> ID of the user who made the annotation * B<text> text of the annotation. =back =cut #: Return Type @%; sub FeatureAnnotations { # Get the parameters. my ($self, $featureID) = @_; #)']); # Assemble them into a hash. my $annotationHash = { featureID => $featureID, timeStamp => FriendlyTimestamp($timeStamp), user => $user, text => $text }; # Add it to the return list. push @retVal, $annotationHash; } # Return the result list. return @retVal; } =head3 AllFunctionsOf C<< functional assignment IDs to user IDs. =back =cut #: Return Type %; sub AllFunctionsOf { # Get the parameters. my ($self, $featureID) = @_; # Get all of the feature's annotations. my @query = $self->GetAll(['IsTargetOfAnnotation', 'Annotation'], "IsTargetOfAnnotation(from-link) = ?", [$featureID], ['Annotation(time)', 'Annotation(annotation)']); # Declare the return hash. my %retVal; # Declare a hash for insuring we only make one assignment per user. my %timeHash = (); # Now we sort the assignments by timestamp in reverse. my @sortedQuery = sort { -($a->[0] <=> $b->[0]) } @query; # Loop until we run out of annotations. for my $annotation (@sortedQuery) { # Get the annotation fields. my ($timeStamp, $text) = @{$annotation}; # Check to see if this is a functional assignment. my ($user, $function) = _ParseAssignment($text); if ($user && ! exists $timeHash{$user}) { # Here it is a functional assignment and there has been no # previous assignment for this user, so we stuff it in the # return hash. $retVal{$function} = $user; # Insure we don't assign to this user again. $timeHash{$user} = 1; } } # Return the hash of assignments found. return %retVal; } =head3 FunctionOf C<< a functional assignment is a type of annotation. The format of an assignment is described in L</ParseLocation>. Its worth noting that we cannot filter on the content of the annotation itself because it's a text field; however, this is not a big problem because most features only have a small number of annotations., only the latest C<FIG> assignment'], "IsTargetOfAnnotation(from-link) = ? ORDER BY Annotation(time) DESC", [$featureID]); my $timeSelected = 0; # Loop until we run out of annotations. while (my $annotation = $query->Fetch()) { # Get the annotation text. my ($text, $time) = $annotation->Values(['Annotation(annotation)','Annotation(time)']); # Check to see if this is a functional assignment for a trusted user. my ($user, $function) = _ParseAssignment($text); if ($user) { # Here it is a functional assignment. Check the time and the user # name. The time must be recent and the user must be trusted. if ((exists $trusteeTable{$user}) && ( BBHList C<< IDs of their best hits. =back =cut #: Return Type %; sub BBHList { # Get the parameters. my ($self, $genomeID, $featureList) = @_; # Create the return structure. my %retVal = (); # Loop through the incoming features. for my $featureID (@{$featureList}) { # Create a query to get the feature's best hit. my $query = $self->Get(['IsBidirectionalBestHitOf'], "IsBidirectionalBestHitOf(from-link) = ? AND IsBidirectionalBestHitOf(genome) = ?", [$featureID, $genomeID]); # Look for the best hit. my $bbh = $query->Fetch; if ($bbh) { my ($targetFeature) = $bbh->Value('IsBidirectionalBestHitOf(to-link)'); $retVal{$featureID} = $targetFeature; } } # Return the mapping. return \%retVal; } =head3 FeatureAliases C<<EntityValues('Feature', $featureID, ['Feature(alias)']); # Return the result. return @retVal; } =head3 GenomeOf C<< my $genomeID = $sprout->GenomeOf($featureID); >> Return the genome that contains a specified feature. =over 4 =item featureID ID of the feature whose genome is desired. =item RETURN Returns the ID of the genome for the specified feature. If the feature is not found, returns an undefined value. =back =cut #: Return Type $; sub GenomeOf { # Get the parameters. my ($self, $featureID) = @_; # Create a query to find the genome associated with the feature. my $query = $self->Get(['IsLocatedIn', 'HasContig'], "IsLocatedIn(from-link) = ?", [$featureID]); # Declare the return value. my $retVal; # Get the genome ID. if (my $relationship = $query->Fetch()) { ($retVal) = $relationship->Value('HasContig(from-link)'); } # Return the value found. return $retVal; } =head3 CoupledFeatures C<<) = @_; # Create a query to retrieve the functionally-coupled features. Note that we depend on the # fact that the functional coupling is physically paired. If (A,B) is in the database, then # (B,A) will also be found. my $query = $self->Get(['IsClusteredOnChromosomeWith'], "IsClusteredOnChromosomeWith(from-link) = ?", [$featureID]); # This value will be set to TRUE if we find at least one coupled feature. my $found = 0; # Create the return hash. my %retVal = (); # Retrieve the relationship records and store them in the hash. while (my $clustering = $query->Fetch()) { my ($otherFeatureID, $score) = $clustering->Values(['IsClusteredOnChromosomeWith(to-link)', 'IsClusteredOnChromosomeWith(score)']); $retVal{$otherFeatureID} = $score; $found = 1; } # Functional coupling is reflexive. If we found at least one coupled feature, we must add # the incoming feature as well. if ($found) { $retVal{$featureID} = 9999; } # Return the hash. return %retVal; } =head3 GetEntityTypes C<< my @entityList = $sprout->GetEntityTypes(); >> Return the list of supported entity types. =cut #: Return Type @; sub GetEntityTypes { # Get the parameters. my ($self) = @_; # Get the underlying database object. my $erdb = $self->{_erdb}; # Get its entity type list. my @retVal = $erdb->GetEntityTypes(); } =head3 ReadFasta C<<} = uc $sequence; } # Clear the sequence accumulator and save the new ID. ($id, $sequence) = ("$prefix$1", ""); } else { # Here we have a data line, so we add it to the sequence accumulator. # First, we get the actual data out. Note that we normalize to upper # case. $line =~ /^\s*(.*?)(\s|\n)/; $sequence .= $1; } } # Flush out the last sequence (if any). if ($sequence) { $retVal{$id} = uc $sequence; } # Close the file. close FASTAFILE; # Return the hash constructed from the file. return %retVal; } =head3 FormatLocations C<< C<< ->{_erdb}->DumpRelations($outputDirectory); } =head3 XMLFileName C<< my $fileName = $sprout->XMLFileName(); >> Return the name of this database's XML definition file. =cut #: Return Type $; sub XMLFileName { my ($self) = @_; return $self->{_xmlName}; } =head3 Insert C<< ->{_erdb}->InsertObject($objectType, $fieldHash); } =head3 Annotate C<< C<<(['Feature'], 'Feature(alias) = ?', [$mappedAlias], 'Feature(id)'); } # Return the result.. my $testInstance = $self->GetEntity($entityName, $entityID); # Return an existence indicator. my $retVal = ($testInstance ? 1 : 0); return $retVal; } =head3 FeatureTranslation C<< C<<, C<< C<< C<<<< my %subsystems = $sprout->SubsystemsOf($featureID); >> Return a hash describing all the subsystems in which a feature participates. Each subsystem is mapped to the role the feature performs. =over 4 =item featureID ID of the feature whose subsystems are desired. =item RETURN Returns a hash mapping all the feature's subsystems to the feature's role. =back =cut #: Return Type %; sub SubsystemsOf { # Get the parameters. my ($self, $featureID) = @_; # Use the SSCell to connect features to subsystems. my @subsystems = $self->GetAll(['ContainsFeature', 'HasSSCell', 'IsRoleOf'], "ContainsFeature(to-link) = ?", [$featureID], ['HasSSCell(from-link)', 'IsRoleOf(from-link)']); # Create the return value. my %retVal = (); # Loop through the results, adding them to the hash. for my $record (@subsystems) { $retVal{$record->[0]} = $record->[1]; } # Return the hash. return %retVal; } =head3 RelatedFeatures C<< = GetAll C<< my @list = $sprout- = $sprout-) = @_; # Call the ERDB method. my @retVal = $self->{_erdb}->GetAll($objectNames, $filterClause, $parameterList, $fields, $count); # Return the resulting list. return @retVal; } =head3 GetFlat C<< my @list = $sprout- Protein C<<. my $triple = substr($sequence, $i, 3); # Translate it using the table. my $protein = "X"; if (exists $table->{$triple}) { $protein = $table->{$triple}; } $retVal .= $protein; } # Remove the stop codon (if any). $retVal =~ s/\*$//; # Return the result. return $retVal; } =head3 LoadInfo C<<->{_erdb}->GetTableNames(); # Return the result. return @retVal; } =head3 LowBBHs C<< my %bbhMap = $sprout->Good = (); #. I<XXXX>C<\nset >I<YYYY>C< function to\n>I<ZZZZZ> where I<XXXX> is the B<assigning user>, I<YYYY> is the B<user>, and I<ZZZZ> is the actual functional role. In most cases, the user and the assigning user will be the same, but that is not always the case. This is a static method. =over 4 =item text Text of the annotation. =item RETURN Returns an empty list if the annotation is not a functional assignment; otherwise, returns a two-element list containing the user name and the function text. =back =cut sub _ParseAssignment { # Get the parameters. my ($text) = @_; # Declare the return value. my @retVal = (); # Check to see if this is a functional assignment. my ($user, $type, $function) = split(/\n/, $text); if ($type =~ m/^set ([^ ]+) function to$/i) { # Here it is, so we return the user name (which is in $1), the functional role text, # and the assigning user. @retVal = ($1, $function, $user); } # Return the result list. return @retVal; } = strftime("%a %b %e %H:%M:%S %Y", localtime($timeValue)); return $retVal; } 1;
http://biocvs.mcs.anl.gov/viewcvs.cgi/Sprout/Sprout.pm?revision=1.13&view=markup&pathrev=mgrast_dev_04052011
CC-MAIN-2019-43
refinedweb
2,414
50.63
On Wed, 2016-11-30 at 19:07 -0800, Ngie Cooper wrote: > > > > On Nov 30, 2016, at 18:21, Conrad E. Meyer <c...@freebsd.org> wrote: > > > > Author: cem > > Date: Thu Dec 1 02:21:36 2016 > > New Revision: 309344 > > URL: > > > > Log: > > Remove a death threat from the FreeBSD sources > > > > Reported by: koobs@, araujo@, linimon@, bjk@, emaste@, jhb@, > > ngie@, cem@ > > Maintainer timeout: des@ > Really?? I wish you hadn't added me to this list.. I don't in any way > endorse the way that you went about dealing with this disagreement. > You kind of just pissed all over what des@ did out of spite. > > </rant> Advertising Really? Well then feel free to ADD my name to the list of people who found that comment, and the subsequent non-response to the complaints about it, completely inappropriate. -- Ian > > > > > > Modified: > > head/lib/libutil/flopen.c > > > > Modified: head/lib/libutil/flopen.c > > =================================================================== > > =========== > > --- head/lib/libutil/flopen.c Thu Dec 1 01:56:34 > > 2016 (r309343) > > +++ head/lib/libutil/flopen.c Thu Dec 1 02:21:36 > > 2016 (r309344) > > @@ -40,10 +40,10 @@ __FBSDID("$FreeBSD$"); > > /* > > * Reliably open and lock a file. > > * > > - * DO NOT, UNDER PAIN OF DEATH, modify this code without first > > reading the > > - * revision history and discussing your changes with <des@freebsd. > > org>. > > - * Don't be fooled by the code's apparent simplicity; there would > > be no > > - * need for this function if it was as easy to get right as you > > think. > > + * Please do not modify this code without first reading the > > revision history > > + * and discussing your changes with <d...@freebsd.org>. Don't be > > fooled by the > > + * code's apparent simplicity; there would be no need for this > > function if it > > + * was easy to get right. > > */ > > int > > flopen(const char *path, int flags, ...) > > @@ -108,7 +108,11 @@ flopen(const char *path, int flags, ...) > > errno = serrno; > > return (-1); > > } > > -#ifdef DONT_EVEN_THINK_ABOUT_IT > > + /* > > + * The following change is provided as a specific example > > to > > + * avoid. > > + */ > > +#if 0 > > if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) { > > serrno = errno; > > (void)close(fd); > > > _______________________________________________ svn-src-all@freebsd.org mailing list To unsubscribe, send any mail to "svn-src-all-unsubscr...@freebsd.org"
https://www.mail-archive.com/svn-src-all@freebsd.org/msg133999.html
CC-MAIN-2017-04
refinedweb
350
65.73
In theory if you use django, changing your RDBS from say sqlite to mysql is a breeze. All you need is generate a dump of your existing data with ./manage.py dumpdata, change settings.py and do ./manage.py migrate on the new server. Then you can import the previously exported data through ./manage.py loaddata but it isn't always that simple. The . /manage.py migrate step on the new database invariably through an error or two dozen. Squashing migrations often works, but the simplest thing is to delete all the migrations from each app's migrations/ folder. Then you do ./manage.py makemigrations followed by ./manage.py migrate and if you are lucky you have a newly created database on your hot new server. If you are unlucky you will find that some of the model fields you have used (example ArrayField) are incompatible with the new RDBMS you are moving to. I leave you to solve that yourself with the reminder that ArrayField should never have been used in the first place. Anyone who has ever tried to use Django's loaddata command can tell you that it will choke on django Content Types. Once you get past that hurdle, you will still find all sorts of errors popping up. Of course you can use MySql's SELECT INTO OUTFILE or Postgresql's COPY command to make the import export process less painfull but the only catch is if you have a large number of models, you will find yourself doing a lot of typing. Enter Odo. import os, sys if __name__ == '__main__': #pragma nocover # Setup environ sys.path.append(os.getcwd()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") import django django.setup() from odo import odo from django.apps import apps for m in apps.get_models(): odo("sqlite://db.sqlite3::{0}".format(m._meta.db_table),"/tmp/{0}.csv".format(m._meta.db_table)) The above code will export data from every single table in your database into a set of CSV files using sqlite's .output command for the export, while most home brewed exporters would save the data line by line. Right now, you can import these into another database right? What if I told you that you can actually import export without intermediate CSV dumps? yep, quite possible but your milage might vary.
http://www.raditha.com/blog/archives/django-change-the-database-backend/
CC-MAIN-2018-13
refinedweb
387
66.33
From bank fraud to preventative machine maintenance, anomaly detection is an incredibly useful and common application of machine learning. The isolation forest algorithm is a simple yet powerful choice to accomplish this task. In this article we'll cover: - An Introduction to Anomaly Detection - Use Cases of Anomaly Detection - What Is Isolation Forest? - Using Isolation Forest for Anomaly Detection - Implementation in Python You can run the code for this tutorial for free on the ML Showcase. So, let's get started! Launch Project For Free Introduction to Anomaly Detection An outlier is nothing but a data point that differs significantly from other data points in the given dataset. Anomaly detection is the process of finding the outliers in the data, i.e. points that are significantly different from the majority of the other data points. Large, real-world datasets may have very complicated patterns that are difficult to detect by just looking at the data. That's why the study of anomaly detection is an extremely important application of Machine Learning. In this article we are going to implement anomaly detection using the isolation forest algorithm. We have a simple dataset of salaries, where a few of the salaries are anomalous. Our goal is to find those salaries. You could imagine this being a situation where certain employees in a company are making an unusually large sum of money, which might be an indicator of unethical activity. Before we proceed with the implementation, let's discuss some of the use cases of anomaly detection. Anomaly Detection Use Cases Anomaly detection has wide applications across industries. Below are some of the popular use cases: Banking. Finding abnormally high deposits. Every account holder generally has certain patterns of depositing money into their account. If there is an outlier to this pattern the bank needs to be able to detect and analyze it, e.g. for money laundering. Finance. Finding the pattern of fraudulent purchases. Every person generally has certain patterns of purchases which they make. If there is an outlier to this pattern the bank needs to detect it in order to analyze it for potential fraud. Healthcare. Detecting fraudulent insurance claims and payments. Manufacturing. Abnormal machine behavior can be monitored for cost control. Many companies continuously monitor the input and output parameters of the machines they own. It is a well-known fact that before failure a machine shows abnormal behaviors in terms of these input or output parameters. A machine needs to be constantly monitored for anomalous behavior from the perspective of preventive maintenance. Networking. Detecting intrusion into networks. Any network exposed to the outside world faces this threat. Intrusions can be detected early on using monitoring for anomalous activity in the network. Now let's understand what the isolation forest algorithm in machine learning is. What Is Isolation Forest? Isolation forest is a machine learning algorithm for anomaly detection. It's an unsupervised learning algorithm that identifies anomaly by isolating outliers in the data. Isolation Forest is based on the Decision Tree algorithm. It isolates the outliers by randomly selecting a feature from the given set of features and then randomly selecting a split value between the max and min values of that feature. This random partitioning of features will produce shorter paths in trees for the anomalous data points, thus distinguishing them from the rest of the data. In general the first step to anomaly detection is to construct a profile of what's "normal", and then report anything that cannot be considered normal as anomalous. However, the isolation forest algorithm does not work on this principle; it does not first define "normal" behavior, and it does not calculate point-based distances. As you might expect from the name, Isolation Forest instead works by isolating anomalies explicitly isolating anomalous points in the dataset. The Isolation Forest algorithm is based on the principle that anomalies are observations that are few and different, which should make them easier to identify. Isolation Forest uses an ensemble of Isolation Trees for the given data points to isolate anomalies. Isolation Forest recursively generates partitions on the dataset by randomly selecting a feature and then randomly selecting a split value for the feature. Presumably the anomalies need fewer random partitions to be isolated compared to "normal" points in the dataset, so the anomalies will be the points which have a smaller path length in the tree, path length being the number of edges traversed from the root node. Using Isolation Forest, we can not only detect anomalies faster but we also require less memory compared to other algorithms. Isolation Forest isolates anomalies in the data points instead of profiling normal data points. As anomalies data points mostly have a lot shorter tree paths than the normal data points, trees in the isolation forest does not need to have a large depth so a smaller max_depth can be used resulting in low memory requirement. This algorithm works very well with a small data set as well. Let's do some exploratory data analysis now to get some idea about the given data. Exploratory Data Analysis Let's import the required libraries first. We are importing numpy, pandas, seaborn and matplotlib. Apart form that we also need to import IsolationForest from sklearn.ensemble. import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.ensemble import IsolationForest Once the libraries are imported we need to read the data from the csv to the pandas data frame and check the first 10 rows of data. The data is a collection of salaries, in USD per year, of different professionals. This data has few anomalies (like salary too high or too low) which we will be detecting. df = pd.read_csv('salary.csv') df.head(10) To get more of an idea of the data we have plotted a violin plot of salary data as shown below. A violin plot is a method of plotting numeric data. Typically a violin plot includes all the data that is in a box plot, a marker for the median of the data, a box or marker indicating the interquartile range, and possibly all sample points, if the number of samples is not too high. To get a better idea of outliers we may like to look at a box plot as well. This is also known as box-and-whisker plot. The box in box plot shows the quartiles of the dataset, while the whiskers shows the rest of the distribution. Whiskers do not show the points that are determined to be outliers. Outliers are detected by a method which is a function of the interquartile range. In statistics the interquartile range, also known as mid spread or middle 50%, is a measure of statistical dispersion, which is equal to the difference between 75th and 25th percentiles. Once we have completed our exploratory data analysis, it's time to define and fit the model. Define and Fit Model We'll create a model variable and instantiate the IsolationForest class. We are passing the values of four parameters to the Isolation Forest method, listed below. Number of estimators: n_estimators refers to the number of base estimators or trees in the ensemble, i.e. the number of trees that will get built in the forest. This is an integer parameter and is optional. The default value is 100. Max samples: max_samples is the number of samples to be drawn to train each base estimator. If max_samples is more than the number of samples provided, all samples will be used for all trees. The default value of max_samples is 'auto'. If 'auto', then max_samples=min(256, n_samples) Contamination: This is a parameter that the algorithm is quite sensitive to; it refers to the expected proportion of outliers in the data set. This is used when fitting to define the threshold on the scores of the samples. The default value is 'auto'. If ‘auto’, the threshold value will be determined as in the original paper of Isolation Forest. Max features: All the base estimators are not trained with all the features available in the dataset. It is the number of features to draw from the total features to train each base estimator or tree.The default value of max features is one. model=IsolationForest(n_estimators=50, max_samples='auto', contamination=float(0.1),max_features=1.0) model.fit(df[['salary']]) After we defined the model above we need to train the model using the data given. For this we are using the fit() method as shown above. This method is passed one parameter, which is our data of interest (in this case, the salary column of the dataset). Once the model is trained properly it will output the IsolationForest instance as shown in the output of the cell above. Now this is the time to add the scores and anomaly column of the dataset. Add Scores and Anomaly Column After the model is defined and fit, let's find the scores and anomaly column. We can find out the values of scores column by calling decision_function() of the trained model and passing the salary as parameter. Similarly we can find the values of anomaly column by calling the predict() function of the trained model and passing the salary as parameter. These columns are going to be added to the data frame df. After adding these two columns let's check the data frame. As expected, the data frame has three columns now: salary, scores and anomaly. A negative score value and a -1 for the value of anomaly columns indicate the presence of anomaly. A value of 1 for the anomaly represents the normal data. Each data point in the train set is assigned an anomaly score by this algorithm. We can define a threshold, and using the anomaly score, it may be possible to mark a data point as anomalous if its score is greater than the predefined threshold. df['scores']=model.decision_function(df[['salary']]) df['anomaly']=model.predict(df[['salary']]) df.head(20) After adding the scores and anomalies for all the rows in the data, we will print the predicted anomalies. Print Anomalies To print the predicted anomalies in the data we need to analyse the data after addition of scores and anomaly column. As you can see above for the predicted anomalies the anomaly column values would be -1 and their scores will be negative. Using this information we can print the predicted anomaly (two data points in this case) as below. anomaly=df.loc[df['anomaly']==-1] anomaly_index=list(anomaly.index) print(anomaly) Note that we could print not only the anomalous values but also their index in the dataset, which is useful information for further processing. Evaluating the model For evaluating the model let's set a threshold as salary > 99999 is an outlier.Let us find out the number of outlier present in the data as per the above rule using code as below. outliers_counter = len(df[df['salary'] > 99999]) outliers_counter outlier_counter = 2 Let us calculate the accuracy of the model by finding how many outlier the model found divided by how many outliers present in the data. print("Accuracy percentage:", 100*list(df['anomaly']).count(-1)/(outliers_counter)) Accuracy percentage: 100 % End Notes In this tutorial we learned what anomalies are, and how the Isolation Forest algorithm can be used to detect them. We also discussed various exploratory data analysis graphs like violin plot and box plot for this problem. Finally we implemented the Isolation Forest Algorithm and printed the real outliers in the data. I hope you liked the article and you may like to use it in your project in future if required. Happy Learning! Add speed and simplicity to your Machine Learning workflow today
https://blog.paperspace.com/anomaly-detection-isolation-forest/
CC-MAIN-2022-21
refinedweb
1,965
54.83
![if !(IE 9)]> <![endif]> A new version of the PVS-Studio analyzer 6.23 is working under macOS, which allows you to check the projects written in C and C++. Our team decided to perform a XNU Kernel check to coincide it with this event. With the release of the analyzer version for macOS, PVS-Studio can now be boldly called a cross-platform static code analyzer for C and C++ code. Originally, there was only a Windows version. About two years ago our team supported Linux: "The Development History of PVS-Studio for Linux". Also, attentive readers of our blog should remember the articles about the FreeBSD Kernel check (1st article, 2nd article). At that time, the analyzer has been built to be launched in PC-BSD and TrueOS. Now, finally, we got to macOS! Is it easy to develop a cross-platform product? This issue has economic and technical component. From the economic point of view, it was the right decision to make a cross-platform analyzer. Software development has long been moving in this direction, and a tool for developers of such projects must be relevant. However, if something is useful, it does not mean that it is worth doing straight away. In the beginning, we always make sure we have enough forces to implement something in a new direction, and then maintain it. Technically, it is difficult only in the very beginning, if the project is not directly intended as cross-platform. We spent a few months on the adaptation of the analyzer in a Linux system. Compilation of a project under a new platform didn't take much time: we have no GUI and the code is practically not connected with using of the system API. Analyzer adaptation under new compilers and improvement of analysis quality took most of the time. In other words, preventing false positives requires many efforts. What's with the development under macOS? At this point, we already had the analyzer project file for CMake, which was easily adaptable under different operating systems. Testing systems of different types were also cross-platform. All this has helped to start out on macOS. The Apple LLVM Compiler became the feature of the analyzer development under macOS. Although the analyzer was building perfectly using GCC and worked magnificently, but it still could have an impact on analyzer compatibility with users' computers. To avoid creating problems for potential users, we have decided to support the distribution build using this compiler that comes with Xcode. C++ development greatly helps in the creating and development of cross-platform projects, but different compilers add such capabilities unevenly, so conditional compilation is still actively used in several places. In general, everything went smoothly and easily. As before, most of the time was spent on refinement of the exceptions, site modification, testing and other related issues. As a first project, checked using PVS-Studio for macOS we'd like to present you the XNU Kernel. Distribution package Please click here, for further information about the ways to download and install PVS-Studio for macOS. How to start demonstrating the abilities of PVS-Studio for macOS? No doubts, the check of the kernel of this system is the best variant! Therefore, the first project, checked using the new version of the analyzer, became the XNU Kernel. XNU is a kernel of computer operating systems developed by Apple and used in OS X operating systems (macOS, iOS, tvOS, watchOS). Read more. It is considered that the kernel is written in C and C++, but in fact, it is C. I counted 1302 *.c-files and only 97 *.cpp-files. The size of the codebase is 1929 KLOC. It turns out that this is a relatively small project. For comparison, the codebase of the Chromium project is in 15 times larger and contains 30 MLOC. The source code can be conveniently downloaded from a mirror on GitHub: xnu. Although the XNU Kernel is relatively small, it's a challenge to study the analyzer warnings alone, which takes much time. False positives make the check more complicated, since I haven't performed the preliminary analyzer configuration. I just quickly looked through the warnings, writing out code fragments that, in my opinion, represent interest. This is more than enough for writing a quite large article. PVS-Studio analyzer easily finds a large number of interesting bugs. Note for XNU Kernel developers. I didn't have an objective to find as many bugs as possible. Therefore, you should not be guided by the article to fix them. Firstly, it's awkward, because there is no possibility to navigate along the warnings. Sure, it is much better to use one of the formats, which can generate PVS-Studio, for example, the HTML report with the possibility of navigation (it is similar to something that Clang can generate). Secondly, I skipped many errors simply because I studied the report superficially. I recommend developers to perform a more thorough analysis of the project with the help of PVS-Studio themselves. As I said, I was bothered with false positives, but in fact, they are no problem. If you configure the analyzer, it is possible to reduce the number of false positives to 10-15%. As analyzer configuration also requires time and restarting the process of analyzing, I skipped this step - it wasn't difficult for me to gather errors for the article even without it. If you plan to perform the analysis carefully, of course, you should take time to make configurations. Mostly, false positives occur due to macros and functions marked not qualitatively enough. For example, in the XNU Kernel, most of them is associated with using of panic. This is how this function is declared: extern void panic(const char *string, ...) __attribute__((__format__ (__printf__, 1, 2))); The function is annotated the way its arguments are interpreted by analogy with the arguments of the printf function. This enables compilers and analyzers to find errors of incorrect strings formatting. However, the function is not marked as the one that doesn't return control. As a result, the following code produces false positives: if (!ptr) panic("zzzzzz"); memcpy(ptr, src, n); Here the analyzer issues the warning that a dereferencing of a null pointer is possible. From its point of view, after calling the panic function, the memcpy function will be called as well. To avoid similar false positives, you must change the annotation of the function by adding __attribute__((noreturn)): extern __attribute__((noreturn)) void panic(const char *string, ...) __attribute__((__format__ (__printf__, 1, 2))); Now let's see what interesting things I managed to notice in the code of the XNU Kernel. In total, I noted 64 errors and decided to stop at this beautiful number. I have grouped the defects according to Common Weakness Enumeration, this classification is quite well-known and it will be easier to understand what errors are a question of this or that chapter. Various errors can lead to CWE-570/CWE-571, i.e. situations where a condition or part of a condition is always false/true. In the case of the XNU Kernel, all these errors, in my opinion, are related to typos. PVS-Studio is generally great at identifying typos. Fragment N1 int key_parse( struct mbuf *m, struct socket *so) { .... if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != m->m_pkthdr.len) { ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n")); PFKEY_STAT_INCREMENT(pfkeystat.out_invlen); error = EINVAL; goto senderror; } .... } PVS-Studio warning: V501 CWE-570 There are identical sub-expressions 'm->M_dat.MH.MH_pkthdr.len' to the left and to the right of the '!=' operator. key.c 9442 Due to a typo, a class member is compared with itself: m->m_pkthdr.len != m->m_pkthdr.len Part of the condition is always false, and as a result, the length of a message is checked incorrectly. It turns out that the program will continue handling incorrect data. Perhaps it's not that scary, but many vulnerabilities are just related to the fact that some input data was unchecked or insufficiently checked. So this fragment of code is clearly worth paying attention of developers. Fragment N2, N3 #define VM_PURGABLE_STATE_MASK 3 kern_return_t memory_entry_purgeable_control_internal(...., int *state) { .... if ((control == VM_PURGABLE_SET_STATE || control == VM_PURGABLE_SET_STATE_FROM_KERNEL) && (((*state & ~(VM_PURGABLE_ALL_MASKS)) != 0) || ((*state & VM_PURGABLE_STATE_MASK) > VM_PURGABLE_STATE_MASK))) return(KERN_INVALID_ARGUMENT); .... } PVS-Studio warning: V560 CWE-570 A part of conditional expression is always false: ((* state & 3) > 3). vm_user.c 3415 Let's consider in more detail this part of expression: (*state & VM_PURGABLE_STATE_MASK) > VM_PURGABLE_STATE_MASK If you substitute the value of the macro, you'll get: (*state & 3) > 3 Bitwise AND operation may result in only the values 0, 1, 2, or 3. It is pointless to check whether 0, 1, 2 or 3 is more than 3. It is very likely that the expression contains a typo. As in the previous case, a status is checked incorrectly, which can result in incorrect processing of incorrect (tainted) data. The same error is detected in the file vm_map.c. Apparently, a part of the code was written using Copy-Paste. Warning: V560 CWE-570 A part of conditional expression is always false: ((* state & 3) > 3). vm_map.c 15809 Fragment N4 void pat_init(void) { boolean_t istate; uint64_t pat; if (!(cpuid_features() & CPUID_FEATURE_PAT)) return; istate = ml_set_interrupts_enabled(FALSE); pat = rdmsr64(MSR_IA32_CR_PAT); DBG("CPU%d PAT: was 0x%016llx\n", get_cpu_number(), pat); /* Change PA6 attribute field to WC if required */ if ((pat & ~(0x0FULL << 48)) != (0x01ULL << 48)) { mtrr_update_action(CACHE_CONTROL_PAT); } ml_set_interrupts_enabled(istate); } PVS-Studio warning: V547 CWE-571 Expression is always true. mtrr.c 692 Let's go through a pointless check, which is likely to have a typo: (pat & ~(0x0FULL << 48)) != (0x01ULL << 48) Let's calculate some expressions: The expression (pat & [0xFFF0FFFFFFFFFFFF]) can not result in the value 0x0001000000000000. The condition is always true. As a result, the function mtrr_update_action is always called. Fragment N5 Here is a typo which, in my opinion, is very beautiful. typedef enum { CMODE_WK = 0, CMODE_LZ4 = 1, CMODE_HYB = 2, VM_COMPRESSOR_DEFAULT_CODEC = 3, CMODE_INVALID = 4 } vm_compressor_mode_t; void vm_compressor_algorithm_init(void) { .... assertf(((new_codec == VM_COMPRESSOR_DEFAULT_CODEC) || (new_codec == CMODE_WK) || (new_codec == CMODE_LZ4) || (new_codec = CMODE_HYB)), "Invalid VM compression codec: %u", new_codec); .... } PVS-Studio warning: V768 CWE-571 The expression 'new_codec = CMODE_HYB' is of enum type. It is odd that it is used as an expression of a Boolean-type. vm_compressor_algorithms.c 419 In the process of checking the condition, the variable new_codec is assigned a value of 2. As a result, the condition is always true and the assert-macro actually checks nothing. The error could be harmless. Well, big deal, macro assert didn't check something - no problem. However, in addition, the debug version also doesn't work correctly. The value of the variable new_codec goes bad and the wrong codec is used, not the one, which was required. Fragment N6, N7 void pbuf_copy_back(pbuf_t *pbuf, int off, int len, void *src) { VERIFY(off >= 0); VERIFY(len >= 0); VERIFY((u_int)(off + len) <= pbuf->pb_packet_len); if (pbuf->pb_type == PBUF_TYPE_MBUF) m_copyback(pbuf->pb_mbuf, off, len, src); else if (pbuf->pb_type == PBUF_TYPE_MBUF) { if (len) memcpy(&((uint8_t *)pbuf->pb_data)[off], src, len); } else panic("%s: bad pb_type: %d", __func__, pbuf->pb_type); } PVS-Studio warning: V517 CWE-570 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 340, 343. pf_pbuf.c 340 To clarify, I'll highlight the main point: if (A) foo(); else if (A) Unreachable_code; else panic(); If the A condition is true, then the body of the first if operator is executed. If not, a repeated check doesn't make sense and the panic function is called immediately. A part of the code is generally unattainable. Here is an error either in logic, or a typo in one of the conditions. Later in this same file, there is the function pbuf_copy_data, which apparently was written by using Copy-Paste and contains the same error. Warning: V517 CWE-570 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 358, 361. pf_pbuf.c 358 The defect CWE-670 says that, most likely, in the code something is not working as intended. Fragment N8, N9, N10 static void in_ifaddr_free(struct ifaddr *ifa) { IFA_LOCK_ASSERT_HELD(ifa); if (ifa->ifa_refcnt != 0) { panic("%s: ifa %p bad ref cnt", __func__, ifa); /* NOTREACHED */ } if (!(ifa->ifa_debug & IFD_ALLOC)) { panic("%s: ifa %p cannot be freed", __func__, ifa); /* NOTREACHED */ } if (ifa->ifa_debug & IFD_DEBUG) { .... } PVS-Studio warning: V646 CWE-670 Consider inspecting the application's logic. It's possible that 'else' keyword is missing. in.c 2010 Perhaps, there is no error in this code. However, this place looks very suspiciously: } if (!(ifa->ifa_debug & IFD_ALLOC)) { It's not normal as it's not the done thing. It would be more logical to start writing if on a new line. Code authors should check out this place. Perhaps, the key word else is omitted here and the code should be as follows: } else if (!(ifa->ifa_debug & IFD_ALLOC)) { Or you just need to add a line break, so that this code would confuse neither the analyzer, nor the colleagues maintaining this code. Similar suspicious fragments can be found here: Fragment N11, N12, N13, N14 int dup2(proc_t p, struct dup2_args *uap, int32_t *retval) { .... while ((fdp->fd_ofileflags[new] & UF_RESERVED) == UF_RESERVED) { fp_drop(p, old, fp, 1); procfdtbl_waitfd(p, new); #if DIAGNOSTIC proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED); #endif goto startover; } .... startover: .... } PVS-Studio warning: V612 CWE-670 An unconditional 'goto' within a loop. kern_descrip.c 628 This code is very strange. Note that the body of the while operator ends with the goto operator. In doing so, the operator 'continue' is not used the body of the loop. This means that the body of the loop will be executed no more than once. Why create a loop, if it does not perform more than one iteration? Really, it would be better to use the operator 'if', then it would not raise any questions. I think that's an error, and in the cycle something is written wrong. For example, perhaps, before the operator 'goto' there is no condition. Similar "one-time" loops are found 3 more times: There are various reasons because of which null pointer dereferencing may happen and PVS-Studio analyzer, depending on the situation, can assign them various CWE-ID: When writing the article I considered it reasonable to collect all the errors of this type in one section. Fragment N15 I'll start with complex and large functions. First, we'll look at the function netagent_send_error_response in which the pointer, passed in the session argument, gets dereferenced. static int netagent_send_error_response( struct netagent_session *session, u_int8_t message_type, u_int32_t message_id, u_int32_t error_code) { int error = 0; u_int8_t *response = NULL; size_t response_size = sizeof(struct netagent_message_header); MALLOC(response, u_int8_t *, response_size, M_NETAGENT, M_WAITOK); if (response == NULL) { return (ENOMEM); } (void)netagent_buffer_write_message_header(.....); if ((error = netagent_send_ctl_data(session->control_unit, (u_int8_t *)response, response_size))) { NETAGENTLOG0(LOG_ERR, "Failed to send response"); } FREE(response, M_NETAGENT); return (error); } Note that the pointer session is dereferenced in the expression session->control_unit without any preliminary check. Whether a dereference of a null pointer occurs or not, depends on what actual arguments will be passed to this function. Now let's see how the function netagent_send_error_response discussed above, is used in the function netagent_handle_unregister_message. static void netagent_handle_unregister_message( struct netagent_session *session, ....) #pragma unused(payload_length, packet, offset) u_int32_t response_error = NETAGENT_MESSAGE_ERROR_INTERNAL; if (session == NULL) { NETAGENTLOG0(LOG_ERR, "Failed to find session"); response_error = NETAGENT_MESSAGE_ERROR_INTERNAL; goto fail; } netagent_unregister_session_wrapper(session); netagent_send_success_response(session, .....); return; fail: netagent_send_error_response( session, NETAGENT_MESSAGE_TYPE_UNREGISTER, message_id, response_error); } PVS-Studio warning: V522 CWE-628 Dereferencing of the null pointer 'session' might take place. The null pointer is passed into 'netagent_send_error_response' function. Inspect the first argument. Check lines: 427, 972. network_agent.c 427 Here Data Flow analysis, implemented in PVS-Studio, shows itself. The analyzer notes that if the session pointer was equal to NULL, then some information would be written to the log, and then it goes to a label fails. Next, a call to the function netagent_send_error_response will follow: fail: netagent_send_error_response( session, NETAGENT_MESSAGE_TYPE_UNREGISTER, message_id, response_error); Note that the ill-fated session pointer that is equal to NULL is passed to the function as an actual argument. As we know, in the function netagent_send_error_response there is no protection in this case and a null pointer dereference will occur. Fragment N16 The next situation is similar to the previous one. The function code is shorter, but we'll have to deal with it the same slowly and thoroughly. void * pf_lazy_makewritable(struct pf_pdesc *pd, pbuf_t *pbuf, int len) { void *p; if (pd->lmw < 0) return (NULL); VERIFY(pbuf == pd->mp); p = pbuf->pb_data; if (len > pd->lmw) { .... } Note that the pointer pbuf is dereferenced without prior check for NULL. In code there is a check "VERIFY(pbuf == pd->mp)". However, pd-> mp may be equal to NULL, so the check cannot be seen as protection against NULL. Note. Please, remember that I'm not familiar with the XNU Kernel code and I may be wrong. Possibly pd->mp will never store the NULL value. Then all my reasoning is wrong and there is no error here. However, such code still needs to be checked again. Let's continue and see how to the described function pf_lazy_makewritable is used. static int pf_test_state_icmp(....) { .... if (pf_lazy_makewritable(pd, NULL, off + sizeof (struct icmp6_hdr)) == NULL) return (PF_DROP); .... } PVS-Studio warning: V522 CWE-628 Dereferencing of the null pointer 'pbuf' might take place. The null pointer is passed into 'pf_lazy_makewritable' function. Inspect the second argument. Check lines: 349, 7460. pf.c 349 NULL is passed to the function pf_lazy_makewritable as the second actual argument. This is very strange. Let's say, a programmer thinks that "VERIFY(pbuf == pd->mp)" will protect the program from the null pointer. Then the question arises: why write such code? Why call a function passing clearly incorrect argument? Therefore, it seems to me that actually, the function pf_lazy_makewritable must be able to accept a null pointer and handle this case in a special way, but it doesn't do so. This code deserves thorough verification by a programmer, and the PVS-Studio analyzer is definitely right, drawing our attention to it. Fragment N17 Let's relax for a while and consider a simple case. typedef struct vnode * vnode_t; int cache_lookup_path(...., vnode_t dp, ....) { .... if (dp && (dp->v_flag & VISHARDLINK)) { break; } if ((dp->v_flag & VROOT) || dp == ndp->ni_rootdir || dp->v_parent == NULLVP) break; .... } PVS-Studio warning: V522 CWE-690 There might be dereferencing of a potential null pointer 'dp'. vfs_cache.c 1449 Look at the check: if (dp && (dp->v_flag & VISHARDLINK)) It tells us that a pointer dp can be null. However further on, the pointer is dereferenced before the preliminary check: if ((dp->v_flag & VROOT) || ....) Fragment N18 In the previous example, we saw a situation where the pointer was checked before dereference, and then check in code was forgotten. But much more often you may come across a situation when pointer is dereferenced first, and only then is checked. The code of the XNU Kernel project was no exception. First, let's consider a synthetic sample for better understanding what it is about: p[n] = 1; if (!p) return false; Now let's see how these errors look like in reality. We'll start with the function of names comparison. The comparison functions are very insidious :). bool IORegistryEntry::compareName(....) const { const OSSymbol * sym = copyName(); bool isEqual; isEqual = sym->isEqualTo( name ); // <= if( isEqual && matched) { name->retain(); *matched = name; } if( sym) // <= sym->release(); return( isEqual ); } PVS-Studio warnings: V595 CWE-476 The 'sym' pointer was utilized before it was verified against nullptr. Check lines: 889, 896. IORegistryEntry.cpp 889 I've marked with comments like "//< =" lines of code which are of interest for us. As you can see, the first pointer is dereferenced. Further, in code, there is a check for pointer equality to nullptr. But it is clear at once that if the pointer is null, then there will be a null pointer dereferencing and function, in fact, is not ready for such a situation. Fragment N19 The following error occurred because of a typo. static int memorystatus_get_priority_list( memorystatus_priority_entry_t **list_ptr, size_t *buffer_size, size_t *list_size, boolean_t size_only) { .... *list_ptr = (memorystatus_priority_entry_t*)kalloc(*list_size); if (!list_ptr) { return ENOMEM; } .... } PVS-Studio warning: V595 CWE-476 The 'list_ptr' pointer was utilized before it was verified against nullptr. Check lines: 7175, 7176. kern_memorystatus.c 7175 The analyzer sees that the variable is first dereferenced, and in the following line is checked for equality to nullptr. This interesting error occurred due to the fact that the programmer forgot to write the character '*'. Actually, correct code should be as follows: *list_ptr = (memorystatus_priority_entry_t*)kalloc(*list_size); if (!*list_ptr) { return ENOMEM; } We can say that the error was identified indirectly. However, it does not matter, because the most important thing is that the analyzer drew our attention to abnormal code and we saw the error. Fragment N20 - N35 In the XNU Kernel code there are many errors identified thanks to the V595 diagnostic. However, considering all of them will be boring. So, I will regard just one case, and cite a list of messages that indicate errors. inline void inp_decr_sndbytes_unsent(struct socket *so, int32_t len) { struct inpcb *inp = (struct inpcb *)so->so_pcb; struct ifnet *ifp = inp->inp_last_outifp; if (so == NULL || !(so->so_snd.sb_flags & SB_SNDBYTE_CNT)) return; if (ifp != NULL) { if (ifp->if_sndbyte_unsent >= len) OSAddAtomic64(-len, &ifp->if_sndbyte_unsent); else ifp->if_sndbyte_unsent = 0; } } PVS-Studio warning: V595 CWE-476 The 'so' pointer was utilized before it was verified against nullptr. Check lines: 3450, 3453. in_pcb.c 3450 I suggest the reader to independently follow the fate of the pointer so and make sure, that the code is written incorrectly. Other errors: Fragment N36, N37 And the last couple bugs on the use of NULL pointers. static void feth_start(ifnet_t ifp) { .... if_fake_ref fakeif; .... if (fakeif != NULL) { peer = fakeif->iff_peer; flags = fakeif->iff_flags; } /* check for pending TX */ m = fakeif->iff_pending_tx_packet; .... } PVS-Studio warning: V1004 CWE-476 The 'fakeif' pointer was used unsafely after it was verified against nullptr. Check lines: 566, 572. if_fake.c 572 I think, this code doesn't need any comments. Just look how the pointer fakeif is checked and used. The last similar case: V1004 CWE-476 The 'rt->rt_ifp' pointer was used unsafely after it was verified against nullptr. Check lines: 138, 140. netsrc.c 140 I came across a couple of errors, related to the buffer overrun. A very unpleasant kind of error for such a responsible project, like XNU Kernel. Different variants of array overrun can be classified with different CWE ID, but in this case, the analyzer chose CWE-119. Fragment N38 For a start, let's see how some macros are declared. #define IFNAMSIZ 16 #define IFXNAMSIZ (IFNAMSIZ + 8) #define MAX_ROUTE_RULE_INTERFACES 10 It is important for us to remember that: And now we'll look at the function where the buffer overrun is possible when using the snprintf and memset functions. So, 2 errors take place here. static inline const char * necp_get_result_description(....) { .... char interface_names[IFXNAMSIZ][MAX_ROUTE_RULE_INTERFACES]; .... for (index = 0; index < MAX_ROUTE_RULE_INTERFACES; index++) { if (route_rule->exception_if_indices[index] != 0) { ifnet_t interface = ifindex2ifnet[....]; snprintf(interface_names[index], IFXNAMSIZ, "%s%d", ifnet_name(interface), ifnet_unit(interface)); } else { memset(interface_names[index], 0, IFXNAMSIZ); } } .... } PVS-Studio warnings: Notice how the two-dimensional array interface_names is declared: char interface_names[IFXNAMSIZ][MAX_ROUTE_RULE_INTERFACES]; // i.g.: char interface_names[24][10]; But this array is used as if it is as follows: char interface_names[MAX_ROUTE_RULE_INTERFACES][IFXNAMSIZ]; // i.g.: char interface_names[10][24]; In the result we get a mush of data. Someone may say without thinking, that there is nothing to worry about, because both arrays hold the same number of bytes. No, it's bad. The elements of the array interface_names[10..23][....] are not used, because the variable index in the loop takes values [0..9]. But the elements of interface_names[0..9][....] begin to overlap each other. I.e. some data overwrites the other. The result is just nonsense. A part of the array remains uninitialized, and the other part contains a "mush", when data was written over the already written data. Fragment N39 Later in this same file necp_client.c there is another function that contains very similar errors. #define IFNAMSIZ 16 #define IFXNAMSIZ (IFNAMSIZ + 8) #define NECP_MAX_PARSED_PARAMETERS 16 struct necp_client_parsed_parameters { .... char prohibited_interfaces[IFXNAMSIZ] [NECP_MAX_PARSED_PARAMETERS]; .... }; static int necp_client_parse_parameters(...., struct necp_client_parsed_parameters *parsed_parameters) { .... u_int32_t length = ....; .... if (length <= IFXNAMSIZ && length > 0) { memcpy(parsed_parameters->prohibited_interfaces[ num_prohibited_interfaces], value, length); parsed_parameters->prohibited_interfaces[ num_prohibited_interfaces][length - 1] = 0; .... } PVS-Studio warning: All the same. The array: char prohibited_interfaces[IFXNAMSIZ][NECP_MAX_PARSED_PARAMETERS]; is handled as if it is: char prohibited_interfaces[NECP_MAX_PARSED_PARAMETERS][IFXNAMSIZ]; Defects CWE-563 detected by PVS-Studio are often the consequences of typos. Now we'll consider one such beautiful typo. Fragment N40; } .... } PVS-Studio warning: V519 CWE-563 The 'wrap.Seal_Alg[0]' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 2070, 2071. gss_krb5_mech.c 2071 The value 0xff is written in the same element of the array twice. I looked at the code and concluded that the programmers actually wanted to write here: wrap.Seal_Alg[0] = 0xff; wrap.Seal_Alg[1] = 0xff; Judging by the name of the function, it is associated with a network authentication protocol. And such a kludge. Just terrifying. You can buy PVS-Studio here. Our analyzer will help prevent many of these errors! Fragment N41, N42, N43, N44 static struct mbuf * pf_reassemble(struct mbuf *m0, struct pf_fragment **frag, struct pf_frent *frent, int mff) { .... m->m_pkthdr.csum_flags &= ~CSUM_PARTIAL; m->m_pkthdr.csum_flags = CSUM_DATA_VALID | CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID; .... } PVS-Studio warning: V519 CWE-563 The 'm->M_dat.MH.MH_pkthdr.csum_flags' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 758, 759. pf_norm.c 759 String: m->m_pkthdr.csum_flags &= ~CSUM_PARTIAL; has no practical meaning. In the next string the variable m->m_pkthdr.csum_flags will be assigned a new value. I don't know how the correct code should actually look like, but I would venture to guess that the symbol '|' was lost. In my humble opinion, your code should look like this: m->m_pkthdr.csum_flags &= ~CSUM_PARTIAL; m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID; There are 3 warnings pointing at similar errors: A very insidious type of defect that is invisible in the debug version. If the reader is not familiar with it yet, before you continue reading, I suggest to be acquainted with the following links: If the reader wonders why overwrite private data that is stored in the memory, I recommend the article "Overwriting memory - why?". So, it is important to overwrite private data in memory, but sometimes the compiler removes the corresponding code, because, from its point of view, it is redundant. Let's see what interesting things were found in the XNU Kernel on this topic. Fragment N45 __private_extern__ void YSHA1Final(unsigned char digest[20], YSHA1_CTX* context) { u_int32_t i, j; unsigned char finalcount[8]; .... /* Wipe variables */ i = j = 0; memset(context->buffer, 0, 64); memset(context->state, 0, 20); memset(context->count, 0, 8); memset(finalcount, 0, 8); // <= #ifdef SHA1HANDSOFF YSHA1Transform(context->state, context->buffer); #endif } PVS-Studio warning: V597 CWE-14 The compiler could delete the 'memset' function call, which is used to flush 'finalcount' buffer. The memset_s() function should be used to erase the private data. sha1mod.c 188 The compiler may remove the line of code which I marked with the comment "// <=" in order to optimize the Release-version. Almost certainly, it will act in this way. Fragment N46 __private_extern__ void YSHA1Transform(u_int32_t state[5], const unsigned char buffer[64]) { u_int32_t a, b, c, d, e; .... state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Wipe variables */ a = b = c = d = e = 0; } PVS-Studio warning: V1001 CWE-563 The 'a' variable is assigned but is not used until the end of the function. sha1mod.c 120 The compiler may not generate code that resets the variables, since they are not used in the function. I would like to draw your attention to the fact that PVS-Studio analyzer interpreted this suspicious situation as CWE-563. The fact of the matter is that the same defect can often be interpreted as different CWE and in this case, the analyzer chose CWE-563. However, I decided to include this code to CWE-14 because it explains more accurately, what's wrong with this code. The defect CWE-783 occurs where the programmer confused priorities of the operations and wrote code that works not the way he had planned. Often these errors are made because of carelessness or missing parentheses. Fragment N47 int getxattr(....) { .... if ((error = copyinstr(uap->attrname, attrname, sizeof(attrname), &namelen) != 0)) { goto out; } .... out: .... return (error); } PVS-Studio warning: V593 CWE-783 Consider reviewing the expression of the 'A = B != C' kind. The expression is calculated as following: 'A = (B != C)'. vfs_syscalls.c 10574 A classic error. I meet a lot of such bugs in various programs (proof). The root cause is that for some reason programmers seek to cram more just in one line. As a result, instead of: Status s = foo(); if (s == Error) return s; they write: Status s; if (s = foo() == Error) return s; And contribute the error to the code. As a result, the return operator returns incorrect error status equal to 1, but not the value that is equal to a constant Error. I regularly criticize such code and recommend not to "shove in" in one line more than one action. "Stuffing in" doesn't really reduce the code size, but provokes a different error. See the chapter 13 from the book "The Ultimate Question of Programming, Refactoring, and Everything" for more details. See the chapters: Let's get back to code from the XNU Kernel. In case of an error, the function getxattr will return value of 1, not the actual error code. Fragment N48-N52 static void memorystatus_init_snapshot_vmstats( memorystatus_jetsam_snapshot_t *snapshot) { kern_return_t kr = KERN_SUCCESS; mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; vm_statistics64_data_t vm_stat; if ((kr = host_statistics64(.....) != KERN_SUCCESS)) { printf("memorystatus_init_jetsam_snapshot_stats: " "host_statistics64 failed with %d\n", kr); memset(&snapshot->stats, 0, sizeof(snapshot->stats)); } else { + .... } PVS-Studio warning: V593 CWE-783 Consider reviewing the expression of the 'A = B != C' kind. The expression is calculated as following: 'A = (B != C)'. kern_memorystatus.c 4554 Variable kr can be assigned only two values: 0 or 1. Due to this printf function always prints the number 1 instead of the actual status, which the function host_statistics64 returned. Article turns out to be large. I guess I'm tiring not only myself, but also the readers. So I'm reducing the number of fragments regarded in the article. Other similar defects are uninteresting to be considered, and I shall confine myself to the message list: There is an enormous number of ways how to get undefined or unspecified behavior in program written in C or C++. Therefore, PVS-Studio provides quite a lot of diagnostics aimed at identifying such problems: V567, V610, V611, V681, V704, V708, V726, V736. In the case of XNU, the analyzer has identified only two weaknesses CWE-758, related to undefined behavior caused by a shift of negative numbers. Fragment N53, N54 static void pfr_prepare_network(union sockaddr_union *sa, int af, int net) { .... sa->sin.sin_addr.s_addr = net ? htonl(-1 << (32-net)) : 0; .... } PVS-Studio warning: V610 CWE-758 Undefined behavior. Check the shift operator '<<'. The left operand '-1' is negative. pf_table.c 976 Shift of a negative number to the left leads to undefined behavior. In practice, this code may work well exactly as the programmer expects. But still, this code is incorrect and should be corrected. This can be done in the following way: htonl((unsigned)(-1) << (32-net)) PVS-Studio analyzer finds another shift here: V610 CWE-758 Undefined behavior. Check the shift operator '<<'. The left operand '-1' is negative. pf_table.c 983 XNU Kernel developers should be praised for the fact that the analyzer could not find any problems with memory leaks (CWE-401). There are only 3 suspicious places when the delete operator is not called when the object initialization error. While I'm not sure that this is an error. Fragment N55, N56, N57 IOService * IODTPlatformExpert::createNub(IORegistryEntry * from) { IOService * nub; nub = new IOPlatformDevice; if (nub) { if( !nub->init( from, gIODTPlane )) { nub->free(); nub = 0; } } return (nub); } V773 CWE-401 The 'nub' pointer was assigned values twice without releasing the memory. A memory leak is possible. IOPlatformExpert.cpp 1287 If the function init is not able to initialize an object, possibly a memory leak will occur. In my opinion, it lacks the operator delete, and should have been written like this: if( !nub->init( from, gIODTPlane )) { nub->free(); delete nub; nub = 0; } I'm not sure that I'm right. Perhaps, the function free destroys the object itself, performing the operation "delete *this;". I didn't carefully sort all that out, because by the time I reached those warnings I was already tired. Similar analyzer warnings: The defect CWE-129 says that the variables, used for indexing of elements in the array, are incorrectly or insufficiently verified. Consequently, the array overrun may occur. Fragment N58-N61 IOReturn IOStateReporter::updateChannelValues(int channel_index) { .... state_index = _currentStates[channel_index]; if (channel_index < 0 || channel_index > (_nElements - state_index) / _channelDimension) { result = kIOReturnOverrun; goto finish; } .... } PVS-Studio warning: V781 CWE-129 The value of the 'channel_index' variable is checked after it was used. Perhaps there is a mistake in program logic. Check lines: 852, 855. IOStateReporter.cpp 852 Negative values protection is implemented improperly. First, the element is retrieved from an array, and only after that, the check follows that the index isn't negative. I think this code should be rewritten as follows: IOReturn IOStateReporter::updateChannelValues(int channel_index) { .... if (channel_index < 0) { result = kIOReturnOverrun; goto finish; } state_index = _currentStates[channel_index]; if (channel_index > (_nElements - state_index) / _channelDimension) { result = kIOReturnOverrun; goto finish; } .... } You may need to add checks that the value channel_index is not greater than the size of the array. I'm not familiar with the code, so I'll leave it to the discretion of the XNU Kernel developers. Similar errors: CWE-480 defects are commonly related to some typos in expressions. There are usually not very much of them, but they are very fun. You just look at the errors and wonder how they could be done. However, as we have already demonstrated in the articles that no one is insured from such errors, even highly skilled programmers. Fragment N62 #define NFS_UC_QUEUE_SLEEPING 0x0001 static void nfsrv_uc_proxy(socket_t so, void *arg, int waitflag) { .... if (myqueue->ucq_flags | NFS_UC_QUEUE_SLEEPING) wakeup(myqueue); .... } PVS-Studio warning: V617 CWE-480 Consider inspecting the condition. The '0x0001' argument of the '|' bitwise operation contains a non-zero value. nfs_upcall.c 331 An essence "awakes" more often that it's needed. Rather, it "is woken" constantly, regardless of the conditions. Most likely, the code here is supposed to be as follows: if (myqueue->ucq_flags & NFS_UC_QUEUE_SLEEPING) wakeup(myqueue); PVS-Studio analyzer was unable to classify the following error according to CWE. From my point of view, we are dealing with CWE-665. Fragment N63 extern void bzero(void *, size_t); static struct thread thread_template, init_thread; struct thread { .... struct thread_qos_override { struct thread_qos_override *override_next; uint32_t override_contended_resource_count; int16_t override_qos; int16_t override_resource_type; user_addr_t override_resource; } *overrides; .... }; void thread_bootstrap(void) { .... bzero(&thread_template.overrides, sizeof(thread_template.overrides)); .... } PVS-Studio warning: V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'thread_template.overrides' class object. thread.c 377 A programmer took the address of the variable, containing a pointer and nullified the variable, using the bzero function. In fact, just recorded nullptr in the pointer. To use the bzero function is a very strange unnatural way to reset the value of the variable. It would be much easier to write: thread_template.overrides = NULL; Hence, I conclude that a programmer wanted to reset the buffer, but occasionally nullified the pointer. Therefore, correct code should be like this: bzero(thread_template.overrides, sizeof(*thread_template.overrides)); CWE-691 reveals anomalies in the sequence of instructions execution. Another anomaly is also possible - the code presentation doesn't correspond to the way it works. I faced exactly this case in the XNU Kernel code. Fragment N64 Hooray, we got to the last code fragment! There may be other errors that I didn't notice when viewing the report, issued by the analyzer, but I'd like to remind that it was not my purpose to identify as many errors as possible. In any case, developers of the XNU Kernel will be able to study the report better, because they are familiar with the project code. So let's stop at the beautiful number 64 that is consonant with the name of our site viva64. Note. For those who wonder where "viva64" came from, I suggest to get acquainted with the section "PVS-Studio project - 10 years of failures and successes. void vm_page_release_startup(vm_page_t mem); void pmap_startup( vm_offset_t *startp, vm_offset_t *endp) { .... // -debug code remove if (2 == vm_himemory_mode) { for (i = 1; i <= pages_initialized; i++) { .... } } else // debug code remove- /* * Release pages in reverse order so that physical pages * initially get allocated in ascending addresses. This keeps * the devices (which must address physical memory) happy if * they require several consecutive pages. */ for (i = pages_initialized; i > 0; i--) { if(fill) fillPage(....); vm_page_release_startup(&vm_pages[i - 1]); } .... } PVS-Studio warning: V705 CWE-691 It is possible that 'else' block was forgotten or commented out, thus altering the program's operation logics. vm_resident.c 1248 Perhaps there is no error here. However, I'm very confused by the keyword else. The code is formatted in such a way as if the loop is always executed. Actually the loop is executed only when the condition (2 == vm_himemory_mode) is false. In the macOS world a new powerful static code PVS-Studio analyzer appeared that is able to detect errors and potential vulnerabilities in C, and C++. I invite everyone to try out our analyzer on your projects and to assess its abilities. Thanks for your attention and don't forget to share the information with colleagues that PVS-Studio is now available ...
https://www.viva64.com/en/b/0566/
CC-MAIN-2019-09
refinedweb
6,303
57.47
Hi and welcome to Just Answer!As a general rule - interest from coupons on the decedent's bonds is constructively received by the decedent if the coupons matured in the decedent's final tax year, but had not been cashed. Include the interest income on the final return. Specifically for series EE or series I US savings bonds, owned by a cash method taxpayer who reported the interest each year, or by an accrual method taxpayer are transferred because of death, the increase in value of the bonds (interest earned) in the year of death up to the date of death must be reported on the decedent's finalreturn.If the bonds transferred because of death were owned by a cash method taxpayer who chose not to report the interest each year and had purchased the bonds entirely with personal funds, interest earned before death must be reported in one of the following ways.1..2..So far - if you choose to redeem all bonds in 2013 - the interest is reported on your 2013 tax return (not 2012 tax return). The actual tax liability is based on your total income - the taxable interest is added to your other taxable income. You may review tax rate schedule on the last page of this publication - As long as the interest is reported in the year of maturity or the year or redemption - there is no penalty.Please be aware that the interest is not taxable on your state income tax return. Thank you for the quick reply. My apologies herewith for not understanding some of the legal terminology that you've used in your answer to my question - and which, therefore, has clouded my comprehension of your answer. My understanding of the tax return process associated with my dad's death and his estate is that: (1) A personal income tax return for 2010, the year of his death, should have been filed by April 15th, 2011, and the savings bonds could have been cashed out and included as income on that return. (2) Following his death, an estate account was created to deal with any estate tax issues that arose following his death - and it was into this account that the monies from the savings bonds was just deposited by the Executor of the Estate in this year. (3) Income on an Estate Tax Return is taxed at a different rate than on a Personal Income Tax Return - with any income exceeding a total of approximately $11,000 being taxed at a rate of 35%. ......Hence, inasmuch as the interest income on the savings bonds was not declared on the 2010 Personal Income Tax Return for my father, nor on the 2011 Estate Tax Return but will, instead, be declared on the 2012 Estate Tax Return - it appears to me that it will be taxed at the rate of 35%. Is this correct? Additionally, inasmuch as the savings bonds were cashed in near the end of last year (i.e., 2012) and the monies added to the Estate Account - and the 2012 tax return is being filed late this year, without an extension having been filed for, with no estimated taxes having been paid by April 15th - it appears to me that there will be penalties for having filed the tax return late and for not having made an on-time payment for the estimated tax on the income of the savings bond interest. The penalties for filing late (without an extension) and for having not paid an estimated tax on time appears to be as much as 25% of the total tax that was due - with an interest charge of 3%. Is this correct? Thank you very, very much! - One last and final quick question: There is a possibility that the Executor of my dad's estate did not cash in his savings bonds and deposit them into the Estate Account until the first part of January 2013. If this should happen to be the case and the income from the interest on the savings bonds is declared and filed on time with the 2013 Estate Tax Return (and is paid on time), then there should be no penalties for late filing or late payment - correct? Hello! I received a "pop-up" window that said a tax expert needed to chat with me about my last question. However, when I clicked on the button to begin the chat - nothing happened. Do I need to continue waiting for the "chat" to begin? Thank you so very much! You've been a great help. Have a wonderful day! Sincerely Yours: Tracy
http://www.justanswer.com/tax/7wytl-hello-i-ve-tricky-question-think.html
CC-MAIN-2016-07
refinedweb
769
62.92
Server :: Heartbeat Not Assigning Virtual IP For Interface Eth0Jul 19, 2010 I have followed th given site for HA configuration in my virtualbox but heartbeat is not assigning virtual IP for interface eth0 [URL]...View 1 Replies I have followed th given site for HA configuration in my virtualbox but heartbeat is not assigning virtual IP for interface eth0 [URL]...View 1 Replies i have a root-server and a vserver.the vserver should provide services if the root-server is not reachable. i would like to configure heartbeat. its runnung on the root, but on the vserver i get an error: if i set the following in the ha.cf: Code: bcast eth0 # Linux Code: heartbeat[14629]: 2011/02/25_16:06:10 info: heartbeat: version 2.1.3 heartbeat[14629]: 2011/02/25_16:06:11 info: Heartbeat generation: 1298641135 heartbeat[14629]: 2011/02/25_16:06:11 ERROR: glib: Error setting socket option [code]... I found multiple sites explaining how to add IPs to a network interface as virtual interface like eth0:0. However I can add IPs to an interface as well using the ip command: ip a a 192.168.2.2/24 dev eth0 What I want to know is how I can make this persistent on rhel/centos.View 2 Replies View Related I have set 'ONBOOT=no' in interface script '/etc/sysconfig/network-scripts/ifcfg-eth0:2' but my interface bring up at boot time, what is the problem , I have checked it 3 or 4 diff os/machine but the same issue. Can anyone please help me to disable virtual IP's at boot time that network script make it up every boot time.View 4 Replies View Related I just had an ATT Uverse RG installed. However my Smoothwall router that previously worked fine with the ADSL SpeedStream is no longer accepting an address assignment DHCP ip address from this new gateway. (3800HGV-B)Any thoughts ideas or experience working with this hardware? ATT only supports Windows and MacView 2 Replies View Related I have to do a project on network security.For that i have to capture the packets from the device. I installed libpcap tool in ubuntu. If I give ifconfig -a it lists out eth0, wlan0, lo. I am able to connect to the internet via eth0. But when I give #include <stdio.h> #include <pcap.h> int main() { char *dev, errbuf[PCAP_ERRBUF_SIZE]; [Code]... It says device is null. I'm not able to run sniffex.c program also. All I want to do is to capture the live network level packets and analyse them. Just completed installing Xubuntu 9.04 to my old Dell Latitude CPi and it seems to be working quite well. However I need to assign interface eth0 to my pcmcia network card (as opposed to eth1 or eth2). I have two cards to try out. One of them comes up as eth1 and the other as eth2. There is no eth0 listed when I run ifconfig -a. There is no built-in network cards on the laptop, so I don't know why it won't assign eth0 to either of the cards. how to assign eth0 to either of the two PCMCIA network cards.? My network name is eth2 it was changed by some reason and now i got these errors... i installed, reinstalled, re re installed, tried to run the asistant but no luck :/ Code: * Stopping the Firestarter firewall... eth0: error fetching interface information: Device not found eth0: error fetching interface information: Device not found eth0: error fetching interface information: Device not found [code].... I'm running a dual boot Ubuntu 10.04/Backtrack 4 (Ubuntu 8.10) system. I can get internet in the BT4 side but not in the Lucid side. In Lucid I can ping my router, and the network manager says I'm good to go, but I can't get to any web sites. It all started when I tried to put my laptop on another network by mimicking the settings of a computer I had just unplugged from the network. MAC address and all. ifconfig eth0: Code: eth0 Link encap:Ethernet HWaddr 00:1f:16:ba:4c:8c inet addr:10.136.9.147 Bcast:10.136.9.159 Mask:255.255.255.240 inet6 addr: fe80::21f:16ff:feba:4c8c/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 [code].... I'm looking for a Postfix Management Web interface for user, domains, etc... The problem is I'm not using mysql for domains/users, so I can't use postfixadmin. I use virtual mailboxes as described here: [URL] Basically all mappings are saved inside an /etc/postfix/vmaps file. The users/passwords files are in /home/vmail/passwd and /home/vmail/shadow. Users are in /home/vmail/$domain/$user I searched for a web management tool that supports my config for weeks now, and can't seem to find any... i is it possible to setup a DHCP server using the loopback or a virtual interface? I installed Sun VirtualBox on my fedora system and want to try and kickstart them from within the same box on a virtual network. Is this possible and has anyone done it? I only have a single NIC in the box and it is on my public network.View 1 Replies View Related When I create virtual ethernet interface and do a ping -I <v_int> <host> the outgoing address is the one of the physical interface and NOT the virtual interface.Is there no chance that trafic will go out with virtual interface address??Incoming trafic is done well i.e. responds to the virtual interface have the virtual address. My problem is that I have 2 modems and want to check both default gw behind the modems. If I do a "normal" ping both are reachable over default route even the modem which is not the default route will not work because ping goes over the working modem.So I have 2 routing tables and want to route the virtual interface to one modem the other to the other modem I have setup a MySQL High Availability Cluster with two nodes using DRBD & Heartbeat. I have successfully installed the cluster but one question which is still not solved is that Heartbeat monitors failover of network or server failure, etc. What will happen if MySQL service gets stopped or do not start. This heartbeat-DRBD cluster does not take any action on that part. Now I want to enable this feature too which also monitors MySQL service. I have gone through MON help on web but could not find out any good step by step tutorial. The following are the output of command "ifconfig -a": [Code].... The interface "eth0", which is down, was not displayed, but loopback interface has been displayed. So, how can I make my application display all interfaces, including the interfaces which are down, but excluding the loopback interface?. I booted an OS from a live CD. The OS boots successfully but eth0 fails to start. I checked lspci, it outputs these Ethernet card details: (Broadcom Netextreme II BCM5716 GBabyte ethernet) ifconfig -a returns only the loopback interfaces lo and sit0. The output of dmesg | grep -I 'eth' is: "Netfront : initializing network ethernet driver" When I run service network restart I get: "Obtaining IP for lo [FAILED] WARNING: Deprecated config gile /etc/modprobe.conf , all config files belong into /etc/modprobe.d/ Device eth0 does not seem to be present, delaying initialization [FAILED]" The output of MII-tool -v is: No MII interface found. I was also able to find the kernel module bnx2.ko. I did insmod and lsmod lists it. I have already tried reloading the drivers, restarting the interface (which is missing) and every other solution I found on this forum (well... not exactly all of them but many of them) uname -a gives Linux hostname 2.6.35-27-generic #48-Ubuntu SMP Tue Feb 22 20:25:46 UTC 2011 x86_64 GNU/Linux [Code].... Is it possible to do jboss application server fail over by using heartbeat on rhel5?View 1 Replies View Related'm having the same Harker2010 's problem.Running 10.04 LTS on a Dell latitude D-820, and switching between lan and wifi worked OK until last upgrade.Harker2010's screenshots are also valid for my problem. I've tried everything I see on this post but the problem still there.View 1 Replies View Related 5 Replies View Related I am trying to connect my fresh new Ubuntu 10.10 to my router. However I am having a bit of difficulty. This is what I have done so far: Code: lspci My devise is a Broadcom Corporation BCM4311 802.11b/g WLAN (rev 02). Then: Code: sudo ifconfig eth0 up sudo iwlist eth0 scan I get eth0 Interface doesn't support scanning. 7 Replies View Related I got two IP's in my dedicated server. Both are external IP's. I would like to make connections using 2nd IP address under eth0:0 interface. For example: when using "lynx whatismyip.com" should display my 2nd IP. How to do this using iptables ?View 1 Replies View Related I'd like high-availability feature to firewall (iptables) and openvpn service I'm running at my job. Mi project is two firewall boxes in a active/pasive configuration. And if it's possible sync connections' states. I started reading on heartbeat and I'd like to hear some advices and take away some doubts: For the config I'm planning heartbeat service is enough or it would require a CRM service such as pacemaker.View 3 Replies View Related I am in need of finding out the physical interface corresponds to eth0,eth1,eth2., As similar like the lscfg command which is available in the AIX operating system. The output given below got it from AIX OS. $ lscfg -l ent* ent2 U787B.001.DNWFFC6-P1-T9 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902) ent3 U787B.001.DNWFFC6-P1-T10 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902) ent0 U787B.001.DNWFFC6-P1-C4-T1 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902) ent1 U787B.001.DNWFFC6-P1-C4-T2 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902) Is there any utility/commands available to find out the physical interface ? I am trying to setup a High-Availability HTTP Load Balancer With HAProxy & Heartbeat using the below links. I have all RHEL 5.4 servers hosted on VMWare. [url] [url] This is the scenario, as given in the links as wells as my setup. Load Balancer 1 Load Balancer 2 Web Server 1 Web Server 2 I have followed all the steps mentioned in the links religiously except the 2.2 here, in which it is asking to configure the vhosts. I could not really understand , what is to be placed in /etc/httpd/conf.d/vhosts.conf file and in which Web Server. Due to this step only, I think I am failing in Failover test given in Point 4.1 here. I am able to open the webpage by [url].
https://linux.bigresource.com/Server-heartbeat-not-assigning-virtual-IP-for-interface-eth0-evc3VNBOa.html
CC-MAIN-2021-17
refinedweb
1,877
74.29
import os with open("filename", "r+") as file: content = file.readline() while(content!=""): print(content) content = file.readline() file.close Here is what the above code is Doing: 1. Opening the file in read+ mode. This means that we can read from the file, and write to it. 2. Reading the first line of the file into the variable content. 3. Printing the contents of content. 4. Reading the next line of the file into content. 5. Going back to step 3. 6. Once we reach the end of the file, the while loop will end, and the file will be closed.
https://myedukit.com/coders/python-examples/code-for-showing-contents-of-a-file-and-printing-it-in-python/
CC-MAIN-2022-21
refinedweb
102
87.11
C Tutorial The C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. The C is the most widely used computer language, it keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers. Audience. Execute C Online For most of the examples given in this tutorial you will find Try it option, so just make use of this option to execute your C programs at the spot and enjoy your learning. Try following example using Try it option available at the top right corner of the below sample code box − #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! \n"); return 0; }
http://www.tutorialspoint.com/cprogramming/index.htm
CC-MAIN-2015-32
refinedweb
140
51.58
Sketch for Lightning Sensor Hi all, Has anyone developed a MySensors sketch for the AS3935 Digital Lightning Sensor that's listed in the MySensors store? Playingwithfusion, the manufacturer of the sensor, has a sample sketch, but being new to MySensors, I need some help setting this up to send data to the MS gateway. Thanks in advance for any help. Cheers Al - BulldogLowell Contest Winner last edited by Playingwithfusion cool sensor. Were you able to get it working with your arduino already? It looks like you have a few options, but you could try first getting it to work with SoftSPI.h library, and moving the MOSI, MISO and SCLK pins off of the MySensors Hardware SPI pins. Alternatively, you could try to implement using I2C, but I didn't see an example (maybe the manufacturer can provide that). Once you have it working with SoftSPI or I2C, it would be easy to help you get it to work with your MySensors Gateway. We can help you with the program, but testing would be yours to do, so try to get it working as above, and post that code. cool sensor. Were you able to get it working with your arduino already? Thanks for the response. I haven't hooked it up yet, hopefully tomorrow although not a lot of lightning this time of year where I live to test with. Is it possible to use "normal" SPI and just use a different pin for slave select for it? I was thinking about using pins 8 and 7 for the lightning sensor as to not conflict with the radio on pins 10 and 9, and using pin 3 for IRQ for the sensor versus 2 for the radio. Can both be connected to MOSI, MISO and SCLK? I was looking to use it with a Pro Mini and would need the following SPI parameters: SPI.begin(); SPI.setClockDivider(SPI_CLOCK_DIV8); SPI.setDataMode(SPI_MODE1); SPI.setBitOrder(MSBFIRST); Do these conflict with what's needed for the radio? I guess using I2C would eliminate the conflicts, and will ask Playingwithfusion the details on how to make it work with that. I would like to learn how to get multiple devices playing together using SPI though. I'll read up on SoftSPI as well. Cheers Al - BulldogLowell Contest Winner last edited by presently, MySensors (and @hek can correct me if I am wrong) is still not using interrupt on pin2, so you should be OK there. SPI is a hardware implementation on pins 11, 12, 13 on your Arduino. MySensors is using hardware SPI to communicate with the radio. SoftSpi is a software implementation of SPI and will allow you to make SPI communication to your breakout board, but must use alternate pins on your Arduino as avoid the conflict. You should be able to get it to work with SoftSPI or I2C. Thanks, but isn't SPI designed to allow more than one slave to be connected? From what I understand, each slave requires a separate slave select pin, but should be able to share the other pins. I'm new to this so please correct me if I'm wrong. Thanks Al - BulldogLowell Contest Winner last edited by BulldogLowell Thanks, but isn't SPI designed to allow more than one slave to be connected? yes, if they play well together... I've not been that lucky with Arduino. Since the breakout isn't on a shield, it may work OK. You can always just try it and let us know. @BulldogLowell said: yes, if they play well together... I've not been that lucky with Arduino. Since the breakout isn't on a shield, it may work OK. You can always just try it and let us know. Thanks, I did not realize that. The manufacturer got back to me already (great support over a weekend) and indicated that they don't have a sample I2C sketch, so I'll likely try getting it working with SPI first. Cheers Al @BulldogLowell @Sparkman Hi guys, Have any of you made any developments? I was wondering, can I make changes to distance sensor sketch and use it for lighting? as3935_lightning_snsr_nocal.ino PWFusion_AS3935.cpp PWFusion_AS3935.h @jeylites I haven't done much with it as I was waiting for my NRF24l01's to show up, First shipment got lost and my replacement shipment seems to be stuck in customs for far too long. I'm hoping to get back to it in a couple of weeks. I did write a sketch that compiled and loaded properly, but I haven't been able to test it due to lack of radios Cheers Al My radios showed up a few days ago and this is the sketch I'm using: #include "MySensor.h" // the sensor communicates via SPI or I2C. This example uses the SPI interface #include "SPI.h" // include Playing With Fusion AXS3935 libraries #include "PWFusion_AS3935.h" // setup CS pins used for the connection with the sensor // other connections are controlled by the SPI library) int8_t CS_PIN = 8; int8_t SI_PIN = 7; int8_t IRQ_PIN = 3; volatile int8_t AS3935_ISR_Trig = 0; // #defines #define AS3935_INDOORS 1 #define AS3935_OUTDOORS 0 #define AS3935_DIST_DIS 0 #define AS3935_DIST_EN 1 #define AS3935_CAPACITANCE 96 // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD // prototypes void AS3935_ISR(); PWF_AS3935 lightning0(CS_PIN, IRQ_PIN, SI_PIN); #define CHILD_ID_DISTANCE 1 #define CHILD_ID_INTENSITY 2 MySensor gw; MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE); MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1); void setup() { gw.begin(); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Lightning Sensor", "1.0"); // Register all sensors to gw (they will be created as child devices) gw.present(CHILD_ID_DISTANCE, S_DISTANCE); gw.present(CHILD_ID_INTENSITY, S_CUSTOM); boolean metric = gw.getConfig().isMetric; Serial.begin(115200); Serial.println("Playing With Fusion: AS3935 Lightning Sensor, SEN-39001"); Serial.println("beginning boot procedure...."); // setup for the the SPI library: SPI.begin(); // begin SPI SPI.setClockDivider(SPI_CLOCK_DIV4); // SPI speed to SPI_CLOCK_DIV16/1MHz (max 2MHz, NEVER 500kHz!) SPI.setDataMode(SPI_MODE1); // MAX31855 is a Mode 1 device // --> clock starts low, read on rising edge SPI.setBitOrder(MSBFIRST); // data sent to chip MSb first lightning0.AS3935_DefInit(); // set registers to default // now update sensor cal for your application and power up chip lightning0.AS3935_ManualCal(AS3935_CAPACITANCE, AS3935_OUTDOORS, AS3935_DIST_EN); // AS3935_ManualCal Parameters: // --> capacitance, in pF (marked on package) // --> indoors/outdoors (AS3935_INDOORS:0 / AS3935_OUTDOORS:1) // --> disturbers (AS3935_DIST_EN:1 / AS3935_DIST_DIS:2) // function also powers up the chip // enable interrupt (hook IRQ pin to Arduino Uno/Mega interrupt input: 0 -> pin 2, 1 -> pin 3 ) attachInterrupt(1, AS3935_ISR, RISING); lightning0.AS3935_PrintAllRegs(); // delay execution to allow chip to stabilize. delay(1000); } void loop() { // This program only handles an AS3935 lightning sensor. It does nothing until // an interrupt is detected on the IRQ pin. while(0 == AS3935_ISR_Trig){} // reset interrupt flag AS3935_ISR_Trig = 0; // now get interrupt source uint8_t int_src = lightning0.AS3935_GetInterruptSrc(); if(0 == int_src) { Serial.println("Unknown interrupt source"); //gw.send(msgDist.set(999)); //gw.send(msgInt.set(0)); } else if(1 == int_src) { uint8_t lightning_dist_km = lightning0.AS3935_GetLightningDistKm(); uint32_t lightning_intensity = lightning0.AS3935_GetStrikeEnergyRaw(); Serial.print("Lightning detected! Distance to strike: "); Serial.print(lightning_dist_km); Serial.println(" kilometers"); Serial.print("Lightning detected! Lightning Intensity: "); Serial.println(lightning_intensity); gw.send(msgDist.set(lightning_dist_km)); gw.send(msgInt.set(lightning_intensity)); } else if(2 == int_src) { Serial.println("Disturber detected"); //gw.send(msgDist.set(998)); //gw.send(msgInt.set(0)); } else if(3 == int_src) { Serial.println("Noise level too high"); //gw.send(msgDist.set(997)); //gw.send(msgInt.set(0)); } } // this is irq handler for AS3935 interrupts, has to return void and take no arguments // always make code in interrupt handlers fast and short void AS3935_ISR() { AS3935_ISR_Trig = 1; } It seems to be working (based on what I'm seeing using the serial monitor) and updating my controller (HomeSeer), although hard to know how well it's working without lightning in the area. I'll have to find a way to simulate lightning. I have both the lightning sensor and the radio hooked up to the SPI bus. Cheers Al EDIT: The diagram above is incorrect, I had to connect the lightning sensor breakout board to 5V, it did not seem to work at 3.3V in this configuration. Sweet. Would you want to create a pull request when you're ready with this example (including AS3935 library)? @hek The AS3935 Sensor also registers the energy intensity. What sensor type would be the best way to send that data to the controller? I'm using S_DISTANCE for the calculated distance, but would also like to capture the energy intensity. The energy intensity is returned as a 32 bit integer. Also, the AS3935 returns the distance in km, but I believe S_DISTANCE is in cm. Is there a way to specify different units or should I have the sketch convert it to cm and then have the controller convert back to km? Thanks Al Oh.. than sensor is more advanced than I thought. Send distance in "meter" for now. Stupid thing that the distance sensor example we're sending in cm in the first place. Energy intensity is harder. What unit that is that? Maybe you could send it in VAR_1 for now? @hek The sensor has a number of registers that can be set and/or read, so depending what someone wants to do with it, additional parameters may be sent. Ok, will do regarding the units. The energy intensity is just a relative value with no units associated with it. I saw one sketch for a different breakout board for the same chip that converted the intensity to a value in the range of 1-10. The actual value returned can be as large as 16843008. I'll take a look at VAR_1, but don't believe the HomeSeer plugin supports that yet. As a test I used I used V_WATT/S_POWER for now. Cheers Al If you can give me some time say around June or July, I'll be going to a tropical country with lots of lightning. I could test it out for you using Vera. @jeylites Thanks, I appreciate the offer. July/August are prime thunderstorm season where I live and they are forecasting a possible thunderstorm for today, so I'm hoping to confirm that everything is working today Cheers Al I put one of these together a short while ago -- just missed a storm rolling though, but another round might come through later. There's a reference in the code to AS3935_CAPACITANCE and a comment suggesting it be set to "THE NUMBER LISTED ON YOUR BOARD", however I'm seeing no number listed on the board. Am I just over looking it or is it something you derive? thanx, JpS @soward So far the thunderstorms have skirted our area, but more to come tonight. Here's hoping The Capacitance value is written on the bag the sensor came in. If you don't have the bag anymore, send an email to TechnicalSupport@PlayingWithFusion.com and they should be able to cross reference your order and provide the value. How does your sketch compare to mine? Cheers Al @Sparkman great thanx, I do have the bag somewhere in the pile-of-parts-bags. So far I have only used the demo sketch from playingwithfusion, but once it appears to detect something I'll probably use yours as a base and branch out form there. I'm using a Vera so I can try to use VAR_1 as hek suggested. - hleidecker Plugin Developer last edited by hleidecker Also, the AS3935 returns the distance in km, but I believe S_DISTANCE is in cm. Is there a way to specify different units or should I have the sketch convert it to cm and then have the controller convert back to km? The actual value returned can be as large as 16843008. I'll take a look at VAR_1, but don't believe the HomeSeer plugin supports that yet. As a test I used I used V_WATT/S_POWER for now. Two mechanisms have been implemented in the HomeSeer controller plugin (1.0.5574.17274) to support custom unit strings in the controller UI: - V_UNIT_PREFIX (only available in the development branch of the MySensors library). The prefix provided in the V_UNIT_PREFIX message will precede the default metric unit (defined by the plugin e.g. m (meter) for the distance sensor). The sensor configuration (metric/imperial) can be set by the user as a property on S_ARDUINO_NODE device via the HomeSeer UI. Please note, the prefix will not take effect when the sensor configuration is set to imperial. - A user defined unit string. A unit string can be defined by the user. The metric/imperial configuration unit string and unit prefix will be ignored if a user defined unit string exists. The user defined unit string can be set by the user as a property on the device e..g. S_DISTANCE via the HomeSeer UI. The HomeSeer MySensors plugin is available here. Best regards, Henrik @hleidecker Thanks Henrik! Hi all, Well I was finally home when a thunderstorm rolled through and I was able to test the sensor and the sketch. Even though the sensor appeared to be working at 3.3V, I had to change it to 5V to get it to work properly with the USB powered Nano I have it connected to. I modified the sketch slightly (updated in my earlier post) to no longer send data when disturbers or unknown interrupt sources were detected. It's working great now and just need to put it into a case. I may use a different Arduino as well. Cheers Al Sweet. Would you want to create a pull request when you're ready with this example (including AS3935 library)? Hi Henrik, Pull request submitted. Hopefully I did it correctly. Cheers Al Nice that you finally got some lightings to test your sketch. Pull request looks all ok! - Tore André Rosander last edited by Is it possible to detect the distance to the lightningstrike? I was thinking to get some sort of detector to notify me if there is ligning registered X km away from my home. You would need a sound detector for the thunder. Time (in milliseconds) between lightning and thunder times 0.34[m]. Same as you would do it with your own sensors (eyes and ears) BR, Boozz @Tore-André-Rosander Yes, the sensor can detect the distance. See the details of the sensor here:. Although I'm starting to believe that it's actually a lightning repeller rather than a lightning sensor as we've had very little lightning in our area after I installed it Cheers Al I found a similar sensor in the UK and added this to the list of my to be sensors for the weatherstation. Can I use it inside or it has to be placed outside to have a direct vision? - Tore André Rosander last edited by @alexsh1 What i read when researching this chip it can be placed inside. @Sparkman Nice, i see that it has a detection range about 40km so thats already a pretty good distance to get a notification when lightning is detected. @Sparkman I suppose your wiring diagram above is correct? I noted that the sensor is not working with 3.3V. Did you manage to find what the problem was? Looking at the datasheet I can see what the module can operate down to 2.4V I am going to receive the sensor in a few days and test it. As I have a different module manufacturer, I may need to change the sketch as it uses a different library. This is unmodified example sketch: */ // AS3935 MOD-1016 Lightning Sensor Arduino test sketch // Written originally by Embedded Adventures #include <Wire.h> #include <AS3935.h> #define IRQ_pin 2 volatile bool detected = false; void setup() { Serial.begin(115200); while (!Serial) {} Serial.println("Welcome to the MOD-1016 (AS3935) Lightning Sensor test sketch!"); Serial.println("Embedded Adventures ()\n"); Wire.begin(); mod1016.init(IRQ_pin); //Tune Caps, Set AFE, Set Noise Floor //autoTuneCaps(IRQ_pin); mod1016.setTuneCaps(7); mod1016.setOutdoors(); mod1016.setNoiseFloor(5);Distance(); break; } } void printDistance() { int distance = mod1016.calculateDistance(); if (distance == -1) Serial.println("Lightning out of range"); else if (distance == 1) Serial.println("Distance not in table"); else if (distance == 0) Serial.println("Lightning overhead"); else { Serial.print("Lightning ~"); Serial.print(distance); Serial.println("km away\n"); } } This is SPI sketch, I'd like to use I2C connection. Generally, the procedure is as follows: Wait a few milliseconds for the system to stabilise Set the tune capacitor to the value indicated on the packaging, by setting the TUNE_CAP bits of register 8 Wait 2 milliseconds Callibrate RCO by: o Sending a calibrate RCO direct command (set memory location 0x3d to the value 0x96) o Set Register 0x08, bit 5 to 1 o Wait 2 milliseconds o Set Register 0x08, bit 5 to 0 The factory calibrating tuning cap value will be fine for general use. When you have a MOD-1016 in an enclosure or close to other electronics it is worth calibrating the tuning cap again. - scalz Hardware Contributor last edited by scalz can't wait to test this one too i have pcbs for a weather shield (with bme280, veml6070 etc. ) and i have this sensor on it too (). But not assembled yet, was busy, i hope asap.. i plan to use it with 3v and i2c. @alexsh1 There are libs for i2c if you want Thx @Sparkman for your work on it I'm running my sketch with I2C now, rather than SPI. I found the sensor would lock up occassionally, so recently converted it and am still testing it. I have mine running at 5v now as well instead of 3.3v, but it works fine with either. I'll post an updated sketch (and wiring diagram) soon. I based both the spi and i2c sketches on the examples found here:. Cheers Al @Sparkman Thanks. Your sketch is very much appreciated. I'll have to adopt it anyway as I have a different manufacture and there is a certain process I have to follow to get it initiated (posted above). Absolutely delighted with the module I have received today by post. The weather is sh@t tonight (lightning, rain etc.) which means that I can test it: Welcome to the MOD-1016 (AS3935) Lightning Sensor test sketch! TUNE IN/OUT NOISEFLOOR 6 10010 5 after interrupt DISTURBER DETECTED DISTURBER DETECTED DISTURBER DETECTED DISTURBER DETECTED DISTURBER DETECTED LIGHTNING DETECTED Lightning ~27km away DISTURBER DETECTED DISTURBER DETECTED LIGHTNING DETECTED Lightning ~17km away DISTURBER DETECTED LIGHTNING DETECTED Lightning ~10km away I calibrated the sensor and put a reasonable "noise floor". Now I have to convert it into MySensors and hook up to the ceech board outside. @Sparkman I have my sensor running at 3.3V BTW, I am not sure the sensor is similar to what you guys have. @alexsh1 It looks to be a different breakout board, but for the same chip. So I would expect them to work basically the same. Cheers Al @Sparkman it is a different board made (or designed) by a UK company. We are having a real British summer over here :-))) LIGHTNING DETECTED Lightning ~20km away LIGHTNING DETECTED Lightning ~20km away LIGHTNING DETECTED Lightning ~6km away LIGHTNING DETECTED Lightning ~6km away LIGHTNING DETECTED Lightning ~6km away LIGHTNING DETECTED Lightning ~6km away LIGHTNING DETECTED Lightning ~6km away LIGHTNING DETECTED Lightning ~5km away - NeverDie Hero Member last edited by @alexsh1 There doesn't appear to be audio input to this board, nor a microphone on the board. So, how does it estimate the distance to the lightening? @NeverDie All these breakout boards are based on this chip:. They use a proprietary method to figure out distance and is not based on sound. Cheers Al - NeverDie Hero Member last edited by @NeverDie All these breakout boards are based on this chip:. They use a proprietary method to figure out distance and is not based on sound. Cheers Al Any impression yet as to how accurate its distance estimates are? @NeverDie Al, was quicker replying to your question. yes, I think it is accurate for my needs - if a lightning detected at, say, 10km+/- 1km this is ok. How accurate do you want it to be? This is a great technology - NeverDie Hero Member last edited by NeverDie @NeverDie Al, was quicker replying to your question. How accurate do you want it to be? I'm not sure, but more accurate than lightningmaps.com or it's a no-go. I've played with lightningmaps.com during a few thunderstorms, and although it's great for getting a general idea of lightning strike rate and density, I was surprised that it seems to miss a lot of detections entirely that both my eyes and ears have confirmed. e.g. some strikes that were big enough to rattle the windows didn't show up at all on lightningmaps. Some of the others were detected, but the map plot of the strike was wrong by maybe 10 miles or so. @NeverDie I have not tested this sensor long enough, but recently we have had torrential rain, lightning, etc - you can see some data I published above. The sensor did not miss a single one. There are a few parameters you can alter (noise floor). One has to setup it correctly. I have not started looking into converting the sketch for MySensors yet I have adopted the MOD-1016 module () for MySensors if anyone is interested: /* Copyright (c) 2016, Embedded Adventures All rights reserved. Contact us at source [at] embeddedadventures Embedded Adventures. */ // Enable debug prints to serial monitor #define MY_DEBUG // Enable and select radio type attached #define MY_RADIO_NRF24 //#define MY_RADIO_RFM69 #define MY_NODE_ID 15 #include <Wire.h> #include <MySensors.h> #include <AS3935.h> // AS3935 MOD-1016 by Embedded Adventures volatile bool detected = false; //-----------------IMPORTANT-------------------- //---------------CHANGE SETTINGS HERE----------- #define IRQ_pin 2 #define AS3935_TUNE_CAPS 6 // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD #define AS3935_INDOORS 1 // AS3935_INDOORS=1 indoors, AS3935_INDOORS=0 outdoors #define AS3935_NOISE_FLOOR 6 #define AS3935_ENABLE_DISTURBERS 1 // 0 or 1 #define CHILD_ID_DISTANCE 1 #define CHILD_ID_INTENSITY 2 MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE); MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1); void setup() { Serial.begin(115200); while (!Serial) {} Serial.println("MOD-1016 (AS3935) Lightning Sensor"); Serial.println("beginning boot procedure...."); Wire.begin(); mod1016.init(IRQ_pin); //-----------------IMPORTANT-------------------- //---------------CHANGE SETTINGS HERE----------- //Tune Caps, Set AFE, Set Noise Floor //autoTuneCaps(IRQ_pin); mod1016.setTuneCaps(AS3935_TUNE_CAPS); delay(2); #if AS3935_INDOORS == 1 mod1016.setIndoors(); #else mod1016.setOutdoors(); #endif delay(2); mod1016.setNoiseFloor(AS3935_NOISE_FLOOR); delay(2); #if AS3935_ENABLE_DISTURBERS == 1 mod1016.enableDisturbers(); #else mod1016.disableDisturbers(); #endif //mod1016.calibrateRCO(); delay(2);"); // delay execution to allow chip to stabilize. delay(1000); } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("Lightning Sensor MOD-1016", "1.0"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID_DISTANCE, S_DISTANCE); present(CHILD_ID_INTENSITY, S_CUSTOM); }andsendToGW(); break; } } void printandsendToGW() { int distance = mod1016.calculateDistance(); unsigned int lightning_intensity = mod1016.getIntensity(); if (distance == -1) Serial.println("Lightning out of range"); else if (distance == 1) Serial.println("Distance not in table"); else if (distance == 0) Serial.println("Lightning overhead"); else { Serial.print("Lightning ~"); Serial.print(distance); Serial.println("km away\n"); Serial.print("Lightning Intensity: "); Serial.println(lightning_intensity); send(msgDist.set(distance)); send(msgInt.set(lightning_intensity)); } } You have to change the sketch according to your module settings I ordered one form embedded adventures on 27/7 - Now it is 3/9 and still nothing. Waiting to hear from them.... That's the whole truth. @skywatch give them a call or send a e-mail. Maybe your order was lost in post. Happens. My order arrived in 2 days from Embedded Adventures OK - finally got board, seems the problem was in the warehouse. I got email to say it had been sent and it never did. At least I can try it out soon and see how it compares to the current lightning sensors I use. @alexsh1 Is your example using I2C or SPI? I can't make it out. I'd guess I2C, but want to make sure first..... Thank you - NeverDie Hero Member last edited by NeverDie @skywatch said in Sketch for Lightning Sensor: see how it compares to the current lightning sensors I use. Please do let us know how it compares and which one you like the best.?
https://forum.mysensors.org/topic/880/sketch-for-lightning-sensor/25
CC-MAIN-2018-51
refinedweb
4,036
65.42
How to generate Individual Hits report using commands in Linux Hi, I am running my load tests in Linux and the .rpt file will get generated once the test got completed. Generating individual hits report from the .rpt file takes more time since the file size will be high (around 350 MB) and also it takes more time to copy from linux machine to windows machine. Please let me know if there are any commands available to generate individual hits report from Linux machine. Thanks in advance Ranjith Best Answer Hi Ranjith Below is the export hits QoS metric script rewritten in Groovy. You will find its syntax similar to Java and JavaScript. I tested it on 9.9.5, if your 9.9 Service Pack is less than 5 I don't know whether it will work or not. Let me know if it does not. I highly recommend that you update the the latest 9.10 version! import com.parasoft.api.loadtest.* import com.parasoft.api.loadtest.output.* import com.parasoft.simulator.api.output.* import com.parasoft.simulator.output.raw.* import com.parasoft.simulator.output.view.table.* // See Help->API->Scripting API // See Help->API->Component API void exportIndividualHits(args, context) { PrintWriter hitsWriter; try { hitCount = 0 hitsFile = new File('C:/Shared/Forum/ExportHits/hits.csv') hitsWriter = new PrintWriter(hitsFile) ltReport = args.getOutput() hits = ltReport.getHits() outputMap = SingleOutputNameResolver.getTestNameMap(ltReport.getOutput().getMergedOutput()) rawOutput = ltReport.getOutput().getRawOutput() hitsWriter.write('Machine, Profile, Test, Success, Start Time (ms), Execution Time (ms), Request Size (bytes), Response Size (bytes), Error String' + '\n') for (hit in hits) { testName = SingleOutputNameResolver.resolveTestName(outputMap, hit) if (!testName.contains("Test Suite")) { // filter out Test Suite hits hitsWriter.write(SingleOutputNameResolver.resolveInstance(rawOutput, hit) + ', ') hitsWriter.write(SingleOutputNameResolver.resolveProfile(rawOutput, hit) + ', ') hitsWriter.write(testName + ', ') if (hit.getState() == SingleOutput.HIT_SUCCESS) hitsWriter.write('Success, ') else hitsWriter.write('Failure, ') hitsWriter.write(hit.getStartTime() + ', ') hitsWriter.write(hit.getExeTime() + ', ') hitsWriter.write(hit.getBytesOut() + ', ') hitsWriter.write(hit.getBytesIn() + ', ') hitOutput = hit.getHitOutput() if (hitOutput != null) { hitError = new TableErrorString(hitOutput).getFormattedString() hitsWriter.write(hitError) } hitsWriter.write('\n') hitCount++ } } System.out.println("Wrote "+hitCount+" hits.") } catch (Throwable t) { System.out.println("Exception: "+t.getMessage()+" | "+t.getClass()) } finally { if (hitsWriter != null) { hitsWriter.close() } } }5 Answers You can add the Individual Hits graph to your HTML report and have the HTML report automatically generated if you are running your load test from command line mode. First verify that the Individual Hits are included into the HTML report configuration - see Reviewing and Customizing Load Test Results -> Viewing a Report -> Configuring HTML Report Options section of the docs for steps. Then run Load Test with the -allReport command like so: loadtest -minutes ${minutes} -allReports ${pathToReportsDirectory} ${scenario} (see details in Load Test Command Line Interface section of the docs). Load Test will create an HTML report (as well as the binary and xml) with an individual hits graph under that path. Hi, Thanks for your reply. In my HTML report i'm getting the individual hits as a graph. To know the response time of a single hit in my load test, i can save the individual hits report as a .csv file which can be done in user interface mode (in windows machine). I would like to know whether any command line option is available in Linux to save the individual report in .csv format (like how HTML report is being saved using -allReport command). Thanks in Advance. Regards, Ranjith Hi Ranjith, There is no command line option to save individual hits in a .cvs table separately from the report, it is possible however to save hit details with the help of a custom/scriptable QOS metric. Although QOS metrics are designed to process relevant data in the report and produce a success/failure output, it is possible to use metrics for other types of processing of the report data, which in your case is exporting of the individual hits. Below in a Jython script for a custom QOS metric that writes hits in the same format as the "Export Individual Hits" option in the Load Test report graph view. The QOS metric will be applied at the completion of a load test. You will need to modify the path of the destination file in the script to the one that is relevant for your case: hitsFile = open('REPLACE_WITH_PATH_TO_FILE/hits.csv','w') Thanks, -Sergei Hi Sergei, Thanks a lot for your reply. I tried with custom QOS metrics that you shared in my loadtest . I observed a compilation error (Traceback (most recent call last): File "", line 6, in ImportError: No module named table) When i tried removing the line " from com.parasoft.simulator.output.view.table import *" i'm getting an error message (Traceback (most recent call last): File "", line 13, in exportIndividualHits AttributeError: 'com.parasoft.simulator.output.LoadTestOutputImpl' object has no attribute 'getOutput') once the test got over. Please find the attached images for your reference. Could you please help here. Thanks in advance. Regards, Ranjith Hi Ranjith, Judging by the screenshots, you are using a (very) old version of Load Test - you can see it in Help->About. I tested the script with Load Test 9.10, which is the latest version. Please update to the latest versions of SOAtest/LoadTest. Also because of the nature of the functionality you've requested, the script is using some non-API calls, so it is sensitive to the SOAtest/LoadTest version. -Sergei Hi Sergei, Thanks for your response. I checked with parasoft version 9.9 and i'm able to generate individual hits report. But when checked in the report, the data are being populated for the first hit only and not for all the hits (eg. my run count from html report is 49 and from individual hits report is 1). I guess the for loop is exiting after capturing the first hit. Since i'm not faimiliar with jython script, i could not compile it and fix it. Could you please help in this. Or is there any alternate java code or javascript code available for capturing the individual hits. Thanks in advance. Regards, Ranjith Hi Sergei, This has worked fine with parasoft version 9.9.5. Thanks
https://forums.parasoft.com/discussion/2850/how-to-generate-individual-hits-report-using-commands-in-linux
CC-MAIN-2018-22
refinedweb
1,025
50.33
and You. DataGrid Column Types - DataGridTextColumn – When you think of a standard column in a DataGrid, you probably picture something that looks a lot like a DataGridTextColumn. This column is the default and uses a TextBlock to display its data, and a TextBox to allow editing of its data. - DataGridCheckBoxColumn – The DataGridCheckBoxColumn is the first out of box custom column type. It provides a read-only CheckBox for displaying a boolean or nullable boolean value, and a normal CheckBox to allow editing of that value. This column derives from DataGridBoundColumn and serves as a sample for building your own column types. We’ll walk through the process of building your own column types in a future post. - DataGridTemplateColumn – If the DataGrid was a movie, the DataGridTemplateColumn would be the star. It is the most versatile column but, like most prima donnas, takes the most work to get up and going. Once it is going though there is pretty much no limit to what it can do. Using the Columns Collection: - It creates the Columns collection using the <data:DataGrid.Columns> tag. - Inside that collection it creates a new DataGridTextColumn - The content that you see in the column header is set to "First Name" using the Header property - The column is data bound to the FirstName property using the Binding property. Notice that since the DataContext of the DataGrid is its ItemsSource collection a Source does not need to be specified. Side Note: Some of you might be wondering why we use Binding here instead of a string like DisplayMemberPath. The thinking behind this decision was that a binding gives you a lot more control of what ends up being shown. It allows the use of converters, and leaves the door open for the addition of validation, and formatters. If you run this you should see something like this: In addition to the Header and Binding properties, you can also customize the column through properties such as: Column Properties: - CanUserResize – Determines if this column can be resized. In regards to its relationship with the DataGrid property CanUserResizeColumns, false always wins. - CanUserReorder – Determines if this column can be reordered with other columns. In regards to its relationship with the DataGrid property CanUserReorderColumns, false always wins. - CanUserSort – Determines if this column can be sorted. In regards to its relationship with the DataGrid property CanUserSortColumns, false always wins. - IsReadOnly – Determines if this column can be edited. In regards to its relationship with the DataGrid property IsReadOnly, true always wins. - Width – Sets the width of the column. Setting this value overrides the DataGrid ColumnWidth property. - MinWidth – Sets the minimum width for this column. - Visibility – Hides or shows this column - ElementStyle – The property used to style the display element for a column. (In the case of the TextBox Column the display element is the TextBlock) - EditingElementStyle – The property used to style the editing element for a column. (In the case of the TextBox Column the display element is the TextBox) TextBox Column Specific Properties: - FontFamily – Sets the FontFamily property on both the TextBlock and TextBox. - FontSize – Sets the FontSize property on both the TextBlock and TextBox. - FontStyle – Sets the FontStyle property on both the TextBlock and TextBox. - FontWeight – Sets the FontWeight property on both the TextBlock and TextBox. - Foreground – Sets the Foreground property on both the TextBlock and TextBox. CheckBox Column Specific Properties: - IsThreeState – Sets the IsThreeState property on the CheckBoxes. Unleashing the Template Column: C#) _ }) Next. What’s going on in the code above: - A DataGridTemplateColumn is being added to the Columns collection with its header being set to "Birthday". - The CellTemplate property, which takes a DataTemplate, is being used to define the UI that cells in the column will use to display the data. - In this instance, the content of that DataTemplate is a TextBlock that has its Text property bound to the "Birthday" property on the Data Item. Once again notice that no binding source is necessary since the default DataContext of a Template column’s contents is the data item that it will be representing. - In addition to the CellTemplate the DataGridTemplateColumn’s CellEditingTemplate property is also being set. This property is also a DataTemplate and defines the UI that cells in the column will display during edit mode. - In this instance, the content of the CellEditingTemplate’s DataTemplate is a DatePicker control that has its SelectedDate property also bound to the "Birthday" property. - Notice that its binding has the Mode property set to TwoWay. This is crucial to make sure that any changes made to this property at runtime will be pushed back into the data source. Note that you do not need to set the Mode when you are using the DisplayMemberBinding property in column types other than DataGridTemplateColumn because the columns themselves take care of this.) Using Value Converters: C# using System.Windows.Data; using System.Globalization; public class DateTime; } } VB Imports System.Windows.Data Public Class DateTime. -Scott? Hi Scott, Here is the latest in my link-listing series .  Also check out my ASP.NET Tips, Tricks and Tutorials:Name=”dataGrid” Margin=”80,88,104,116″ > <my:DataGrid.Columns> <my:DataGridTemplateColumn Header=”Thumbnail”> <my:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source=”{Binding Thumbnail}” Width=”64″/> <. Hope this helps! Hi scmorris, This is works! Thank You Very Much… Hi, im new to silver light i have a got a basic doubt. I need to bind an array of items. which contains 5 attributes, and i need only 3 of them to be displayed in the grid. I did the follwoing <data:DataGrid.Columns> <data:DataGridTextColumn <data:DataGridTextColumn <data:DataGridTextColumn <data:DataGridTextColumn <data:DataGridTextColumn </data:DataGrid.Columns> But in addition to these the other 5 attributes are also getting binded to the grid. How to make those five columns invisible. Thanks. Hi i got the answer for my question. Thank u. Hi scmorris, Since DataGridColumn properties aren’t DependencyPropertys they can’t be data-bound or whatever, right? So is there any way to bind the Width (or other) properties in XAML? Thanks, Robert Hi Robert, Unfortunately there is no way to databind properties on DataGridColumns yet. This is since they are DependencyObjects instead of Controls, and DO’s cannot be the target of a binding in Silverlight 3. If the future when this functionality exists in the platform you can expect the DataGrid to fully support it. In the mean time, you will have to use programmatic methods to try to emulate the binding logic. Hope this helps. Hi Scott… Thanks, very much nice topic, it was very useful 🙂 can we transform row and column of the grid so that column appears in the top and row appears in the place of row Scott, This is a great article. I would like to see if there is a way to create dynamic rows for silverlight datagrid?? Thanks Hi, Is there any way possible that I can add rows dynamically. for e,g, say pressing the tab in the last row can take me to a new row where I can add values? Thanks guys for your help I'm trying to create a debug window for myself writing out when certain events fire and I'm having problems catching any events when I change the state of the checkbox. Which event should I be listening for to catch this event? Also, I wanted to change the way the tab loops through the grid. Instead of looping through all rows cell by cell, I want the grid to loop through only the cells in the currently selected row and start over when the last cell is reached. I tried the TabNavigation but that doesn't seem to change this behavior. Where should I be looking for this?
https://blogs.msdn.microsoft.com/scmorris/2008/03/27/defining-columns-for-a-silverlight-datagrid/
CC-MAIN-2017-17
refinedweb
1,286
64.41
Tests Contents - 1 Prerequisites - 2 Building and running unit tests - 3 Submitting test suite reports to the dashboard - 4 Writing unit tests Prerequisites First of all, this page applies to the development branch, not 2.0. You need to know how to use CMake, see our page on that topic. From now on, we assume that we are in the build directory and that you have already run cmake. There is no need to pass a particular option to CMake to enable tests. Building and running unit tests To build and run all tests using CTest, use the check target. For example, if your platform uses make: $ make check This will not send a report to the online dashboard. If you want to do that, see below. We do not use the "test" target because of a well-documented limitation of CTest (the "test" target does not build the tests). If you only want to build the tests, not run them, use the buildtests target. For example, with make, do: $ make buildtests Working on one specific test Each test has its own build target, so for example, for the 'basicstuff' test, you can do: $ make basicstuff Notice that if you want to rebuild a test in debug mode, see below. Inside each test, each executable (under the default behavior of splitting tests into smaller executables) has its own build target, so for instance you can do: $ make basicstuff_2 If you want to run specifically that executable and see its output, run it directly: $ test/basicstuff_2 Note that these test executables take optional command-line parameters to control the number of repetitions and the seed. Alternatively, this can be controlled by the environment variables EIGEN_REPEAT and EIGEN_SEED. To get some help, just pass anything on the command line, like 'help': $ test/basicstuff_2 help Filtering tests with regular expressions We have two scripts for that, directly in your build directory. They currently assume "make" and the Bash shell, feel free to port them to your platform. To build all tests matching a regular expression pattern, do: $ ./buildtests.sh regexp To build and run all tests matching a regular expression pattern, do: $ ./check.sh regexp Notice that that is the same as doing "./buildtests.sh" followed by "ctest -R". These scripts honor the EIGEN_MAKE_ARGS and EIGEN_CTEST_ARGS environment variables, allowing to pass arguments to make and ctest. For example, you could put this in your '.bashrc' file, or wherever you put your custom environment variables: # The following works with GNU make and lets it use 5 concurrent build jobs: export EIGEN_MAKE_ARGS=-j5 # The following works with CTest >= 2.8 and lets it use 8 concurrent test jobs: export EIGEN_CTEST_ARGS=-j8 Build types and debugging There are 2 build types, Debug and Release. The default build type is "Release". If you have a test that fails and want to debug into it, you'll probably have to rebuild it in Debug mode. This is controlled by the standard CMake variable CMAKE_BUILD_TYPE. On Windows/MSVC, this is controlled from within the IDE as usual. Otherwise, we provide scripts for re-running CMake with that variable changed, just do: $ ./debug.sh and $ ./release.sh Note that in Debug mode, optimization is disabled and full debugging info is generated. Tests take a ton of disk space, and a very long time to finish. Submitting test suite reports to the dashboard Submissions on Unix Systems To submit reports to the dashboard: - Update your mercurial clone to the desired branch: cd path/to/eigen hg pull -u Make sure you are in the branch that you want (hg branch, hg up <branchname>). - Configure a build directory with the desired compiler version and cmake options, e.g.: mkdir build-XXX cd build-XXX CXX="g++-4.6" cmake path/to/eigen -DEIGEN_TEST_OPENMP=ON - Run ctest with the -D option, e.g.: ctest -D Continuous For a nightly build use Nightly instead of Continuous. It is straightforward to create a shell script automatizing these steps for a couple of different compilers/options. Submissions on MSVC Systems To submit reports to the dashboard, checkout/clone Eigen to any folder on your hard disk. Now run CMake to create a build folder and choose a generator of your choice, e.g. 'Visual Studio 11 Win64'. Now you have to choices. Either open the IDE and build the 'Experimental' target or open a command prompt (e.g. via Start -> Run -> cmd) and change to the build directory in which you have created the build files with CMake. Once you are in the build directory run the following command ctest -C Release -D Experimental or in case you want to trigger just an incremental build run ctest --build-noclean -C Release -D Experimental The tests are build automatically by CTest with the exact configuration you have defined while running CMake. The advantage of running the tests from the command prompt is the possibility to perform incremental builds without a full rebuild which could take up to 3 hours. Checking your results Then you can check the results on our dashboard: For further information, check theses web pages: - ctest documentation: - ctest wiki: - cdash documentaion: - cdash wiki: Writing unit tests If you want to add a simple test of small feature highly related to an existing unit test, then simply extend the existing one. Otherwise, you have to create a new unit test. Let's call it mytest. - Create a new file mytest.cpp in the eigen/test (or eigen/unsupported/test) folder. - Your file must start by including the file main.h and declare a test function with the EIGEN_DECLARE_TEST macro: #include <main.h> EIGEN_DECLARE_TEST(mytest) { /* ... */ } This creates a function test_mytest that will be automatically called. You can declare multiple tests in a single .cpp file, they will all be called in sequential order. - If you don't know how to fill the blank, have a look at the other unit test files in eigen/test. - Add it to the respective CMakeLists.txt file by adding the line: ei_add_test(mytest) Important: splitting your test into small executables To limit compiler memory usage (and enable more parallel builds), it's good to split tests into smaller executables. It makes the most sense to group together instantiations of the same types, e.g. one executable with MatrixXf, one with Matrix4d, etc... Fortunately, we have infrastructure that makes doing that very easy. In your test file, just replace CALL_SUBTEST by CALL_SUBTEST_1, CALL_SUBTEST_2, etc... (can go up to 16) and CMake will automatically parse that, create multiple executables, each with only one channel activated. You can also split a test by checking for symbols as: EIGEN_TEST_PART_i where i=1,2,... and again, CMake parses for that and creates corresponding executables. If a EIGEN_TEST_PART_i is found, then the test will be split unconditionally. A typical use case consists in building the same unit-test with different Eigen's options (C++ max version, vectorization, alignment, etc.) See for instance test/indexed_view.cpp See existing test files for examples. Benchmarking compilation times and memory usage The following command permits to measure the build time and memory usage of each unit tests using GNU time (gtime from macport on OSX): for f in ../../test/*.cpp; do t=`echo ${f%.*} | cut -d '/' -f 4`; gtime -f "%e %M" make -j 1 $t 2> z.txt > /dev/null ; u=`tail -n 1 z.txt | cut -d " " -f 1`; # get user time m=`tail -n 1 z.txt | cut -d " " -f 2`; # get max memory usage echo $t $u $((m/1024/1024)); done It can be useful to spot huge unit tests and compare the build time of each unit tests with and without splitting. To disable splitting: cmake . -DEIGEN_SPLIT_LARGE_TESTS=OFF Advanced: optional ei_add_test parameters The macro ei_add_test takes two optional arguments: - The first one specifies additional compile flags. - The second one contains the additional libraries to link with.
http://eigen.tuxfamily.org/index.php?title=Tests&oldid=2381
CC-MAIN-2019-18
refinedweb
1,311
63.29
S E P T E M B E R 1 9 9 9 The instructions above are for this month's puzzle only. See a complete introduction to clue-solving. See the solution to last month's Puzzler. 5. "Eternities" is dedicated to a civil-rights figure (8) 10. I would like names for girls (4) 11. Solicit drink in one half of duplex (4,2) 13. Company soldier captures heart of stray dog (5) 16. After outbreak, "untouchable" agent's haste (8) 17. Stuff you believe as visitor to our world laughs (5) 19. Fair attractions covered in diamonds display rainbow colors (8) 21. Again, Study in Scarlet including actor from The Crying Game (6) 23. Find Mexican food in the Mexican counter (6) 25. Name of a notable Ethiopian girl I caught amid visit (8) 29. A formal examination cut short in Roman courts (5) 30. Samples of men's epics recast (9) 31. Church figure in 150, an old Norseman (6) 32. Some dishes with pronounced merits (8) 33. Gift-getters witness sign of acknowledgment in return (6) Down 1. Mediterranean capital misrepresented as "Ionic" (7) 2. Tokyo's old name in verse written up (3) 3. Less often seen live in Red River (5) 4. Small trend reverses works in a magazine office (5) 5. Heater for coffee container in front (7) 6. Oh, mother's one with guts (5) 7. Something just passing convertible -- mere heap (8) 8. Ringing of two notes on land (10) 9. Gave some lip to shortstop and starter for Expos in blue (6) 12. Eating the last piece of cake, you laugh (2-3) 14. Austrian dog disrupted school ceremonies (11) 15. Grow bitter about a diner (7) 18. Quarry surrounding Los Angeles Catholic bishop's office (7) 20. Use a magic spell on door (8) 22. Unfinished set in Rent's creating problems (7) 23. Decked in foliage, started holding prayer (6) 24. Comb and powder (5) 26. Exercise time has Penny in a bad mood (5) 27. Music of the 1970s is in Washington Circle (5) 28. Energy used by Hoover vendors (5) Copyright © 1999 by The Atlantic Monthly Company. All rights reserved.The Atlantic Monthly; September 1999; The Puzzler - 99.09; Volume 284, No. 3; page 107.
http://www.theatlantic.com/past/docs/issues/99sep/9909puzz.htm
CC-MAIN-2016-40
refinedweb
380
79.56
Programmatically managing blobs - This post has two main objectives: (1) Educate you that you can host web content very economically; (2) Show you how you can create your own blob management system in the cloud. - You can also learn about some threading techniques and how to update WPF user interfaces in a multi-threaded environments. - Download the source to my VS 2012 RC project: - Hosting web content as a blob on Windows Azure is powerful. To start with, it is extremely economical; it doesn’t require you to host a web server yourself. As a result blobs are very cost-effective. Secondly, the other powerful aspect of hosting html content as blobs on Windows Azure is that you get that blobs get replicated 3 times. It will always be available, with SLA support. - I use Windows Azure-hosted blobs for my blog. I store html, javascript, and style sheets. I manage video content as well. You can see my article in MSDN Magazine for further details. - I could store anything I want. When you visit my blog, you are pulling content from Windows Azure storage services. - You can dynamically create content and then upload to Azure. I’ll show you how to upload the web page as a blob. - But that web page can be dynamically created based on a database. The code I am about to show is infinitely flexible. You could adapt it to manage all your content programmatically. - I will illustrate with the latest tools and technologies, as of July 2012. This means we will use: - Windows 8 - Visual Studio 2012 RC - Azure SDK and Tooling 1.7 - I assume you have an Azure Account (free trials are available) 2 main blob types - The storage service offers two types of blobs, block blobs and page blobs. - You specify the blob type when you create the blob. - Blob storage. - Common uses of Blob storage include: - Serving images or documents directly to a browser - Storing files for distributed access - Streaming video and audio - Performing secure backup and disaster recovery - Storing data for analysis by an on-premise or Windows Azure-hosted service - Once the blob has been created, its type cannot be changed, and” it can be updated only by using operations appropriate for that blob type”, i.e., writing a block or list of blocks to a block. - You can assign attributes to blobs and then query those attributes within their corresponding container using LINQ. - Blobs allow you to write bytes to specific offsets. You can enjoy typical read/write block-oriented operations. - Note following attributes of blob storage: - Storage Account - All access to Windows Azure Storage is done through a storage account. This is the highest level of the namespace for accessing blobs. An account can contain an unlimited number of containers, as long as their total size is under 100TB. - Container - A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs. - Blob - A file of any type and size. - “A single block blob can be up to 200GB in size”. “Page blobs, another blob type, can be up to 1TB in size”, and are more efficient when ranges of bytes in a file are modified frequently. For more information about blobs, see Understanding Block Blobs and Page Blobs. - URL format - Blobs are addressable using the following URL format: - Web Pages as blobs - As I explained, what I am showing is how I power my blog with Windows Azure [1]. My main blog page starts with an <iframe>[2][3]. This tag lets you embed an html page within an html page. My post is basically a bunch of iframe‘s glued together. One of those iframe‘s is a menu I have for articles I have created. It really is a bunch of metro-styled hyperlinks. - As I said before, this post is about how I power my blog[1]. This post is about generating web content and storing it as a web page blob up in a MS data center. The left frame on my blog is nothing more than an iframe with a web page.[2][3] - The name of the web page is key_links.html. Key_links.html is generated locally, then uploaded to blog storage. - The pane on the left here that says Popular Posts. It is just an embedded web page, that is stored as a blob on Windows Azure. I upload the blob through a Windows 8 Application that I am about to build for you. - The actual one that I use his slightly more complicated. It leverages a SQL Server database that has the source for the content you see in Popular Posts. - For my blog, all I do is keep a database of up to date. The custom app we are writing generates a custom web page, based on the SQL server data that I previously entered. - My app then simply loops through the rows in the SQL server database table and generates that colorful grid you see labeled Popular Posts. - You can see my blob stored here: - Dynamically created based on SQL Server Data - You can navigate directly to my blob content. - - The point here is that Key_links.html is generated based on entries in a database table - You could potentially store the entries in the cloud as well using SQL Database (formerly SQL Azure) - This post will focus on how you would send key_links.html and host it in the Windows Azure Storage Service - Here you can see the relationship between the table data and the corresponding HTML content. - The metro-like web interface you see up there is generated dynamically by a Windows 8 application. We will not do dynamic creation here. - I used Visual Studio 2012 RC to write the Windows 8 application. To upload the blob of all I needed the Windows Azure SDK and Tooling. Adding a WPF Application - On the File menu, select New and then click Project. - In the New Project dialog box, select one of the Project types from the left pane. - Select Windows of the project Templates from the right pane. - In the middle pane, select WPF Application. - Enter a Name for the new project. - I chose UploadBlob Creating a WPF ApplicationWe can start dragging controls over. We will drag buttons, textboxes, and labels. Actually, I will provide you the XAML code. With WPF applications, the user interface is built in XAML. - This is just for illustration purposes. I will provide you all the XAML code in a moment so you don’t have to drag and drop anything. Dragging a control generates XAML - I am being very detailed here. Most developers hopefully can see that when I drag a control, XAML code is generated. Note that we dragged in a button. - Also note that XAML code below. - You can see the <Button> tag. - This is just for illustration purposes. I will provide you all the XAML code in a moment. The finished application that we are building Here is the interface we’d like to build. - It has one button, 2 labels, and 2 textboxes. I’ll give you the XAML code in a little while Our app is finished and running - Here is what it looks like when running. - The top text box will show the html web page that we will upload to the cloud. - The second text box will show the user the progress as it executes the upload. Building the app - Let’s start to build up the application. The first task is to set some references. - We need a reference to the Windows Azure SDK. - We will add a reference to support the Assert() statements in the code. - For the user interface we will add some XAML code (I will provide) - The programming logic will be handled by the code behind. - Get the Windows Azure 90-day trial. - Download the link below: - Connecting to the Azure tooling - Note the two references added. - One for the Quality Tools - So we can do Asserts in code - One for the Storage Client - So we can upload blobs - You will need to select the browse button. Adding two helper classes - After you paste the main code, you will need to generate some classes. - Once generated, we will paste even more code into these freshly generated classes. - You can see that we are going to two classes to generate empty classes. - FileIOReader - BlobManager - Just place your cursor on the class name, right mouse click, and choose Generate Class You need to have a Windows Azure Portal Account - You get this information from the Windows Azure portal - The portal is where you get the Account Name and the Account Key - You will need to click on the View button. - Keep this information so you can paste into the application. - You can think of this information as a user name and password. The portal - The portal is where you get the Account Name and the Account Key - You will need to click on the View button. - Keep this information so you can paste into the application. - You can think of this information as a user name and password. Defining the blob that you will upload - We now need to define the content that we wish to upload has a blob to the Windows Azure storage Service. In our case, we will simply upload a web page. It is also possible to upload almost anything, such as zipfiles, MP3 files, videos, just about anything you can think of. - You can right mouse click on the project, allowing you to add a new folder. From there you can add a new item, which in our case will be a web page, basically an HTML file. - Right mouse click on the project and select Add, New Folder - Call the folder Content - Right mouse click on the new folder (Content) and choose Add New Item - The web page will be called BrunoPage.html - You can call it whatever you want, but you’ll need to remember this for the code behind. It obviously needs to match. The blob and the running app - Running the application and uploading the web page (blob) - BrunoPage.html can be seen above. Notice the <body> tag that we’ve added. - Right mouse click on BrunoPage.html and choose open - Type in the code you see above. I called the new file BrunoPageDestination.html - Using Azure Storage Explorer - You can download Azure Storage Explorer here: - - Azure Storage Explorer will help you view your uploaded blob. - It also works with tables and queues (2 other Azure-related storage types) - Once you’ve entered in your account info, you can simply click on blobs. - Once installed, you will need to configure your account. - It is the same process as before. - You will need to go to the portal and retrieve the account name and account key Interacting with Azure Storage Explorer - Note the container has been called blobcalendarcontent - This was defined by our code (MainWindow.xaml.cs) Drilling into our blob (web page) - Azure Storage Explorer can help you obtain the absolute uri of your blob content. - You can also notice the ContentType is text/html Viewing the web page that we uploaded - You could probably go there right now. - Conclusion - This was an ambitious post. It covered a lot of interesting ground. - I will make it possible for you to create dynamically generated content. - Follow up - Understanding Block Blobs and Page Blobs - - Visual Studio 2012 RC downloads - - Download: Windows Azure SDK for .NET -
https://blogs.msdn.microsoft.com/brunoterkaly/2012/07/24/how-to-create-a-custom-blob-manager-using-windows-8-visual-studio-2012-rc-and-the-azure-sdk-1-7/
CC-MAIN-2017-22
refinedweb
1,937
73.58
From: Beman Dawes (beman_at_[hidden]) Date: 1999-08-05 15:59:27 At 06:03 AM 8/5/99 -1000, Thomas Plum wrote: >I want to provide some arguments for making use of, and encouraging >the use of, the <stdint.h> as defined in C9X (or indirectly thru a >boost-specific <stdint.hpp> or whatever). > > [snip] > >Just a plea to focus the creative effort upon the other problems, where >there is clearly no opportunity for common C/C++ solutions ... I agree with you as regards the C stdint.h typedefs. In addition to your arguments, it seems to me that the int32_t, int_least32, etc. typedefs are simply easier to understand and use than other approaches for many basic programming tasks. So the C stdint.h typedefs (or the same content in namespace boost) are a firm foundation. I assume you don't have any problem with layering added functionality on top of it, such as Valentin's "checked integers" or "choosers", as long as that added functionality is build on the stdint.h typedefs, not competing with them. But what about the macros in stdint.h? Since the C committee had foresight enough to put guards around them so they must be explicitly invoked, boost can use stdint.h without automatically defining macros. Providing a C++ traits class to get at max, min, and other traits is a distinct technical advantage for generic programming with templates, and because a traits class obeys scope rules which macros don't. Do you have a problem with boost providing a traits class and requesting boost authors use something like integer_traits<int32_t>::max or numeric_limits<int32_t>::max() rather using the stdint.h macros? --Beman Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/1999/08/0483.php
CC-MAIN-2019-43
refinedweb
302
66.13
Using C# Domain Objects to Define Couchbase Views. One of the overloads for creating new design documents allows you to specify a Stream as the source of the design document. With this version, it's easy to create design documents from a set of files. You can also just specify a string containing the document. I recently had an idea to create a simple command line utility to use these design doc management methods to automate the creation of basic views. The result of this idea is up on GitHub at. Using this framework, you'll be able to automate the creation of views simply by decorating your existing model classes with custom attributes. Consider a Beer class with a properties for Name, Description, Brewery and ABV. { public string Id { get; set; } public string Name { get; set; } public string Description { get; set; } public float ABV { get; set; } public string Brewery { get; set; } } This class maps to "beer" documents in your Couchbase bucket. "name": "Samuel Adams Summer Ale", "abv": 5.2, "type": "beer", "brewery_id": "110f04db06", "description": "Bright and citrusy, brewed with mysterious grains of... } To achieve this mapping, you'd likely use Newtonsoft.Json's property mapping attributes. { public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("abv")] public float ABV { get; set; } [JsonProperty("breweryId")] public string Brewery { get; set; } } Using two new attributes found in the CouchbaseModelViews.Framework project, you could further decorate this class to declare which properties in this class should be indexed by Couchbase Server. These attributes are CouchbaseDesignDocument and CouchbaseViewKey. public class Beer { public string Id { get; set; } [JsonProperty("name")] [CouchbaseViewKey("by_abv_and_name", "name", 1)] [CouchbaseViewKey("by_name", "name")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("abv")] [CouchbaseViewKey("by_abv_and_name", "abv", 0)] public float ABV { get; set; } [JsonProperty("breweryId")] [CouchbaseViewKey("by_brewery", "breweryId")] public string Brewery { get; set; } } The CouchbaseDesignDoc attribute is set on a model class. It uses a plain-old-CLR-object (POCO) to define a design document. If you omit the name argument, a design document with the same name (lowercased) as the class will be created. If you omit the type argument, views will check that documents have a type property with the value of the name (lowercased) of the class. The CouchbaseViewKey attribute is set on properties in a POCO class that should be indexed. For example, the Name property in the Beer class above has a CouchbaseViewKey attribute on it with the arguments "by_name" and "name." The view that will result from these values is as follows: if (doc.type == "beer" && doc.name) { emit(doc.name, null); } } The "by_name" argument is the name of this view and the "name" argument defines what property is checked for existence and emitted. It's also possible to include composite keys by decorating multiple properties with CouchbaseViewKey attributes containing the same value for the viewName parameter. Composite keys are demonstrated with "by_abv_and_name" on the ABV and Name properties. Notice also that there is an optional order parameter that allows you to set the order in which properties are emitted. if (doc.type == "beer" && doc.abv && doc.name) { emit([doc.abv, doc.name], null); } } Once you've decorated your class with the appropriate attributes, you can use the CouchbaseModelViewsGenerator project to run the models through the view generator. This is a simple command line project that requires an app.config with a section listing all assemblies containing models that will be used to create views. <section name="assemblies" type="System.Configuration.DictionarySectionHandler"/> </sectionGroup> <modelViews> <assemblies> <add key="DemoModels" value="CouchbaseModelViews.DemoModels" /> </assemblies> </modelViews> Additionally, you will need to configure the CouchbaseCluster. CouchbaseCluster instances are creating using the same configuration (code or app.config) as the existing CouchbaseClient. However, there are now an additional two properties you can set to provide the administrator credentials. <servers bucket="default" bucketPassword="" username="Administrator" password="qwerty"> <add uri="" /> </servers> </couchbase> Once you've setup your app.config, make sure you have the listed assemblies in the bin directory where they can be loaded. The easiest way to achieve this discover-ability is of course to reference them. However, if you just want to use a compiled version of the console app, then simply copy them into the bin directory. When executed, the framework will create a "beers" design document that looks like the following: "views": { "by_abv_and_name": { "map": "function(doc, meta) { \r\n\t if (doc.type == \"beer\" && doc.abv && doc.name) { \r\n\t\t emit([doc.abv, doc.name], null); \r\n\t } \r\n }" }, "by_name": { "map": "function(doc, meta) { \r\n\t if (doc.type == \"beer\" && doc.name) { \r\n\t\t emit(doc.name, null); \r\n\t } \r\n }" }, "by_brewery": { "map": "function(doc, meta) { \r\n\t if (doc.type == \"beer\" && doc.breweryId) { \r\n\t\t emit(doc.breweryId, null); \r\n\t } \r\n }" } } } The console contains no actual view creation logic. It just orchestrates calls to the various plumbing components inside the Framework project. If you prefer to include the view creation inside of Global.asax or some other app start event, you could simply make these calls yourself. There are four primary components of the framework. - The ConfigParser simply reads the list of assemblies from the config section and generates an enumerable list of assemblies. - The ViewBuilder class takes an assembly or enumerable list of assemblies and iterates over each of the types. For each type found with a CouchbaseDesignDoc attribute, views are constructed. The Build method of the ViewBuilder returns a dictionary, where the keys are design doc names and the values are the actual design docs. - The DesignDocManager takes a dictionary with doc name, design doc pairs and uses the CouchbaseCluster to create design documents. - There's also a ViewRunner class, which will run the newly created views. var builder = new ViewBuilder(); builder.AddAssemblies(assemblies.ToList()); var designDocs = builder.Build(); var ddManager = new DesignDocManager(); ddManager.Create(designDocs, (s) => Console.WriteLine("Created {0} design doc", s)); var runner = new ViewRunner(); runner.Run(designDocs, (k, v, s) => Console.WriteLine("[{0}::{1}] Key {2}", k, v, s["key"]), 5); There is no coupling between any two of these three components and you can use them as you wish. If you have your own assembly gathering facility for example, simply pass it to the ViewBuilder.Build to render the JSON needed to create the views. At this point, the framework is mostly complete and reasonably tested. The code has a few more loops than I'd like and I might have overused Tuples , but it works. Feel free to use it in your projects. Keep in mind, this is a Couchbase Labs project and isn't officially supported. Remember too that it's using the Beta version of the .NET Couchbase Client Library and the API is subject to change.
http://blog.couchbase.com/kr/using-c-domain-objects-define-couchbase-views
CC-MAIN-2014-41
refinedweb
1,139
57.87
evand ev_check- customise your event loop! ev_embed- when one backend isn't enough... ev_fork- the audacity to resume the event loop after a fork libev - a high performance full-featured event loop written in C #include <ev.h> #include <ev.h> */ } static void. Libev supports poll, the Linux-specific epoll, the BSD-specific kqueue and the Solaris-specific event port mechanisms for file descriptor events ( ev_io), the Linux inotify interface (for ev_stat),). Libev is very configurable. In this manual the default. Libev represents time as a single floating point number, representing the (fractional) number of seconds since the (POSIX) epoch (somewhere near the beginning of 1970, details are complicated, don't ask). This type is called ev_tstamp, which is what you should use too. It usually aliases to the double type in C, and when you need to do any calculations on it, you should treat it as such. These functions can be called anytime, even before initialising the library in any way. Returns the current time as libev would use it. Please note that the ev_now function is usually faster and also often returns the timestamp you actually want to know. You can find out the major and minor version numbers of the library you linked against by calling the functions ev_version_major and ev_version_minor. If you want, you can compare against the global symbols EV_VERSION_MAJOR)); Return the set of all backends (i.e. their corresponding EV_BACKEND_* value) compiled into this binary of libev (independent of their availability on the system you are running on). See)); Return the set of all backends compiled into this binary of libev and also recommended for this platform. This set is often smaller than the one returned. Returns the set of backends that are embeddable in other event loops. This is the theoretical, all-platform, value. To find which backends might be supported on the current system, you would need to look at ev_embeddable_backends () & ev_supported_backends (), likewise for recommended ones. See the description of ev_embed watchers for more info.); An event loop is described by a struct ev_loop *. The library knows two types of such loops, the ev_backend () afterwards). If you don't know what event loop to use, use the one returned from this function. ored, or to work around bugs. EVFLAG_FORKCHECK Instead of calling ev_default_fork or ev_loop_fork manually noticable (on my Linux system for example, getpid is actually a simple 5-insn sequence without a syscall and thus very fast, but my Linux system also has pthread_atfork which is even faster). The big advantage of this flag is that you can forget about fork (and forget about forgetting to tell libev about forking) when you use this flag. This flag setting cannot be overriden or specified in the LIBEV_FLAGS environment variable.. EVBACKEND_DEVPOLL(value 16, Solaris 8) This is not implemented yet (and might never. EVBACKEND_ALL Try all backends (even potentially broken ones that wouldn't be tried with EVFLAG_AUTO). Since this is a mask, you can do stuff such); Similar"); Destroys the default loop again (frees all memory and kernel state etc.). None of the active event watchers will be stopped in the normal sense, so e.g. ev_is_active might still return true. It is your responsibility to either stop all watchers cleanly yoursef before calling this function, or cope with the fact afterwards (which is usually the easiest thing, youc na just ignore the watchers and/or free () them for example). Like ev_default_destroy, but destroys an event loop created by an earlier call to ev_loop_new. This function reinitialises the kernel state for backends that have one. Despite the name, you can call it anytime, but it makes most sense after forking, in either the parent or child process (or both, but that again makes little sense). You pthread_atfork: pthread_atfork (0, 0, ev_default_fork); At the moment, EVBACKEND_SELECT and EVBACKEND_POLL are safe to use without calling this function, so if you force one of those backends you do not need to care. Like ev_default_fork, but acts on an event loop created by ev_loop_new. Yes, you have to call this on every allocated event loop after fork, and how you do this is entirely your own problem. Returns one of the EVBACKEND_* flags indicating the event backend in use.). Finally, this is it, the event handler. This function usually is called after you initialised all your watchers and you want to start handling events. If the flags argument is specified as 0, it will not return until either no event watchers are active anymore or ev_unloop was called. Please note that an explicit EVLOOP_NONBLOCK will look for new events, will handle those events and any outstanding ones, but will not block your process in case there are no events and will return after one iteration of the loop. A flags value ev_prepare/ ev_check watchers is usually a better approach for this kind of thing. Here are the gory details of what ev_loop does: * If there are no active watchers (reference count is zero), return. - Queue! Can be used to make a call to ev_loop return early (but only after it has processed all outstanding events). The how argument must be either EVUNLOOP_ONE, which will make the innermost ev_loop call return, or EVUNLOOP_ALL, which will make all nested ev_loop calls return. Ref/unref can be used to add or remove a reference count on the event loop: Every watcher keeps one reference, and as long as the reference count is nonzero, ev_loop will not return on its own. If you have a watcher you never unregister that should not keep ev_loop from returning, ev_unref() after starting, and ev_ref() before stopping it. For example, libev itself uses this for its internal signal pipe: It is not visible to the libev user and should not keep ev_loop from exiting if no event watchers registered by it are active. It is also an excellent way to do this for generic recurring timers or from within third-party libraries. Just remember to unref after start and ref before stop. Example: Create a signal watcher, but keep it from keeping); A watcher is a structure that you create and register to record your interest in some event. For instance, if you want to wait for STDIN to become readable, you would create ev_<type>_set (watcher *, ...) macro with arguments specific to_io watcher has become readable and/or writable. EV_TIMEOUT_loop starts to gather new events, and all ev_check watchers are invoked just after ev_loop has gathered them, but before it invokes any callbacks for any received events. Callbacks of both watcher types can start and stop as many watchers as they want, and all of them will be taken into account (for example, a ev_prepare watcher might start an idle watcher to keep ev_loop from blocking). EV_EMBED The embedded event loop specified in the ev_embed watcher needs attention. EV_FORK The event loop has been resumed in the child process after fork (see ev_fork).. In the following description, TYPE stands for the watcher type, e.g. timer for ev_timer watchers and io for ev_io watchers. (*)(ev_loop *loop, ev_TYPE *watcher, int revents). ev_TYPE_set(ev_TYPE *, . ev_TYPE_init(ev_TYPE *watcher, callback, [args]) This convinience macro rolls both ev_init and ev_TYPE_set macro calls into a single call. This is the most convinient method to initialise a watcher. The same limitations apply, of course. ev_TYPE_start(loop *, ev_TYPE *watcher) Starts (activates) the given watcher. Only active watchers will receive events. If the watcher is already active nothing will happen. ev_TYPE_stop(loop *, ev_TYPE *watcher) Stops the given watcher again (if active) and clears the pending status. It is possible that stopped watchers are pending (for example, non-repeating timers are being stopped when they become pending), but) and you must make sure the watcher is available to libev (e.g. you cnanot free () it). Returns the callback currently set on the watcher. Change the callback. You can change the callback at virtually any time (modulo threads). Each watcher has, by default, a member my_biggy is a bit more complicated, you need to use offsetof: #include <stddef.h> static void t1_cb (EV_P_ struct ev_timer *w, int revents) { struct my_biggy big = (struct my_biggy * (((char *)w) - offsetof (struct my_biggy, t1)); } static void t2_cb (EV_P_ struct ev_timer *w, int revents) { struct my_biggy big = (struct my_biggy * (((char *)w) - offsetof (struct my_biggy, t2)); } EVBACKEND_SELECT and EVBACKEND_POLL). Another thing you have to watch out for is that it is quite easy to receive "spurious" readyness notifications, that is your callback might be called with EV_READ but a subsequent seperately re-test wether a file descriptor is really ready with a known-to-be good interface such as poll (fortunately in our Xlib example, Xlib already does this on its own, so its quite safe to use). Configures an ev_io watcher. The fd is the file descriptor to rceeive events for and events is either EV_READ, EV_WRITE or EV_READ | EV_WRITE); ev_loop . Configure the timer to trigger after after seconds. If repeat is 0., then it will automatically be stopped. If it is positive, then the timer will automatically be configured to trigger again repeat value), or reset the running timer to ev_timer with a repeat value of 60 and then call ev_timer_again the after value and ev_timer_start altogether and only ever use the repeat value and ev_timer_again: ev_timer_init (timer, callback, 0., 5.); ev_timer_again (loop, timer); ... timer->again = 17.; ev_timer_again (loop, timer); ... timer->again = 10.; ev_timer_again (loop, timer); This is more slightly efficient then stopping/starting the timer each time you want to modify its timeout value. The current repeat value. Will be used each time the watcher times out or ev_timer_again is called and determines the next timeout (if any), which is also when any modifications are taken into account. Example: Create a timer that fires after 60 seconds. static void. static void timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) { .. ten seconds without any activity } struct ev_timer mytimer; ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ ev_timer_again (&mytimer); /* start timer */ ev_loop . ev_now () + 10.) and then reset your system clock to the last year, then it will take a year to trigger the event (unlike ( at) has been passed, but if multiple periodic timers become ready during the same loop iteration then order of execution is undefined. Lots of arguments, lets sort it out... There are basically three modes of operation, and we will explain them from simplest to complex: In this configuration the watcher triggers an event ev_periodic will try to run the callback in this mode at the next possible time where time = at (mod interval), regardless of any time jumps. In this mode the values for interval and at event loop modifications. If you need to stop it, return now + 1e30 (or so, fudge fudge) and stop it afterwards (e.g. by starting a prepare watcher). Its prototype later than the passed now value. Not even now itself will do, it must be larger. This can be used to create very complex timers, such as a timer that triggers on each midnight, local time. To do this, you would calculate the next midnight after now and return the timestamp value for this. How you do this is, again, up to you (but it is not trivial, which is the main reason I omitted it as an example).). clock is divisible by 3600. The callback invocation times have potentially a lot of jittering, but good long-term stability. static void: struct).. The process id this watcher watches out for, or 0, meaning any process id. The process id that detected a status change. The process exit/trace status caused by rpid (see your systems waitpid and sys/wait.h documentation for details). Example: Try to exit cleanly on SIGINT and SIGTERM. static void sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents) { ev_unloop (loop, EVUNLOOP_ALL); } struct ev_signal signal_watcher; ev_signal_init (&signal_watcher, sigint_cb, SIGINT); ev_signal_start (loop, &sigint_cb); ev_stat- did the file attributes just change? This watches a filesystem path for attribute changes. That is, it calls st_nlink field being zero (which is otherwise always forced to be at least one) and all the other fields of the stat buffer having unspecified contents. The path should be absolute and must not end in a slash. If it is relative and your working directory changes, the behaviour is undefined. Since there is no standard to do this, ev_stat watchers, which means that libev sometimes needs to fall back to regular polling again even with inotify, but changes are usually detected immediately, and if the file exists there will be no polling. be receive EV_STAT when a change was detected, relative to the attributes at the time the watcher was started (or the last change was detected). Updates the stat buffer immediately with new values. If you change the watched path in your callback, you could call this fucntion to avoid detecting this change (while introducing a race condition). Can also be useful simply to find out the new values. The most-recently detected attributes of the file. Although the type is of ev_statdata, this is usually the (or one of the) struct stat types suitable for your system. If the st_nlink member is 0, then there was some error while stating the file. The previous attributes of the file. The callback gets invoked whenever prev != attr. The specified interval. The filesystem path that is being watched.); ev_idle- when you've got nothing better to do... Idle watchers trigger events when there are no other events are pending (prepare, check and other idle watchers do not count). That is, as long as your process is busy handling sockets or timeouts (or even signals, imagine) it will not be triggered. But when your process is idle all idle watchers are being called again and again, once per event loop iteration - until stopped, that is, or your process receives more events and becomes busy..); ev_prepareand ev_check- customise your event loop! Prepare and check watchers are usually (but not always) used in tandem: prepare watchers get invoked before the process blocks and check watchers afterwards. You must not call ev_loop). Initialises and configures the prepare or check watcher - they have no parameters of any kind. There are ev_prepare_set and ev_check_set macros, but using them is utterly, utterly and completely pointless. Example: To include a library such as adns, you would add IO watchers and a timeout watcher in a prepare handler, as required by libadns, and in a check watcher, destroy them and call into libadns. What follows is pseudo-code only of course: static ev_io iow [nfd]; static ev_timer tw; static void io_cb (ev_loop *loop, ev_io *w, int revents) { // set the relevant poll flags // could also call adns_processreadable etc. here struct pollfd *fd = (struct pollfd *)w->data; if (revents & EV_READ ) fd->revents |= fd->events & POLLIN; if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT; } // create io watchers for each fd and a timer before blocking static void adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents) { int timeout = 3600000;truct on; iow [i].data = fds + i; ev_io_start (loop, iow + i); } } // stop all watchers after blocking static void adns_check_cb (ev_loop *loop, ev_check *w, int revents) { ev_timer_stop (loop, &tw); for (int i = 0; i < nfd; ++i) ev_io_stop (loop, iow + i); adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop)); } (you could also start an idle watcher to give the embedded loop strictly lower priority for example). You can also set the callback to 0, in which case the embed watcher will automatically execute the embedded loop sweep. As long as the watcher is started it will automatically handle events. The callback will be invoked whenever some events have been handled. You can set the callback to 0 to avoid having to specify one if you are not interested in that. Also, there have not currently been made special provisions for forking: when you fork, you not only have to call ev_loop_fork on both loops, but you will also have to stop and restart any ev_embed watchers yourself.; thta, you need to temporarily stop the embed watcher). Make a single, non-blocking sweep over the embedded loop. This works similarly to ev_loop (embedded_loop, EVLOOP_NONBLOCK), but in the most apropriate way for embedded loops. The embedded event loop. ev_fork- the audacity to resume the event loop after a fork Fork watchers are called when a fork () was detected (usually because whoever is a good citizen cared to tell libev about it by calling ev_default_fork or. Initialises and configures the fork watcher - it has no parameters of any kind. There is a ev_fork_set macro, but using it is utterly pointless, believe me. There are some other functions of possible interest. Described. Here. Now. fd is less than 0, then no I/O watcher will be started and events is being ignored. Otherwise, an ev_io watcher for the given fd and events set will be craeted and started. If timeout is less than 0, then no timeout watcher will be started. Otherwise an ev_timer watcher with after = timeout (and repeat = 0) will be started. While 0 is a valid timeout, it is of dubious value. The callback has the type void (*cb)(int revents, void *arg) and gets passed an revents set like normal event callbacks (a combination of EV_ERROR, EV_READ, EV_WRITE or EV_TIMEOUT) and the arg value passed to ev_once: static void stdin_ready (int revents, void *arg) { if (revents & EV_TIMEOUT) /* doh, nothing entered */; else if (revents & EV_READ) /* stdin might have data for us, joy! */; } ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); Feeds the given event set into the event loop, as if the specified event had happened for the specified watcher (which must be a pointer to an initialised but not necessarily started event watcher). Feed an event on the given fd, as if a file descriptor backend detected the given events it. Feed an event as if the given signal occured ( loop must be the default loop!). Libev offers a compatibility emulation layer for libevent. It cannot emulate the internals of libevent, so here are some usage hints:. ev::statonly Invokes (this, &myclass::io_cb), idle (this, &myclass::idle_cb) { io.start (fd, ev::READ); } Libev can be compiled with a variety of options, the most fundemantal is EV_MULTIPLICITY. This option determines wether form is used when this is the sole argument, EV_A_ is used when other arguments are following. Example: ev_unref (EV_A); ev_timer_add (EV_A_ watcher); ev_loop (EV_A_ 0); It assumes the variable loop of type struct ev_loop * is in scope, which is often provided by the following macro. EV_P, EV_P_ This provides the loop parameter for functions, if one is required ("ev loop parameter"). The EV_P form of type struct ev_loop *, quite suitable for use with EV_A. EV_DEFAULT, EV_DEFAULT_ Similar to the other two macros, this gives you the value of the default loop, if multiple loops are supported ("ev loop default"). Example: Declare and initialise a check watcher, utilising the above macros so it will work regardless of wether multiple loops are supported or not. static void check_cb (EV_P_ ev_timer *w, int revents) { ev_check_stop (EV_A_ w); } ev_check check; ev_check_init (&check, check_cb); ev_check_start (EV_DEFAULT_ &check); ev_loop (EV_DEFAULT_ 0);). Depending on what features you need you need to include one or more sets of files in your app. Instead of using EV_STANDALONE=1 and providing your config any of its files. The default is not to build for multiplicity and only include the select backend. Must always be 1 if. If defined to clock_gettime function is hiding in (often -lrt).. See tzhe note about libraries in the description of EV_USE_MONOTONIC, though. If undefined or defined to be 1, libev will compile in support for the select(2) backend. No attempt at autodetection used. on the fd to convert it to an OS handle. Otherwise, it is assumed that all these functions actually work on fds, even on win32. Should not be defined on non-win32 platforms.. The name of the ev.h header file used to include it. The default if undefined is <ev.h> in event.h and "ev.h" in ev. If defined to be 0, then ev.h will not define any function prototypes, but still define all the structs and other symbols. This is occasionally useful if you want to provide your own wrapper functions around libev functions.. If undefined or defined to be 1, then periodic timers are supported. If defined to be 0, then they are not. Disabling them saves a few kB of code. If undefined or defined to be 1, then embed watchers are supported. If defined to be 0, then they are not. If undefined or defined to be 1, then stat watchers are supported. If defined to be 0, then they are not. If undefined or defined to be 1, then fork watchers are supported. If defined to be 0, then they are not. If you need to shave off some kilobytes of code at the expense of some speed, define this symbol to 1. Currently only used for gcc to override some inlining decisions, saves roughly 30% codesize of amd64. ev_child watchers use a small hash table to distribute workload by pid. The default size is 16 (or 1 with EV_MINIMAL), usually more than enough. If you need to manage thousands of children you might want to increase this value (must be a power of two). ev_staz watchers use a small hash table to distribute workload by inotify watch id. The default size is 16 (or 1 with EV_MINIMAL), usually more than enough. If you need to manage thousands of ev_stat watchers you might want to increase this value (must be a power of two). ";" */ Can be used to change the callback member declaration in each watcher, and the way callbacks are invoked and set. Must expand to a struct member definition and a statement, respectively. See the ev.v header file for their default definitions. One possible use for overriding these is to avoid the struct ev_loop * as first argument in all cases, or to use method calls instead of plain function calls in C++. ev_cpp.C implementation file that contains libev proper and is compiled: #include "ev_cpp.h" #include "ev.c" In this section the complexities of (many of) the algorithms used inside libev will be explained. For complexity discussions about backends see the documentation for ev_default_init. Marc Lehmann <libev@schmorp.de>.
https://git.lighttpd.net/mirrors/libev/raw/commit/c395297635f8b8997d698ebe27a49789abd4ce79/ev.html
CC-MAIN-2022-27
refinedweb
3,701
63.59
OUTERTHOUGHT.BLOGMusings on Open Source Java and XMLtag:blog.outerthought.org,2008:DaisyDaisy2012-04-19T12:06:10.000ZOuterthought2012-04-19T12:06:10.000ZLily 1.2 is out!tag:blog.outerthought.org,2008:Daisy493-ot <p xmlns:We’re very happy to announce the release of Lily 1.2. It contains a number of improvements and exciting new features, both on the open source and the enterprise side of things.</p> <p> <strong>Lily Core 1.2</strong> </p> <p>First of all, Lily has been upgraded and verified to be CDH3u3 compatible. We’re also closely tracking CDH4 evolutions and are confident to be among the first to ship a CDH4-compliant version later this year.</p> <p>The most important two new features of Lily Core 1.2 are along improved support for HBase-style operations, more importantly Scanners and Map/Reduce support.</p> <p> <strong>Lily Scanners</strong> </p> <p>Similar to HBase Scanners, Lily Scanners allow you to <a xmlns:scan over records</a>, making use of the natural ordering of records using their row key or record ID. As you might know, Lily supports both system-generated as well as user-specified IDs, and experience taught us the latter are commonly used. Using user-specified IDs, Lily Scanners allow you to influence the storage order of records in Lily, and iterate over them based on ID, range of IDs (start/stop), in an indexed fashion, i.e. fast.</p> <p>Even better, Scanners support the use of filters to select records based on filter expressions, which means if you’re smart about key design, you might no longer need other search indexes to Lily content (such as Solr) for simple search and retrieval operations.</p> <p>You can selectively return only a subset of records fields while scanning, and filter based on RecordType and record ID prefix. Also, using filters, this allows for (Solr) index rebuilds of partial data sets.</p> <p>Lily 1.2 ships with a <a href="">CLI tool</a> allowing to do simple command line Scans.</p> <p> <strong>Lily Map/Reduce</strong> </p> <p>Even though Map/Reduce was already being used for scalable batch rebuilding of search indexes, it wasn’t generally available for people that wanted to process Lily data in map-reduce style for other purposes.</p> <p>With the 1.2 release, Lily supports a LilyScanInputFormat which allows you to use Scanners (and filters) to specify the input to a Lily-based map/reduce job. Lily ships with <a href="">Maven artefacts for generating</a> a skeleton M/R job, too.</p> <p> <strong>Lily testing framework</strong> </p> <p>For those of you using the Lily test framework to develop Lily client applications, you will find startup and tear-down times of the ‘Lily Embed’ tool to be much shorter. Being software engineers ourselves for a long time, we care a lot about the engineer’s experience when developing against Lily. With this improvement, running a Lily development workbench on a laptop or workstation, building and testing has become much more efficient.</p> <p> <strong>Lily Enterprise 1.2</strong> </p> <p>The 1.2 release of Lily Enterprise contains two major improvements: a better, more stable cluster installer, and support for Pentaho Kettle for ETL operations.</p> <p> <strong>Pentaho Data Integration support</strong> </p> <p>Lily is often used as the central data aggregation tier in enterprise deployments, and we want to make the task of bringing data into Lily as easy as possible.</p> <p>Lily Enterprise 1.2 contains a <a href="">Kettle LilyOutput plugin</a>. Kettle, or Pentaho Data Integration, is a powerful ETL tool that connects to many different data sources. Using a simple, UI-based configuration, the Lily Kettle integration allows you to effortlessly, and most importantly without any coding, set up a transformation and loading pipeline to inject data into the Lily Data Repository from a variety of sources, such as relational databases, static files, and even enterprise back-end systems.</p> <p> <strong>Roadmap</strong> </p> <p>Starting with this release, we are now committed to regular releases of Lily Core and Enterprise. We will have three major releases per year – with Lily Enterprise customers having access to schedule and planned features.</p> <p>Thanks for reading this far, and we hope you will enjoy using Lily 1.2 as much as we enjoyed building it.</p> <img src="" height="1" width="1" alt=""/> joins NGDATAtag:blog.outerthought.org,2008:Daisy492-ot <p xmlns:I have some really exciting news to share with you today: Outerthought is now part of a larger company that is committed to bringing Lily to the next level. </p> <p>As interest in Lily was growing at an increasingly fast pace, it became clear that it deserved a strong, growth-targeted and globally-oriented company with a world-class management team.</p> <p>I'm therefore extremely excited to announce that Outerthought is now part of <a xmlns:NGDATA</a>, a Big Data software company that makes sense of your data. NGDATA is planning to secure additional capital to accelerate the development and roll-out of Lily’s roadmap and to support business development activities in the United States. We will make Lily into the best Big Data management platform out there, with a special focus on large-scale machine learning and recommendations in real-time.</p> <p>My role will be VP Product of NGDATA, listening to and working with customers and partners, market research and analysts, and generally making sure Lily has an awesome roadmap. I welcome Luc Burgelman (CEO), Frank Hamerlinck (COO) and Jürgen Ingels as co-founders and private investors of NGDATA, and Anne-Mie Poot as our VP HR.</p> <p>I'm really proud of what Outerthought has achieved in the Big Data space so far, and the future is looking really promising. I'd also like to thank the Outerthought team for their effort and contribution in getting us where we are today! Thanks to anyone who helped us along the way - you won't be disappointed with what comes next.</p> <p>The official announcement can be read on the NGDATA website - <a href=""></a>. </p> <p>Steven Noels<br> CEO Outerthought,<br> VP Product NGDATA.</p> <img src="" height="1" width="1" alt=""/> First Exploration Of SolrCloudtag:blog.outerthought.org,2008:Daisy491-ot <p xmlns:SolrCloud has recently been in <a xmlns:the</a> <a href="">news</a> and was merged into Solr trunk, so it was high time to have a fresh look at it. </p> <p>The <a href="">SolrCloud wiki page</a> gives various examples but left a few things unclear for me. The examples only show Solr instances which host one core/shard, and it doesn’t go deep on the relation between cores, collections and shards, or how to manage configurations. </p> <p>In this blog, we will have a look at an example where we host multiple shards per instance, and explain some details along the way.</p> <p>The setup we are going to create is shown in this diagram.</p> <p align="center"> <img alt="solrcloud sample setup" title="solrcloud sample setup" src="/blog/490-ot/version/default/part/ImageData/data/solrcloud sample setup.png"></p> <h3>SolrCloud terminology</h3> <p>In SolrCloud you can have multiple collections. Collections can be divided into partitions, these partitions are called slices. Each slice can exist in multiple copies, these copies of the same slice are called shards. So the word shard has a bit of a confusing meaning in SolrCloud, it is rather a replica than a partition. One of the shards within a slice is the leader, though this is not fixed: any shard can become the leader through a leader-election process.</p> <p>Each shard is a physical index, so one shard corresponds to one Solr core. </p> <p>If you look at the SolrCloud wiki page, you won’t find the word slice [anymore]. It seems like the idea is to hide the use of this word, though once you start looking a bit deeper you will encounter it anyway so it’s good to know about it. It’s also good to know that the words shard and slice are often used in ambiguous ways, switching one for the other (even in the sources). Once you know this, things become more comprehensible. An interesting <a href="">quote</a> in this regard: “removing that ambiguity by introducing another term seemed to add more perceived complexity”. In this article I'll use the words slice and shard as defined above, so that we can distinguish the two concepts.</p> <p>In SolrCloud, the Solr configuration files like schema.xml and solrconfig.xml are stored in ZooKeeper. You can upload multiple configurations to ZooKeeper, each collection can be associated with one configuration. The Solr instances hence don’t need the configuration files to be on the file system, they will read them from ZooKeeper.</p> <h3>Running ZooKeeper</h3> <p>Let’s start by launching a ZooKeeper instance. While Solr allows to run an embedded ZooKeeper instance, I find that this rather complicates things. ZooKeeper is responsible for storing coordination and configuration information for the cluster, and should be highly available. By running it separately, we can start and stop Solr instances without having to think about which one(s) embed ZooKeeper.</p> <p>For the purpose of this article, you can get it running like this:</p> <ul> <li> <a href="">download ZooKeeper 3.3</a>. Don’t take version 3.4, as it’s not recommended for production yet. </li> <li>extract the download</li> <li>copy conf/zoo_sample.cfg to conf/zoo.cfg</li> <li>mkdir /tmp/zookeeper (path can be changed in zoo.cfg)</li> <li>./bin/zkServer.sh start</li> </ul> <p>And that’s it, you have ZooKeeper running.</p> <h3>Setting up Solr instance directories</h3> <p>We are going to run two Solr instances, thus we’ll need two Solr instance directories.</p> <p>Let’s create two directories like this:</p> <pre>mkdir -p ~/solrcloudtest/sc_server_1 mkdir -p ~/solrcloudtest/sc_server_2</pre> <p>Create the file ~/solrcloudtest/sc_server_1/solr.xml containing:</p> <pre><solr persistent="true"> <cores adminPath="/admin/cores" hostPort=”8501”> </cores> </solr></pre> <p>Create the file ~/solrcloudtest/sc_server_2/solr.xml containing (note the different hostPort value):</p> <pre><solr persistent="true"> <cores adminPath="/admin/cores" hostPort=”8502”> </cores> </solr></pre> <p>We need to specify the hostPort attribute since Solr can’t detect the port, it falls back to the default 8983 when not specified.</p> <p>This is all we need: the actual core configuration will be uploaded to ZooKeeper in the next section.</p> <h3>Creating a Solr configuration in ZooKeeper</h3> <p>As explained before, the Solr configuration needs to be available in ZooKeeper rather than on the file system.</p> <p>Currently, you can upload a configuration directory from the file system to ZooKeeper as part of the Solr startup. It is also possible to run ZkController’s main method for this purpose (<a href="">SOLR-2805</a>), but as there’s no script to launch it, the easiest way right now to upload a configuration is by starting Solr:</p> <pre>export SOLR_HOME=/path/to/solr-trunk/solr # important: move into one the instance directory! # (otherwise Solr will start up with defaults and create a core etc.) cd sc_server_1 java \ -Djetty.port=8501 \ -Djetty.home=$SOLR_HOME/example/ \ -Dsolr.solr.home=. \ <strong>-Dbootstrap_confdir=$SOLR_HOME/example/solr/conf </strong>\ <strong>-Dcollection.configName=config1</strong> \ -DzkHost=localhost:2181 \ -jar $SOLR_HOME/example/start.jar</pre> <p>Now that the configuration is uploaded, you can stop this Solr instance again (ctrl+c).</p> <p>We can now check in ZooKeeper that the configuration has been uploaded, and that no collections have been created yet.</p> <p>For this, go to the ZooKeeper directory, and run <tt>./bin/zkCli.sh</tt>, and do the following commands:</p> <pre>[zk: localhost:2181(CONNECTED) 1] ls /configs [config1] [zk: localhost:2181(CONNECTED) 2] ls /collections []</pre> <p>You could repeat this process to upload more configurations.</p> <p>If you would like to change a configuration later on, you essentially have to upload it again in the same way. The various Solr cores that make use of that configuration won’t be reloaded automatically however (<a href="">SOLR-3071</a>).</p> <h3>Starting the Solr servers</h3> <p>All SolrCloud magic is activated by specifying the zkHost parameter. Without this parameter, you run Solr ‘classic’, with the parameter, you run SolrCloud. If you look into the source code, you will see that this parameter causes the creation of a ZkController, and at various places checks of the kind ‘zkController != null’ are done to change behavior when in cloud mode.</p> <p>Open two shells, and start the two Solr instances:</p> <pre>export SOLR_HOME=/path/to/solr-trunk/solr cd sc_server_1 java \ -Djetty.port=8501 \ -Djetty.home=$SOLR_HOME/example/ \ -Dsolr.solr.home=. \ -DzkHost=localhost:2181 \ -jar $SOLR_HOME/example/start.jar</pre> <p>and (note: different instance dir & jetty port)</p> <pre>export SOLR_HOME=/path/to/solr-trunk/solr cd sc_server_2 java \ -Djetty.port=8502 \ -Djetty.home=$SOLR_HOME/example/ \ -Dsolr.solr.home=. \ -DzkHost=localhost:2181 \ -jar $SOLR_HOME/example/start.jar</pre> <p>Note that now, we don’t have to specify the boostrap_confdir and collection.configName properties anymore (though that last one can still be useful as default sometimes, but not with the way we will create collections & shards below).</p> <p>We have neither added the -Dnumshards parameter, which you might have encountered elsewhere. When you manually assign cores to shards as we will do below, I don’t think it serves any purpose.</p> <p>So the situation now is that we have two Solr instances running, both with 0 cores.</p> <h3>Define the cores, collections, slices, shards</h3> <p>We are now going to create cores, and assign each core to a specific collection and slice. It is not necessary to define collections & shards anywhere, they are implicit by the fact that there are cores that refer them. </p> <p>In our example, the collection is called 'collectionOne' and the slices are called 'slice1' and 'slice2'.</p> <p>Let’s start with creating a core on the first server:</p> <pre>curl ''</pre> <p>(in the URL above, and the solr.xml snippet below, the word 'shard' is used for 'slice')</p> <p>If you have a look now at sc_server_1/solr.xml, you will see the core was added:</p> <pre><?xml version="1.0" encoding="UTF-8" ?> <solr persistent="true"> <cores adminPath="/admin/cores" zkClientTimeout="10000" hostPort="8501" hostContext="solr"> <core name="core_collectionOne_slice1_shard1" collection="collectionOne" shard="slice1" instanceDir="core_collectionOne_slice1_shard1/"/> </cores> </solr></pre> <p>AFAIU the information in ZooKeeper takes precedence, so the attributes collection and shard on the core above serve more as documentation, or they are of course also relevant if you would create cores by listing them in solr.xml rather than using the cores-admin API. Actually listing them in solr.xml might be simpler than doing a bunch of API calls, but there is currently one limitation: you can’t specify the configName this way.</p> <p>In ZooKeeper, you can verify this collection is associated with the config1 configuration:</p> <pre>[zk: localhost:2181(CONNECTED) 5] get /collections/collectionOne {"configName":"config1"}</pre> <p>And you can also get an overview of all collections, slices and shards like this:<":"" } } } }</pre> <p>(the somewhat strange "shard_id":"slice1" is just a back-pointer from the shard to the slice to which it belongs)</p> <p>Now let’s create the remaining cores: one more on server 1, and two on server 2 (notice the different port numbers to which we send these requests).</p> <pre>curl '' curl '' curl ''</pre> <p>Let’s have a look in ZooKeeper at the current state of the clusterstate.json: <":"" }, "fietsbel:8502_solr_core_collectionOne_slice1_shard2": { "shard_id":"slice1", "state":"active", "core":"core_collectionOne_slice1_shard2", "collection":"collectionOne", "node_name":"fietsbel:8502_solr", "base_url":"" } }, "slice2": { "fietsbel:8502_solr_core_collectionOne_slice2_shard1": { "shard_id":"slice2", "leader":"true", "state":"active", "core":"core_collectionOne_slice2_shard1", "collection":"collectionOne", "node_name":"fietsbel:8502_solr", "base_url":"" }, "fietsbel:8501_solr_core_collectionOne_slice2_shard2": { "shard_id":"slice2", "state":"active", "core":"core_collectionOne_slice2_shard2", "collection":"collectionOne", "node_name":"fietsbel:8501_solr", "base_url":"" } } } }</pre> <p>We see we have:</p> <ul> <li>one collection named collectionOne</li> <li>two slices named slice1 and slice2</li> <li>each slice has two shards. Within each slice, one shard is the leader (see "leader":"true"), the other(s) are replicas. Of each slice, one shard is hosted in each Solr instance.</li> </ul> <h3>Adding some documents</h3> <p>Now let’s try our setup works by adding some documents:</p> <pre>cd $SOLR_HOME/example/exampledocs java -Durl=<strong>core_collectionOne_slice1_shard1</strong>/update -jar post.jar *.xml</pre> <p>We sent the request to one specific core, but you could have picked any other core and the end result would be the same. The request will be forwarded automatically to the leader shard of the appropriate slice. The slice is selected based on the hash of the id of the document.</p> <p>Use the admin stats page to see documents got added to all cores:</p> <p> <a href=""></a> <br> <a href=""></a> </p> <p> <a href=""></a> <br> <a href=""></a> </p> <p>In my case, the cores for slice1 got 16 documents, those for slice2, 12. Unlike the traditional Solr replication, with SolrCloud updates are sent directly to the replica's.</p> <h3>Querying</h3> <p>Let’s just query all documents. Again, we send the request to one particular shard:</p> <p> <a href="*:*">*:*</a> </p> <p>You will see the numFound=”28”, the sum of 16 and 12.</p> <p>What happens internally is that when you sent a request to a core, when in SolrCloud mode, Solr will look up what collection the core is associated with, and do a distributed query across all slices (it will pick one shard for each slice).</p> <p>The SolrCloud wiki page gives the suggestion that you can use the collection name in the URL (like /solr/collection1/select). In our example, this would then be /solr/collectionOne/select. This is however not the case, but rather a particularity of that example. As long as you don’t host more than one slice and shard of the same collection in one Solr server, it can make sense to use such a core naming strategy.</p> <h3>Starting from scratch</h3> <p>When playing around with this stuff, you might want to start from scratch sometimes. In such case, don’t forget you have to remove data in three places: (1) the state stored in ZooKeeper (2) the cores defined in solr.xml and (3) the instance directories of these cores.</p> <p>When writing the first draft of this article, I was using just one Solr instance and tried to have all the 4 cores (including replica's) in one Solr instance. Turns out there was a bug that prevents this from working correctly (<a href="">SOLR-3108</a>).</p> <h3>Managing slices & shards</h3> <p>Once you have defined a collection, you can not (or rather should not) add new slices to it, since documents won’t be automatically moved to the new slice to fit with the hash-based partitioning (<a href="">SOLR-2595</a>).</p> <p>Adding more replica shards should be no problem though. While above we have used a very explicit way of assigning each core to a particular slice, you can actually leave that parameter off and Solr will automatically assign it to some slice within the collection. (I guess here the -Dnumshards parameter kicks in to decide whether the new core should be a slice or a shard)</p> <p>How about removing replicas? It can be done, but manually. You have to unload the core and remove the related state in ZooKeeper. This is an area that will be improved upon later. (<a href="">SOLR-3080</a>)</p> <p>Another interesting thing to note is that when your run in SolrCloud mode, all cores will automatically take part in the cloud thing. If you add a core without specifying the collection, a collection named after that core will be created. You can’t mix ‘classic’ cores and ‘cloud’ cores in one Solr instance. </p> <h3>Conclusion</h3> <p>In this article we have barely touched the surface of everything SolrCloud is: there’s the update log for durability and recovery, the sync’ing between replica’s, the details of distributed querying and updating, the special _version_ field to help with some of the these points, the coordination (election of overseer & shard leaders), … Much interesting stuff to explore! </p> <p>As becomes clear from this article, SolrCloud isn't as easy to use yet as ElasticSearch. It still needs polishing and there's more manual work involved in setting it up. To some extent this has its advantages, as long as it's clear what you can expect from the system, and what you have to take care of yourself. Anyway, it's great to see that the Solr developers were able to catch up with the cloud world.</p> <img src="" height="1" width="1" alt=""/> 1.1 is out: what's new?tag:blog.outerthought.org,2008:Daisy488-ot <p xmlns:We have a nice Christmas present for you: <a xmlns:Lily 1.1 is out</a>, and there's improvements for everyone: developers, administrators and Lily hackers. Read more about the exciting new stuff in Lily 1.1 below!</p> <h3>Complex Field Types</h3> <p.</p> <p.</p> <h3>Conditional updates</h3> <p. </p> <p>For concurrency control, you can require that the value of a field needs to be the same as when the record was read before the update.</p> <h3>Test framework</h3> <p.</p> <h3>Server-side plugins</h3> <p>For the fearless Lily repository hacker, we offer two hooks to expand functionality of the Lily server process. There's decorators which can intercept any CRUD operation for pre- or post-execution of side-effect operations (like modifying a field value before actually committing it).</p> <h3>Rowlog sharding</h3> <p>The global rowlog queue is now distributed across a pre-split table, with inserts and deletes going to several region servers. This will lead to superior performance on write-or update-heavy multi-node cluster setups.</p> <h3>API improvements</h3> <p>Our first customers (*waves to our French friends*) found our API to be a tad too verbose and suggested a Builder pattern approach. We listened and unveil a totally new (but optional) method-chaining Builder API for the Java API users. </p> <h3>Whirr-based cluster installer</h3> <p.</p> <iframe src="" width="600" height="375" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe> <h3>Performance</h3> <p>Thanks to better parallelization, Lily has become considerably faster. You can now comfortably throw more clients at one Lily cluster and see combined throughput scale fast.</p> <p>All in all, Lily 1.1 was a great release to prepare. We hope you have as much fun using Lily 1.1 as we had building it. Check it out here: <a href=""></a>.</p> <img src="" height="1" width="1" alt=""/> and collaboration on Big Data recommendationstag:blog.outerthought.org,2008:Daisy487-ot <p xmlns:(press release)</p> <p>Outerthought and <a xmlns:Oxynade</a>, two software companies from the Belgian Ghent area, are collaborating in the context of the TWIRL project, a European research project on open platforms able to process, mine, interlink and fuse data originating from real world applications and on-line data sources. The research groups <a href="">IBBT/Ghent University (IBCN)</a> and <a href="">Sirris</a> join their effort.</p> <p>The research project sits at the root of new developments in Lily, the Big Data content repository from Outerthought, that will combine storage, indexing search with profile management, analytics and content recommendations in its next versions. The Lily platform is based on Apache Hadoop and HBase and is the world's first NOSQL/Big Data content repository.</p> <p>Hadoop and HBase are being used in large organizations such as TomTom, Netlog, Twitter, Facebook and Yahoo!, but the technology is still regarded as complex and finicky to use. Lily makes this technology easy to adopt and use for every organization with large-scale data management needs.</p> <p>"Research without field validation has no purpose", says Steven Noels, Outerthought CEO, "so we are very happy to be able to collaborate with Oxynade on the TWIRL project. They provide us with a lot of practical experience and knowledge about event recommendations, and they possess an immense set of practical trial data. Also, due to their international growth ambitions, they are in need of a data platform that can scale widely, which means Lily is a great fit for them."</p> <p>The TWIRL project also got the <a href="">EU ITEA label</a>, which guarantees high-quality industry research.</p> <p>Outerthought and Oxynade receive a Flemish research grant for their collaboration to the amount of 550.000 EUR for a 100 manmonth project. The tangible collaboration plans between the industry group and Sirris and IBBT as research partners had a positive impact on the grant approval.</p> <p>Contact:</p> <p>Steven Noels - Outerthought - +32 9 338 82 20<br> Niko Nelissen - Oxynade - +32 9 233 40 09</p> <img src="" height="1" width="1" alt=""/> partnership and Accenture Innovation Awardstag:blog.outerthought.org,2008:Daisy486-ot <p xmlns:As mentioned in our previous newsletter, this Summer is Hot in Lily-land. We have some more exciting announcements to make:</p> <h3>Cloudera Connect<sup>TM</sup> Partnership</h3> <p>We're very happy and proud to be included in the initial list of <a xmlns:Cloudera Connect<sup>TM</sup> Partners</a>, announced just a couple of days ago. Lily is also being prominently featured in a Solution Spotlight, explaining the value-add of Lily on top of the Cloudera Distribution of Hadoop. We're excited to work together with Cloudera on making Big Data and HBase easier to use for enterprise developers in retail, media and news.</p> <p> <a href=""><img alt="Outerthought | Apache Hadoop for the Enterprise | Cloudera" title="Outerthought | Apache Hadoop for the Enterprise | Cloudera" src="/blog/484-ot/version/default/part/ImageData/data/Outerthought | Apache Hadoop for the Enterprise | Cloudera.jpg"></a> </p> <p>If you want to learn more about how Lily fits well with Cloudera, a <a title="Outerthought-Solution-Brief" href="/blog/485-ot/version/default/part/AttachmentData/data/Outerthought-Solution-Brief.pdf">solution brief is available as well</a> (application/pdf, 160.9 kB, <a href="/blog/485-ot.html">info</a>).</p> <p> <img align="right" alt="banner120x60_tulp" title="banner120x60_tulp" src="/blog/483-ot/version/default/part/ImageData/data/banner120x60_tulp.gif"></p> <h3>Accenture Innovation Awards</h3> <p>Also, we're <a href="">participating with the Accenture Innovation Awards</a>, a yearly contest for novel business and technology ideas.</p> <img src="" height="1" width="1" alt=""/> Summer seasontag:blog.outerthought.org,2008:Daisy478-ot <p xmlns:This Summer, we’re hard at work on some exciting new features of Lily, while helping some customers to kick off their new Lily-based projects. It’s great to see our product being used in practice, a truly educational experience for ourselves as well. Let’s have a look at the new stuff. </p> <p> <strong>1. Lily Test Framework</strong> </p> <p>We’ve always said Lily is about developer conveniencing: making the hard bits easy. At the core of Lily, we’re solving the really hard problem of consistent index maintenance in between HBase and Solr. On the outside however, we also wanted to make it easy for enterprise devs to Get Things Done with Lily - as if it is just another database component they already know.</p> <p>That means it should be easy to call Lily from inside unit tests, and that you don’t need half-a-cluster per developer to just use Lily and its API to program against. We wanted something that allows you to launch Lily and all of its constituents with a single call, embedable, “laptop-class”-compatible (i.e. not relying on virtualization tools to launch pre-made Linux images with Lily, just to run Lily on a developer workstation). </p> <p>So we went off and created a <a xmlns:Lily test framework</a>, that launches Lily, HBase, Hadoop, Solr and friends quickly, easily and efficiently, with sane single-node preconfigurations and some hooks to cycle data initialization as well. It’s available from trunk since a couple of days. Some people will be really happy to learn that this <strong>Lily test framework supports Windows</strong> (except currently for map/reduce operations) as well. The Lily Test Framework allows you to call Lily from inside unit tests, either standalone or embedded. The standalone mode can also be used to quickly set up a single-node, single-process instance of Lily to play around with.</p> <p>Adding onto that, there’s a Maven goal <a href="">available now</a> to quickly set up a fresh, empty Lily project.</p> <p>All this might sound pretty mundane, and to some extend it is, but it's one of the babysteps we see necessary to emphasize that we're really serious about bringing Lily to the enterprise, <strong>not</strong> requiring PhD-level hackers to get started with Big Data.</p> <p> <strong>2. Lily cluster installs<img align="right" alt="whirr-logo" title="whirr-logo" src="/blog/481-ot/version/default/part/ImageData/data/whirr-logo.jpg"></strong> </p> <p>For Lily Enterprise customers, we’re currently preparing a <a href="">Whirr</a>-based cluster installation that supports both cloud-based installs (e.g. Amazon EC2) and "bring your own nodes" installations - on your own cluster. Whirr is an Apache project under incubation for installing, setting up and running cloud services in a platform-neutral way. We’ve been happily contributing a slew of patches and issue reports (<a href="">221</a>, <a href="">338</a>, <a href="">339</a>, <a href="">240</a> and <a href="">342</a>) while working on Lily support for Whirr.</p> <p>Using Whirr and our <a href="">Lily Enterprise</a> installation packages, setting up complex multi-node installs of Lily will be a breeze.</p> <p> <strong>3. The Lily Adoption Program</strong> </p> <p> <strong><img alt="lily-webinar-062011" title="lily-webinar-062011" src="/blog/479-ot/version/default/part/ImageData/data/lily-webinar-062011.jpg"></strong> </p> <p>As mentioned during our well-attended first <a href="">Lily webinar</a>, we've set up a Lily adoption roadmap helping enterprises to easily discover, explore, adopt, deploy and support Lily inside their organization. It's a multi-step, facilitated process with workshops, proof-of-concept support, training and implementation assistance based on our many years of project experience. The 2-day workshop is still available at a discounted rate (-20%) until end of September, so don't hesitate to get in touch with us.</p> <p>It’s a long (temperature-wise not so hot unfortunately) Summer over here in Lily-land, and we’re making great progress whipping up some exciting new features. Stay tuned for more!</p> <img src="" height="1" width="1" alt=""/> in review.tag:blog.outerthought.org,2008:Daisy474-ot <p xmlns:The AppsForGhent hacking event and contest last Saturday was a success on the many scales you can measure. For me the most important one in any case was the participation both in quality and quantity of the various teams, kuddos to all participating and giving it their best shot.</p> <p>Also nice to see is that more and more stuff (<a xmlns:code</a> and <a href="">ideas</a>) is being shared out there. Here is our <a href="">presentation</a> by the way:</p> <div style="width:425px" id="dsy473-ot___ss_7977055"> <strong style="display:block;margin:12px 0 4px"><a href="" title="20110514 appsforghent">20110514 appsforghent</a></strong><object id="dsy473-ot___sse7977055" width="425" height="355"><param name="movie" value=""><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"> <embed name="__sse7977055" src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed> </object><div style="padding:5px 0 12px">View more <a href="">presentations</a> from <a href="">Outerthought</a>.</div> </div> <p>I'm looking forward to seeing the teams (and the city) showing a prolonged commitment in the 2nd challenge of the event: creating a working application during the next two weeks and will be keeping an eye on twitter <a href="">@AppsForGhent</a> to track progress. </p> <img src="" height="1" width="1" alt=""/> Hacking @AppsForGhenttag:blog.outerthought.org,2008:Daisy472-ot <p xmlns:Today a genuine '<a xmlns:hack the goverment (of Ghent)</a>' event is taking place in the offices of <a href="http://">ibbt</a>. We got invited to sponsor the event and decided to throw in some more then just the typical goodies too share, and what better to way too show off some relevance by just delivering some hacker infrastructure? </p> <p>So we set-up a full <a href="">enterprise</a> seven node cluster for the event on virtual servers in the ibbt demo network (not public though) and preloaded it with the KML files we received from the <a href="">city</a>.<br> Being about geospatial data, the nice side-effect is some first experience with the <a href="">spatial queries in SOLR</a> </p> <p>The setup is rather straightforward, and involved:</p> <ol> <li>Installing the cluster through the lily-provisioning (see <a href="">enterpise documentation</a>)</li> <li>Parsing the placemarks from the KML files and producing lily-import-json through a naive <a href="">convertor</a> </li> <li>Creating a simple lily schema describing those records<br> <pre>{ namespaces: { "be.appsforghent.kml": "k" }, fieldTypes: [ { name: "k$name", valueType: { primitive: "STRING" }, scope: "versioned" }, { name: "k$kind", valueType: { primitive: "STRING" }, scope: "versioned" }, { name: "k$description", valueType: { primitive: "STRING" }, scope: "versioned" }, { name: "k$coordinate", valueType: { primitive: "STRING" }, scope: "versioned" }, { name: "k$address", valueType: { primitive: "STRING" }, scope: "versioned" } ], recordTypes: [ { name: "k$Placemark", fields: [ {name: "k$name" , mandatory: true }, {name: "k$kind" , mandatory: true }, {name: "k$description", mandatory: false }, {name: "k$coordinate" , mandatory: false }, {name: "k$address" , mandatory: false } ] } ] }</pre> </li> <li>Create the needed solr schema. (listing only relevant parts)<br> <pre><schema name="example" version="1.3"> <types> ... <!-- A specialized field for geospatial search. If indexed, this fieldType must not be multivalued. --> <fieldType name="location" class="solr.LatLonType" subFieldType="double"/> ... </types> <fields> <!-- Fields which are required by Lily --> <field name="lily.key" type="string" indexed="true" stored="true" required="true"/> <field name="lily.id" type="string" indexed="true" stored="true" required="true"/> <field name="lily.vtagId" type="string" indexed="true" stored="true"/> <field name="lily.vtag" type="string" indexed="true" stored="true"/> <field name="lily.version" type="long" indexed="true" stored="true"/> <!-- Your own fields --> <field name="name" type="text" indexed="true" stored="true" required="false"/> <field name="kind" type="text" indexed="true" stored="true" required="false"/> <field name="coord" type="location" indexed="true" stored="true"/> <field name="addr" type="text" indexed="true" stored="true" required="false"/> </fields> </schema></pre> </li> <li>Creating an index-configuration and add that to lily<br> <pre><?xml version="1.0"?> <indexer xmlns: <records> <record matchNamespace="k" matchName="Placemark" matchVariant="*" vtags="last"/> </records> <fields> <field name="name" value="k:name"/> <field name="kind" value="k:kind"/> <field name="coord" value="k:coordinate"/> <field name="addr" value="k:address"/> </fields> </indexer></pre> </li> <li>Upload the records</li> <li>Enjoy the SOLR geo filtering results</li> </ol> <p align="center"> <table class="plainTable"> <tr> <td><a style="border: 1px" href="/blog/471-ot/version/default/part/ImageData/data/solr-spatial.png"><img alt="solr-spatial" title="solr-spatial" src="/blog/471-ot/version/default/part/ImagePreview/data"></a></td> </tr> <tr> <td style="text-align: center"><a style="font-style: italic" href="/blog/471-ot/version/default/part/ImageData/data/solr-spatial.png">Klik om te vergroten</a></td> </tr> </table> </p> <img src="" height="1" width="1" alt=""/> 1.0: Smart Data, at Scale, made Easytag:blog.outerthought.org,2008:Daisy468-ot <p xmlns: <em>We.</em> </p> <h3>What</h3> <p.</p> <p>Lily makes Big Data easy with a high-level, developer-friendly data model with rich types, versioning and schema management. Lily offers simple Java and REST APIs for creating, reading and managing data. Its flexible indexing mechanism supports interactive and batch-oriented index maintenance.</p> <p.</p> <p>Lily is dead serious about Scale. The Lily repository has been tested to scale beyond any common content repository technology out there, due to its inherently distributed architecture, providing economically affordable, robust, and high-performing data management services for any kind of enterprise application.</p> <h3>For whom</h3> <p.</p> <h3>Lily Enterprise</h3> <p>Lily Enterprise makes easy <em>easier</em>. Start using Lily with a turn-key technology adoption process featuring training, proof-of-concept consulting, mentoring, enterprise support and a host of enterprise add-on tools, such as cluster deployment tools, administrative user interface, and easy installation packages. <a xmlns:Lily Enterprise</a> is a subscription-based software and services offer available worldwide.</p> <h3>What’s next</h3> <p.</p> <h3>Early adopters and partners</h3> <p>Join the ranks of ADEO, the world's 4th DIY retail group that adopted Lily as the foundation of its next-generation e-commerce platform. Explore Lily together with Bonnier, a leading multinational publishing group. Lily runs great on the <a href="">Cloudera Distribution for Hadoop</a> (CDH) and even better on Cloudera Enterprise. Lily is certified CDH-compatible. Early implementation partners are Cronos Group (BE), SFEIR (F) and Infosys.</p> <h3>Thanks</h3> <p <a href="">Apache Software Foundation</a>. We're thankful for the developer communities working hard on these projects, and strive hard to contribute back where possible. We're also appreciative of the commercial service suppliers backing these projects: Lucid Imagination and Cloudera.</p> <h3>Where</h3> <p>Everything Lily can be found at <a href=""></a>. Enjoy!</p> <img src="" height="1" width="1" alt=""/> HBase Flushes And Compactionstag:blog.outerthought.org,2008:Daisy465-ot <p xmlns:I was looking into more detail at how HBase compactions work, and given my experience collecting metrics for <a xmlns:Lily</a>, and also inspired by <a href="">this blog post</a> on Lucene, I thought it would be nice to do some tests and make some graphs of the HBase flush and compact process.</p> <h2>Background</h2> <p>When something is written to HBase, it is first written to an in-memory store (<em>memstore</em>), once this memstore reaches a certain size, it is flushed to disk into a <em>store file</em> (everything is also written immediately to a log file for durability). The store files created on disk are immutable. Sometimes the store files are merged together, this is done by a process called <em>compaction</em>.</p> <p>This buffer-flush-merge strategy is a common pattern, for example also used by Lucene, and is described in a paper called the <a href="">Log-Structured Merge-Tree</a> (never read it though). In contrast to Lucene though, were one usually has only one IndexWriter, HBase typically has hundreds of regions open. </p> <p>There are two kinds of compactions:</p> <ul> <li> <p>the <em>minor compactions</em>: these are triggered each time a memstore is flushed, and will merge some of the store files, determined by an algorithm described below.</p> </li> <li> <p>the <em>major compactions</em>: these run about every 24 hours (after the currently oldest store file was written), and merge together all store files into one. The 24 hours is adjusted with a random margin of up to 20% to avoid many major compactions happening at the same time. Major compactions can also be triggered manually, via the API or the shell.</p> </li> </ul> <p.</p> <p>If, after a compaction, a newly written store file is greater than a certain size (default 256 MB, see property hbase.hregion.max.filesize), the region will be split into two new regions.</p> <h2>The basic compaction process</h2> <p). </p> <p>The main goal here is to illustrate how the minor compaction process decides when and what to merge.</p> <p align="center"> <img alt="Flush & compactions: default scenario" title="Flush & compactions: default scenario" src="/blog/458-ot/version/default/part/ImageData/data/threshold3.png"></p> <p.</p> <p>The second compaction is only performed after 4 store files are written. How does HBase decide this?</p> <p>The algorithm is basically as follows:</p> <ol> <li> <p>Run over the set of all store files, from oldest to youngest</p> </li> <li> <p>If there are more than 3 (hbase.hstore.compactionThreshold) store files left and the current store file is 20% larger then the sum of all younger store files, and it is larger than the memstore flush size, then we go on to the next, younger, store file and repeat step 2.</p> </li> <li> <p>Once one of the conditions in step two is not valid anymore, the store files from the current one to the youngest one are the ones that will be merged together. If there are less than the compactionThreshold, no merge will be performed. There is also a limit which prevents more than 10 (hbase.hstore.compaction.max) store files to be merged in one compaction.</p> </li> </ol> <p>If you need more detail, have a look at the source of the Store.compact() method.</p> <p>Now, with this knowledge, we can see why the second compaction does not run after flush 5: the oldest file was about ~240MB, the two younger ones together ~160MB, 240 > 160 * 1.2</p> .</p> <p>With the default configuration of HBase, if a store file would be 480MB, the region will be split. I have on purpose augmented the limit to illustrate what happens if there are more store files, though I could also have lowered the memstore flush size.</p> <p>If you wonder how the store file merging behaves over longer time, below is the result of a longer run with 157 flushes of 10 MB. Click on the image below to see it bigger (10000px by 800px).</p> <p align="center"> <a href="463-ot/version/1/part/ImageData/data"><img alt="Compactions: long scenario preview" title="Compactions: long scenario preview" src="/blog/464-ot/version/default/part/ImageData/data/compactions_long_scenario_preview.png"></a> </p> <p <a href="">bloomfilters</a> or by specifying <a href="">timestamp ranges</a>).</p> <p>The number 7 might make you think of the property hbase.hstore.blockingStoreFiles, which has a default value of 7, but I augmented it for this test to be sure it did not have any influence.</p> <h2>Compactions and deletes</h2> <p>When you perform a delete in HBase, nothing gets deleted immediately, rather a delete marker (a.k.a. thombstone) is written. This is because HBase does not modify files once they are written.</p> <p>The deletes are processed during the major compaction process, at which point the data they hide and the delete marker itself will not be present in the merged file.</p> <p.</p> <p align="center"> <img alt="Flush & compactions: put and delete scenario" title="Flush & compactions: put and delete scenario" src="/blog/459-ot/version/default/part/ImageData/data/puts_and_deletes.png"></p> <p>What we see is:</p> <ul> <li> <p>the memstore grows and flushes three times, three store files are created</p> </li> <li> <p>after the third store file is written, a compaction is performed</p> </li> <li> <p>the result of the compaction is a new store file of size 0.</p> </li> </ul> <p>This is a surprising result: only major compactions process deletes, and major compactions supposedly only run every 24 hours.</p> <p.</p> <p>Besides explicit deletes, there are other cases where store files will shrink after a major compaction: cells that are removed because there are more than max-versions versions of it, or when using the TTL feature.</p> <h2>Multiple column families</h2> <p>Each column family has its own memstore and its own set of store files. But all the column families within a table stick together. They will all flush their memstore at the same time (this <a href="">might change</a>). They are also splitted in the same regions, so when one of the column families grows to large, the other ones, how small they might be, will also split.</p> <p>The illustration below shows a scenario where a table with two column families is used. In family 2, we only do a put for every 10 puts we do in family 1. So family 1 will grow much faster than family 2 (family 2 is sparse family).</p> <p align="center"> <img alt="Flush & compactions: two column families" title="Flush & compactions: two column families" src="/blog/460-ot/version/default/part/ImageData/data/two_families.png"></p> <p>The memstore and storefile count graphs show the data for both families counted together. Note how at each memstore flush, the number of store files increases with two.</p> <p>You can also see how a second compaction is performed for family 2 but not for family 1. This is because all store files in family 2 are smaller than the memstore flush size of 100 MB.</p> <h2>Multiple regions</h2> <p>Now lets do a scenario with a table that has multiple regions.</p> <p>For this test, a table was created with 10 initials regions, divided so that random UUIDs would be evenly spread over these regions. This time the memstore flush size was set to 30 MB.</p> <p.</p> <p.</p> <p align="center"> <img alt="Flushes & compactions: multiple regions" title="Flushes & compactions: multiple regions" src="/blog/461-ot/version/default/part/ImageData/data/10regions.png"></p> <h2>Memstore upperLimit</h2> <p>All the above illustrations were quite synthetic. On a real system, there will often be much more regions, and more than one table, and there will often not be enough memory to let memory stores grow to their configured flush size. </p> <p).</p> <p).</p> <p>And, hurary huray, the theory is confirmed by the plot below.</p> <p align="center"> <img alt="Flushes: upperLimit reached first" title="Flushes: upperLimit reached first" src="/blog/462-ot/version/default/part/ImageData/data/upperlimitfirst.png"></p> <p>Some final notes:</p> <ul> <li>during flushes & compactions, HBase keeps processing put and get requests, always giving a consistent view of the data</li> <li>certain properties, like the flush size, can be configured on the level of the table</li> </ul> <p.</p> <img src="" height="1" width="1" alt=""/> 0.3 - the Valentine release!tag:blog.outerthought.org,2008:Daisy457-ot <p xmlns:What better fitting way to celebrate Valentine than with a nice flower? Here's a new and beautiful Lily for you!</p> <p>This release is the result of 3 months of hard work since Lily 0.2 last October. Our focus was stabilization, performance and robustness, providing a platform we can continue building upon. More than 50 tickets were resolved during this development sprint, and we're slowly readying ourselves for the 1.0 release. Lily 0.3 brings many gradual improvements over Lily 0.2. It has various important performance improvements, a more solid implementation of the blob fields, automatic retry of operations that fail due to IO exceptions (between Lily client and Lily server), and other miscellaneous improvements.</p> <p>Lily 0.3 also is the result of a lengthy proof-of-concept project for our first paying Lily customer, who stressed the importance of performance, robustness and flexibility. The resulting, large improvements on the tester tool are all part of the Lily source tree now, for everybody's benefit.</p> <p>In the mean time, we're plugging Lily everywhere, and with great success. We're also slowly <a xmlns:disclosing</a> the Lily future roadmap - Smart Data at Scale - where Lily will be the first (and only) data repository tightly integrating scalable storage, robust indexing, flexible searching, real-time usage analytics and built-in Data Insights, all from a single open source product to be installed on your infrastructure or hosted in the cloud.</p> <p>Everything Lily can be found at <a href=""></a>. We're also sharing the details of our commercial software subscription service with select prospects, let us know if you're interested!</p> <p>Here's a concise list of improvements since Lily 0.2:</p> <h4>Repository</h4> <ul id="dsy457-ot_internal-source-marker_0.842651566490531"> <ul> <li>Performance / space improvements</li> <ul> <li>Shorter column key encoding (field id's)</li> <li>Reduction of number of column families used</li> <li>Avoid duplicate values in the table: make use of sparseness of the table </li> <li>Drop the use of HBase rowlocks, which do not survive region splits/moves. </li> <li>Use byte[] as keys in RecordType FieldType cache</li> </ul> <li>API</li> <ul> <li>Added a new method createOrUpdate which creates or updates a record depending on whether it already exists. This new method has the advantage over the create method that it can be retried in case of IO exceptions, i.e. it is idempotent, similar to PUT in HTTP/REST.</li> <li>Allow updating versioned-mutable fields without specifying the record type. </li> <li>Throw a RecordLockedException instead of generic exception when a record is locked, this allows Lily clients to retry the operation in that case.</li> </ul> <li>Clear historical data when deleting a record and remove any referenced blobs.</li> <li>The link index stores record IDs and field IDs as bytes instead of strings. </li> <li>The record ID string representation was changed to use comma instead of semicolon to separate variant properties, since the use of semicolons was problematic in the JAX-RS based REST interface implementation.</li> </ul> </ul> <h4>Upgrade to Apache HBase 0.90</h4> <h4>Blobs</h4> <ul> <ul> <li>Rework blobstore functionality</li> <ul> <li>Blobs can only be accessed through the record they are used in, not directly by using their blob key. This is to allow for future record-level access control.</li> <li>Introduce a Repository.getBlob() method, which returns a BlobAccess object, which provides access to the blob meta data (Blob object) and the blob input stream. This avoids the need to read the record in case you need the blob metadata.</li> <li>Uploaded blobs which are never used in a record are cleaned up.</li> </ul> <li>The HDFS-stored blobs are stored in a hierarchical structure.</li> </ul> </ul> <h4>RowLog improvements</h4> <ul> <ul> <li>Performance improvements</li> <ul> <li>the RowLog processor uses a Zookeeper based notification system instead of Netty based.</li> <li>Optimize queue scanning: avoid scanning over deleted rows in the table, fix too-frequent scanning, fix endless scanning loop on startup in case of no repository activity.</li> <li>The RowLog processor only processes messages of a minimal age (avoid conflicts with direct processing of wal messages).</li> </ul> <li>Extended RowLogConfigurationManager to add/update rowlog configuration information.</li> <li>Avoid and remove stale messages in the queue.</li> <li>Allow the rowlog to either use row-level locks (wal use case) or executionstate-level locks per subscription (mq use case) when processing messages.</li> <li>Added a WAL processor which handles open WAL messages.</li> </ul> </ul> <h4>REST interface</h4> <ul> <ul> <li>Adapted blob-support to new blobstore functionality. Content-Length header is now set when downloading blobs. Multi-value or hierarchical blobs are now accessible.</li> <li>Support updating versioned-mutable fields.</li> <li>Fixed various smaller bugs reported by users.</li> </ul> </ul> <h4>HBase index library</h4> <ul> <ul> <li>Allow to add/remove multiple entries in one call.</li> <li>Performance</li> <ul> <li>Fixed important performance issue whereby row scanning always ran to the end of the index table.</li> <li>Enable scan caching.</li> <li>Added a performance testing tool.</li> </ul> </ul> </ul> <h4>Indexer</h4> <ul> <ul> <li>Upgrade to Tika 0.8</li> <li>Performance</li> <ul> <li>Avoid FieldNotFoundException when evaluating field values</li> </ul> <li>the SOLR request-writer and response-parser implementation configurable. This allows to use the XML format instead of the javabin format.</li> </ul> </ul> <h4>LilyClient</h4> <ul> <ul> <li>Automatically retry operations on IOExceptions, this allows operations to survive node failures.</li> <li>Automatic balancing over all Lily nodes. Each method called on the Repository object will automatically be performed on an arbitrarily selected Lily node.</li> <li>Avro: switch from HTTP to Netty transport. For this, upgraded to an Avro 1.5 snapshot with patch AVRO-747.</li> </ul> </ul> <h4>Tester tool</h4> <ul> <ul> <li>Allows to configure test scenarios and indexer and solr configuration.</li> <li>Has extended logging, metrics and metrics plotting (gnuplot integration) capabilities allowing for performance evaluations.</li> <li>Introduces general performance testing library.</li> </ul> </ul> <h4>Lily server process</h4> <ul> <ul> <li>Abilitly to create tables with multiple initial regions at first cluster startup (record table, linkindex, blobincubator, ...). Also allows to set the max file size and the memstore flush size.</li> <li>The initial Lily startup can now be performed on multiple nodes concurrently, previously this failed because the table creation code did not handle failures in case of concurrent table creation.</li> <li>Configuration files changed so that they allow for inheritance (= fallback from one conf dir to another, to the built-in conf). Include default configuration in Kauri-module jars. All this will help in maintaining Lily configuration across Lily versions.</li> </ul> </ul> <p>We hope you'll enjoy this new Lily as much as we did making it. Let us know how we're doing!</p> <img src="" height="1" width="1" alt=""/>'s in store for 2011?tag:blog.outerthought.org,2008:Daisy456-ot <p xmlns:As we're gently spinning down for Christmas and Year's End parties, it's time to take a quick peek at what we have in store for next year.</p> <p <a xmlns:our UStream show page</a>. We aren't done yet, if you have some time tomorrow tune in between 12AM and 1PM Belgian Time.</p> <p>We're planning to release a new beta of Lily somewhere end of January introducing a number of performance enhancements we're currently researching with the nice (hardware) assistance of the <a href="">Sizing Servers lab of HOWEST</a>. I'll be giving a NOSQL intro presentation during <a href="">YaJUG's inaugural NOSQL User Group</a> meeting that month as well.</p> <p.</p> <p.</p> <p>In the mean time, we're working on some proof-of-concept Lily projects for customers, putting Lily through its paces and see how well it performs. Needless to say, we're thankful and thrilled to have these early adopters on board.</p> <p>On the Daisy side, projects are doing well, we just signed up a new customer who's going to manage medico-operational care procedures for a Dutch oncology center.</p> <p>We'll be merrily continuing our open source product activities in 2011, with some other exciting announcements ahead of us. The entire Outerthought team wishes you a great Christmas season, and see you on the other side!</p> <img src="" height="1" width="1" alt=""/> Devoxx 2010tag:blog.outerthought.org,2008:Daisy454-ot <p xmlns:Last week Antwerp (<a xmlns:devoxx</a>).</p> <p>Sure enough there is side-tracks and comments on how Oracle is translating its "ownership" into "stewardship", but mostly the conference is just about the techy stuff, some showing off, and quite some well-deserved awe.</p> <p>We got the floor for two sessions during the conference focussing more on the REST (<a href="">kauri</a>) side of our activities. For those who missed the slides or want to rehash them, see below. <br> <a href="">contemplate about this wonder at least once a week</a>. Joking aside, "the wonder view" serves as my motivation for advocating REST as in "going with the web grain": follow the techniques for making your web application an integral part of this link-in wonder, rather then a stand-alone island in this digital universe.</p> <p>Overall it was great to see how much air-time (too much <a href="">according to some</a>) this conference has been giving to REST. Mostly thanks to the great presentations of <a href="">Paul Sandoz</a> on Jax-RS and <a href="">the plans for 2.0</a>. Other important 'trend' to watch was the obvious attention to the BigData/Cloud/NoSQL track. Credits to the fine line-up of speakers there of course.</p> <p>My two biggest takeaways of the week finally: "Java Modules" and "CDI" (and how they relate to the future of kauri) deserve their own blogposts. (promise!) </p> <p>Here are the slides from the talks we gave:</p> <ul> <li>"Lab" Session (3h) on restfull programming in Java</li> </ul> <div style="width:425px" id="dsy452-ot___ss_5899588"> <strong style="display:block;margin:12px 0 4px"><a href="" title="Devoxx 2010 | LAB : ReST in Java">Devoxx 2010 | LAB : ReST in Java</a></strong><object id="dsy452-ot___sse5899588" width="425" height="355"><param name="movie" value=""><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"> <embed name="__sse5899588" src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed> </object><div style="padding:5px 0 12px">View more <a href="">presentations</a> from <a href="">Outerthought</a>.</div> </div> <ul> <li>"Tools in Action" Session (30') on Kauri and Lily as the groundwork for web-scale applications</li> </ul> <div style="width:425px" id="dsy453-ot___ss_5902665"> <strong style="display:block;margin:12px 0 4px"><a href="" title="Devoxx 2010 | Tools In Action : Kauri and Lily">Devoxx 2010 | Tools In Action : Kauri and Lily</a></strong><object id="dsy453-ot___sse5902665" width="425" height="355"><param name="movie" value=""><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"> <embed name="__sse5902665" src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed> </object><div style="padding:5px 0 12px">View more <a href="">presentations</a> from <a href="">Outerthought</a>.</div> </div> <img src="" height="1" width="1" alt=""/> : A message queue system on top of HBasetag:blog.outerthought.org,2008:Daisy449-ot <h1 xmlns: <strong>Rowlog : A message queue system on top of HBase</strong> </h1> <h2> <strong>The need for a MQ</strong> </h2> <p>In our Lily content repository project (cfr <a xmlns:</a>), each time we update (create, update, delete) a record we want to update a SOLR-based index. To accomplish this we need a message queue system (MQ) that delivers messages about updates on records to an indexer component which updates the SOLR index.<br> The MQ needs to comply to a few requirements:</p> <ul> <li>The context of the messages are events that happen on Lily records</li> <li>Messages can be delivered in an asynchronous way to the indexing component </li> <li>Messages about a specific record should be delivered in-order</li> <li>No two messages of a same record can be consumed by the indexer component at the same time</li> <li>A message consumer should be able to retrieve all oustanding messages related to a record</li> <li>There can be no message loss</li> </ul> <h2> <strong>Why build our own?</strong> </h2> <p>MQ systems already exist in many flavors and implementations like for instance RabbitMQ, ActiveMQ, etc. Still we decided to build our own system on top of HBase. <br> First of all we want to keep the amount of different components and storage technologies (e.g. MySQL) co-existing in the Lily space as low as possible since each new technology adds an extra level of complexity with respect to configuration, administration, deployment etc. <br> Secondly we want all components of Lily to behave the same with respect to scalability (partitioning), failover, reliablity (replication). Since we were already using HBase that has our desired scalabiliy properties we decided to use the same technology to build a MQ system.</p> <h2> <strong>A MQ on HBase named 'Rowlog'</strong> </h2> <p>Until now this blog has been talking about updates and events that apply to Lily records. But in fact we have built an MQ system that is usable outside the context of Lily. The context of the messages are events that happen on a HBase row. That is also where the name "Rowlog" comes from.</p> <h3> <strong>Subscriptions</strong> </h3> <p>Each client interested in processing or consuming messages should register a subscription on the rowlog. In case of Lily this is the indexer updating the SOLR index, but this could just as well be an e-mail notification client or anything else. <br> A message will then be offered to each registered subscription for consumption by one of its listeners.</p> <h3> <strong>Message Queue Table</strong> </h3> <p>Each message is stored in a message table (which is stored in a HBase table). The key of the message contains a subscription id, a timestamp of when the event happened and the rowkey of the row the message is about. <br> A Rowlog processor will regularly scan the message table and process the messages. The messages are sorted based on their timestamp. They will therefore be processed in the order the events happened, even across different rows.</p> <p align="center"> <img alt="MessageQueueTable" title="MessageQueueTable" src="/blog/450-ot/version/default/part/ImageData/data/MessageQueueTable.png"></p> <h3> <strong>Row-local Queue</strong> </h3> <p>Next to the message queue table, there is also the concept of a row-local queue. In a row-local queue we keep information about events on a row in messages that are stored on the same row where the message is about, but in a column family separate from the actual data. <br> Doing this gives us a few advantages:</p> <ul> <li>Adding a message can happen in the same atomic put operation as updating the data itself (thereby avoiding the need for transactions).</li> <li>All outstanding messages of a row can easily be retrieved. In the message queue table the messages of one row are interleaved with the messages of other rows.</li> <li>All message information is available next to the data. If the message queue table would be lost it can be rebuild based on the row-local queue. (This is more a hypothetical advantage since we don't expect to be loosing the message queue table.)</li> </ul> <p>The information stored in the row-local queue is an execution state for each subscription (executed or not) and a payload (extra information about the event that happened). By storing this information here, the messages stored in the message queue table can be kept very light-weight.</p> <p align="center"> <img alt="RowLocalQueue" title="RowLocalQueue" src="/blog/451-ot/version/default/part/ImageData/data/RowLocalQueue.png"></p> <h2> <strong>Write-Ahead Log (WAL)</strong> </h2> <p>The message queue is not the only reason why we came up with the rowlog solution. <br> At the same time we also needed a solution to be able to execute actions as a consequence of an update on a record, i.e. 'secondary actions'. The requirements for these actions were :</p> <ul> <li>Guaranteed, eventual execution (cfr no message loss)</li> <li>Preferably synchronous execution (can't be fulfilled in case of failures)ability to resume in case of failures (e.g. a node crash after an update but before a secondary action got executed)</li> <li>Secondary actions should be able to see the state of the record corresponding to the update. Therefore, secondary actions should be executed before the next update on the record happens.</li> <li>Ordered execution of multiple secondary actions following the same update </li> </ul> <p>The above requirements don't completely apply to what is usually understood under a write-ahead log. For instance, we don't need are transactions across multiple updates on multiple rows. But we stick with the name.</p> <h3> <strong>Rowlog as a solution for the WAL</strong> </h3> <p>While designing a solution for the WAL we noticed that we ended up with something that was very similar to our MQ solution and that in fact we could distill the same solution for both use cases : the "Rowlog".</p> <p>For a more technical explanation of the Rowlog, it's architecture and how to use it, take a look <a href="">here</a>. </p> <img src="" height="1" width="1" alt=""/> for the weekend: Lily 0.2 is OUT !tag:blog.outerthought.org,2008:Daisy446-ot <p xmlns:Three.</p> <h3>For whom</h3> <p.</p> <h3>Foundations</h3> <p>Lily builds further upon <a xmlns:Apache HBase</a> and <a href="">Apache SOLR</a>. HBase is a faithful implementation of the <a href="">Google BigTable</a>.</p> <h3>Key features of this release</h3> <ul> <li>Fully distributed: Lily has a fully-distributed architecture making maximum use of all available hardware for scalability and availability. ZooKeeper is used for distributed process coordination, configuration and locking. Index maintenance is based on an HBase-backed RowLog mechanism allowing fast but reliable updating of SOLR indexes.</li> <li>Index maintenance: Lily offers all the features and functionality of SOLR, but makes index maintenance a breeze, both for interactive as-you-go updating and MapReduce-based full index rebuilds</li> <li>Multi-indexers: for high-load situations, multiple indexers can work in parallel and talk to a sharded SOLR setup</li> <li>REST interface: a flexible and platform-neutral access method for all Lily operations using HTTP and JSON</li> <li>Improved content model: we added URI as a base Lily type as a (small) indication of our interest in semantic technology</li> </ul> <p.</p> <h3>From where</h3> <p>Download Lily from <a href=""></a>. Open source, Apache license, no strings attached.</p> <h3>Enterprise support</h3> <p>Together with this release, we're rolling out our <a href="">commercial support services</a> (and signed up a first customer, yay!) that allows you to use Lily with peace of mind. Also, this release has been fully tested and depends on the latest <a href="">Cloudera Distribution for Hadoop</a> (CDH3 beta3) - Cloudera being the leading Hadoop enterprise services provider. We're proud to collaborate with a true market leader here.</p> <h3>Next up</h3> <p.</p> <h3>Follow us</h3> <p>If you want to keep track of Lily's on-going development, join the Lily discussion list or follow our company Twitter <a href="">@outerthought</a>.</p> <h3>Thank you</h3> <p>I'd like to thank Bruno and Evert for their hard work so far, the Flemish IWT government fund for their partial financial support, and all of our early Lily adopters and enthusiasts for their much valued feedback. You guys rock!</p> <img src="" height="1" width="1" alt=""/> is coming! Come and see us!tag:blog.outerthought.org,2008:Daisy443-ot <p xmlns:In just under three weeks from now, <a xmlns:Europe's largest Java-fest</a> is happening again, with <em>loads</em> of cool things happening in or around Metropolis in Antwerp. We've been helping with organizing this year's edition, we'll be there, in full force, and we'd love to meet you in Belgium's second nicest city (Ghent coming first of course ;-) November 15-19. Here's what we contributed to Devoxx' ninth edition!</p> <h3>The NoSQL/Cloud track</h3> <a href="" title="IMG_5991 by JoséPaumard, on Flickr"><img src="" width="500" height="333" alt="IMG_5991"></a> <p>It's no secret that NoSQL and Cloud technology, with a good dash of Devops tactics, is this year's Devoxx key theme. As a matter of fact, I've been asked to join <a href="">the Devoxx steering group</a> specifically for this purpose, reaching out to some great BigData speakers all around the globe, and have been plugging this 'conference-inside-the-conference' at various other events, like in the picture above from <a href="">ParisJUG</a> in September.</p> <a href="" title="My Devoxx Schedule by stevenn, on Flickr"><img src="" width="500" height="303" alt="My Devoxx Schedule"></a> <p>As you can see from my own personal agenda, Devoxx will be <em>very busy</em> - attending all sessions related to NoSQL, Cloud and Devops will already be a full-time task on its own. We have 3h university sessions on Cassandra, HBase, MongoDB and Hadoop, and 45' conference sessions on both these products plus Voldemort (from LinkedIn) and Mahout, and great case-studies from Twitter, Facebook and Adobe. That's <strong>Big</strong>Data Adobe, not Flex/AIR. ;)</p> <p>To top this all off, I'll be co-hosting <a href="">a NoSQL BOF</a> meeting Thursday night between 9 and 10PM (yes, sessions run <em>that</em> late during Devoxx).</p> <h3>RESTy stuff</h3> <p>On the Kauri/REST/Java side of things, we haven't been sitting around idle as well. Marc will be presenting <a href="">a 'Tools In Action' talk on Kauri and Lily</a> Tuesday afternoon, before co-hosting the REST BOF that evening. But the most important news is that Marc will be presenting <a href="">a Hands-on Lab on RESTful, Kauri-based development</a> Tuesday morning. People who've been subject to Marc's tutoring in the past know that this kind of hands-on sessions are his favorite pet peeve, so I can only strongly advise you to join that Lab: it will be great!</p> <h3>Be there!</h3> <p>Devoxx <em>will</em> be selling out, this week if not sooner. So if you haven't booked your passes yet, better now than sorry. See you in Antwerp!</p> <img src="" height="1" width="1" alt=""/> countdown for Lily 0.2tag:blog.outerthought.org,2008:Daisy440-ot <p xmlns:Next week, it's final countdown for Lily 0.2, which for all imaginable reasons is a pre-qualifier for 1.0 soon after that. Our primary focus for this important 0.2 release is two-fold: full distributability and developer contracts. That means we're trying to stabilize APIs and data/disk formats so that devs can safely start playing with Lily with the assurance that upgrading to 1.0-final will be as easy as possible. In the mean time, it's crunch time around Lily, tying up various loose bits, testing the robustness in case of node failures, some performance and load testing (tweaking of which will be the primary focus for 1.0), and making sure everything is well documented.</p> <p>There's a small sample application showing loading and indexing of mail archives (mbox) into Lily which you'll find in the Lily source tree, and I made a little screencast of that.</p> <embed src="" type="application/x-shockwave-flash" width="480" height="330" allowscriptaccess="always" allowfullscreen="true"></embed> <p>Overall, Lily is in good shape for this next release, and we are really excited of the reactions we got so far. So keep your browsers ready, we're shooting for 0.2 next week on Friday, or the Monday after that (because that's how it goes, no?)</p> <img src="" height="1" width="1" alt=""/> 2.4 is out, and it's worth the wait!tag:blog.outerthought.org,2008:Daisy439-ot <p xmlns:This is bound to end up being the largest product release announcement we've ever written, as it's the result of both fortunate and unfortunate circumstances. First, the good news: we've been <em>very</em> busy in the last 15 months, working both on our new product Lily, but also adding new features and improving the already rich feature set of Daisy.</p> <p>People who have been in touch with us during trade shows or events over the past year heard the story already: we're focusing Daisy onto the wonderful world of techdoc, internal collaborative document/book authoring and legal/QDoc publishing, with sophisticated document models and a feature set to match that. </p> <p>The bad news is that it took us 15 months to release this new version, but I can honestly testify that it's entirely worth the wait. Daisy 2.4 is better than ever, with a new build system, new features and new developer conveniencing, and we're very proud to release it today. So without further ado, I'll pass the mic to Karel, who has been shepherding this new Daisy release for a long time now, and who will introduce you to <em>all things new</em> in Daisy 2.4.</p> <p>Thanks for all the hard work that went into this release!</p> <p>Steven.</p> <h2>Main features</h2> <h3>Point in time (<a xmlns:docs</a>)</h3> <p>Go back in time and pick an arbitrary date: we'll show you the matching versions of your content and even better: We allow you to search and navigate facets in the complete corpus back into time. This is a feature you can't find elsewhere in the open source CMS market.</p> <h3>Replication service (<a href="/daisy-docs-current/652-daisy">docs</a>)</h3> <p>Handle higher loads and fail-safe setups through replication between multiple repository instances in master-slave mode.</p> <h3>Simpler repository installation</h3> <p> <em>Keep enjoying that next installation of Daisy. </em> </p> <p>Up to Daisy 2.3, the installation script would ask you a lot of questions without giving the possibility to change your answers without starting over. Now the installation process is driven by a configuration file: you start with a template installation file. Easy!</p> <h3>Inline editing (<a href="/daisy-docs-current/623-daisy">docs</a>)</h3> <p>Customize the editing environment to match the presentation layout.</p> <p>Your users can now edit the content in the familiar layout of your site. The tabbed paradigm is still the default, but can easily be modified into a true inline editing environment.</p> <h3>Single sign-on (<a href="/daisy-docs-current/636-daisy">docs</a>) and account manager support (<a href="">link</a>)</h3> <p>Skip the login page! Yay! Finally!</p> <ul> <li>Use Kerberos authentication (Windows or other ), or</li> <li>Plug in your own authentication scheme, or</li> <li>Use "Account Manager", an Online Identity project by the Mozilla Labs people - for now, only an Firefox add-on with a <a href="">prototype implementation</a> exists, but as the spec gains attention, more implementations should arise.</li> </ul> <h3>Updating authentication schemes (<a href="/daisy-docs-current/639-daisy">docs</a>)</h3> <p>Keep your Daisy user data in sync with your own backend (e.g. LDAP or your own)</p> <h3>Document task improvements</h3> <p>Better leverage your document handling batch processes</p> <ul> <li>We've added a 'retry count' to tasks. This overcomes failed tasks due to document locks or other temporary situations, and gives them possibly another run later on.</li> <li>Document tasks now survive server restarts</li> <li>Restarting document tasks is made much easier</li> <li>Adding custom document tasks (Java) as part of your customization-project is made a lot easier.</li> </ul> <h2>Developer features</h2> <p> <em>Because happy developers are effective developers.</em> </p> <h3>Maven 2 build system</h3> <p>We switched from maven to Maven 2 for building Daisy.</p> <h3>Maven 2 plugin & sample-project archetype (<a href="/daisy-docs-current/654-daisy">docs</a>)</h3> <p>We don't just use Maven 2 for building Daisy, but for projects <strong>using</strong> Daisy. The daisy-maven-plugin allows this to be done in a very efficient and professional manner.</p> <p>Using the sample-project archetype, you can give your Daisy project the best start it can get, for the complete dev team, in no time! </p> <p>During your project customization project we offer the flexibility to switch and test various Daisy versions (which is important for facing the cutting edge challenges of working on top of Daisy trunk, but also could be useful in longer-term projects)</p> <h3>Spring context component</h3> <p>A wrapper which lets you use the popular Spring framework for developing your own wiki extensions, rather than the less-well known/used Avalon framework that Cocoon provides.</p> <h3>Context doc in search page</h3> <p>The query search page lets you set a context document. This makes it easier to test queries using the ContextDoc() function. </p> <h3>Custom Lucene analyzers</h3> <p>Optimize the full-text indexing process for your content using a custom index analyzer and get better full-text search results by using custom query analyzers. (e.g. handling custom synonym lists)</p> <h2>Convenience upgrades and fixes</h2> <h3>Important libary upgrades</h3> <ul> <li>FOP 1.0 (from 0.95)</li> <li>JQuery 1.4.2 (from 1.2.6)</li> <li>Lucene 3.0.1 (from 2.2.0)</li> </ul> <h3>Conditional namespaces (<a href="/daisy-docs-current/337-daisy">docs</a>) </h3> <p>A Daisy repository can now manage multiple namespaces and decide in which namespace each document should go. Playing with multiple content repositories and reshuffling their content over time was never easier.</p> <h3>Configuration</h3> <p>Various changes making configuration easier and more flexible.</p> <h3>Version mode cookie</h3> <p>By storing the version mode in a cookie, guests can also benefit from the version mode and point in time features across your customizations</p> <h3>Document browser</h3> <p>This was introduced in 2.3, and got some usability fixes and general attention.</p> <h3>Publisher: custom link annotation</h3> <p>In the advanced section: publisher requests now support adding custom link-annotation metadata (available to the layout styling) based on value-expressions.</p> <h2>Summary</h2> <p>We realize there has been an exceptional long time lapse between Daisy 2.4 and the previous 2.3 release, but we are confident this exhaustive feature-list makes up for your wait. </p> <p>Obviously the Point-in-Time support makes us specially proud. Again Daisy sets itself apart from the CMS-pack with a new compelling feature.</p> <p>Adding this to a growing differentiator list from previous releases (remember Books, document tasks, workflow,...) makes for more persuasive argumentation to envy both end-users and project-customers. And delivering on the promises should be a breeze with the added developer support.</p> <p>As always, there's our Daisy mailing list which gets your questions answered, and our professional services you can tap into if you want your project to be done with Daisy by its makers.</p> <p>May all your Daisy projects be merry, and enjoy this new release!</p> <p>Go and get the good stuff at <a href=""></a>.</p> <img src="" height="1" width="1" alt=""/> season: NoSQL and REST ahoy!tag:blog.outerthought.org,2008:Daisy437-ot <p xmlns:Conference season is heating up rapidly in the next few weeks. Or rather, it seems like <em>we're onto something</em> with this NoSQL/HBase/SOLR/BigData thingy, to the extent that all the pieces of the puzzle are falling together quite nicely. Hurray!</p> <p>Next Monday, I'll be (very briefly) presenting Lily to the <a xmlns:Bay Area HBase MeetUp group</a>, who has temporarily moved places to New York for the occasion of <a href="">Hadoop World 2010</a>, the (now yearly) Cloudera/Hadoop lovefest. Not only that, I'll finally get to meet all those great folks that make the HBase-clock tick, something which puts a really big smile on my face. I have a couple of more business-like meetings scheduled as well, so things will be pretty busy.</p> <p>Tuesday, I have the cumbersome challenge of choosing between all those Hadoop World conference sessions and absorb as much info as possible to relay to my colleagues at Outerthought HQ. Even though it's my first stay in NYC, I doubt there will be much time for touristy things. Oh well, such is life.</p> <p>The weeks thereafter, leading up to the end of October, it's Lily release crunch time again, preparing a decent set of release info materials and making sure all the right channels are properly informed. That, and continuing work on the Lily partnership model, convincing fellow techy folks about the value-add Lily can provide to their business.</p> <p>Mid November, during Devoxx, it's the NoSQL bandwagon ride again, but we're topping this off with something <em>hot off the presses</em>: a Lab session on RESTful development with Java, combining the power of REST design patterns, Java and Kauri in a 3 hour hands-on mega-exercise for Devoxx University attendees. So if you happen to attend Devoxx during University days and want to get a <em>proper</em> introduction into REST and Kauri, join Marc for <a href="">RESTful development with Java</a>. People who have heard Marc presenting before, know that such training sessions are his favorite pastime, so I'm sure you'll be in for a great ride.</p> <img src="" height="1" width="1" alt=""/>
http://feeds.feedburner.com/Outerthought
CC-MAIN-2017-13
refinedweb
13,762
53
Setting up The Folder Structure of ObjectScript Code For InterSystems Package Manager Hi Developers! When you prepare your modules for ZPM (InterSystems Package Manager) it expects the certain directory structure for ObjectScript source files. ObjectScript in your source folder need to be stored by types in the following subfolders. E.g. if you have the source folder named as /src the structure should be as follows: /src /cls - for classes /inc - for include files /mac - for mac files /int - for interpretable files /gbl - for globals And the ObjectScript should be in CLS (a.k.a UDL) and not in XML. Example. Ok! But how could you setup it for your current ObjectScript packages? Manually? Never! There are at least 2 ways to manage this. 1. Use isc-dev module Import isc-dev module via ZPM as: zpm:USER>install isc-dev Or import the release into the namespace. Setup the workdir for isc-dev: USER>Do ##class(dev.code).workdir("/yoursourcedir") USER>Do ##class(dev.code).export() It will export all the source code in CLS into "/yoursourcedir" folder and will create proper folders structure with file types and packages. 2. Another way to do the proper export is to use VSCode ObjectScript 1. Open the folder with your project where your want to export sources. 2. Create the source folder, .e.g. /src 3. Put the src folder in VSCode settings.json and add "objectscript.export.addCategory": true, and "objectscript.export.folder": "src" into the settings. E.g. here is the example of settings.json file: "objectscript.conn.active": true, "objectscript.conn.version": 3, "objectscript.conn.ns": "USER", "objectscript.conn.port": 52773, "objectscript.export.addCategory": true, "objectscript.export.folder": "src" After that open InterSystems ObjectScript section in VSCode, find the package you want to export or all of them and click Export:
https://community.intersystems.com/post/setting-folder-structure-objectscript-code-intersystems-package-manager
CC-MAIN-2021-04
refinedweb
303
61.12
Search the regex that fits all querying strings. Project description Search the regex that fits all querying strings. Dozens of pre-written regexes are indexed and organized as a partial order, available in regexorder/templates.json. The regex of all the querying strings' least upper bound in the partial order is returned. templates.svgplots the partial order. The core part is the pre-written regexes and their respective structure. Currently they only cover the most common cases. - Any idea or contribution is highly welcome. Reference This library is part of the implementation for our research paper to be submitted. Installation This package is available on PyPI. Just use pip3 install -U RegexOrder to install it. Our regexes utilize some advanced Unicode features, that are not available in standard re library yet. Thus, the more advanced regex library must be used to match our regexes. Examples from regexorder import RegexOrder r = RegexOrder() t = r.match("123") t.name # 'pos_int' t.regex # '\\+?\\d+' t = r.matchall(["apple", "banana", "cheese cake"]) t.name # 'lower_words' t.regex # '\\p{Ll}+(\\s+\\p{Ll}+)*' Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/RegexOrder/
CC-MAIN-2019-47
refinedweb
205
70.39
Specification link: 14.1 References linking-refs-205-t ← index → linking-uri-03-t Tests that values for the xlink role and arcrole attributes are stored in the DOM. The test is passed if the raster image and the vector image both have dark green and light green borders, same as the reference image. The values for role and arcrole are based on the RDDL specifications of well known link natures (role) and well known link purposes (arcrole). Roles uses the namespace URI (for XML content types) or the canonical IANA URI of the media type registration (for non-XML content). A uDOM script reads the values of the xlink role and arcrole attributes, checks that they are the correct values, and sets the fill colour of some rectangles from shades of red (meaning incorrect) to shades of green (meaning correct).
http://www.w3.org/Graphics/SVG/Test/20080912/htmlObjectHarness/linking-refs-206-t.html
CC-MAIN-2016-07
refinedweb
141
65.86
In file included from netwm.h:37:0, from netwm.cpp:31: netwm_def.h:284:4: error: expected ‘}’ before ‘::’ token netwm_def.h:284:24: error: invalid use of ‘::’ netwm_def.h:285:13: error: ISO C++ forbids initialization of member ‘Toolbar’ netwm_def.h:285:13: error: making ‘Toolbar’ static netwm_def.h:285:13: error: ISO C++ forbids in-class initialization of non-const static member ‘Toolbar’ netwm_def.h:285:13: error: invalid conversion from ‘int’ to ‘NET::WindowType’ ... - Aug 30 2011 g++ -c -pipe -fPIC -O2 -Wall -W -D_REENTRANT -DLONG64 -DQT_NO_DEBUG -DQT_QT3SUPPORT_LIB -DQT3_SUPPORT /Qt3Support -I/usr/include/qt4 -I. -I../kernel -I../diagram -I.. -I.moc -I.ui -o .obj/main.o main.cpp In file included from main.cpp:22:0: MainWindow.h:49:5: error: 'auto_ptr' in namespace 'std' does not name a type make[1]: *** [.obj/main.o] Error 1 ---------- g++ -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/lto-wrapper Target: x86_64) --------- what is wrong with that auto_ptr? - Aug 30 2011 While original wicd manager (gnome version) has labeled buttons, and a multi-line row for each station (some kind of usual interface for gnome user, inspired by firefox multi-lists, I suppose), kde version (this one, wicd-kde) however does not follow "gnome standard" and does not have multi-lined station row nor labeled actions in it. From other hand, wicd-kde does not follow "kde standard" approach to display status and actions (for example I have N stations scanned, but wicd-kde window layout has always N+1 disconnect buttons). I think that wicd is a good software, but if wicd-kde tend to follow KDE usability approach, it is better to display things in a way that usual KDE user is awaiting from his/her KDE desktop (e.g. in KDE-ish way), so eye will not cry when a numerous "action" buttons change their status according to available action. In KDE environment this looks like a misproper functional overhead which does not relate to real network interface state. I mean that indeed a network interface can be connected and disconnected, with a station as configuration parameter (ssid). But wicd-kde shows instead that station can be connected/disconnected, and these actions are self-contained (independent from each other), so "in KDE words" this looks like I can connect them all (or several), but this is not true. If this is a KDE app, why it can not be usual to KDE user? - Aug 09 2011 I have in left pane (at top) two buttons with "unclear" function - it seems that there are thing to cleanup and add more shine inside. Why not to just place this app in personal package archive (PPA) at ubuntu's launchpad service? So with this users can simply install from it and even update regularly... - Jun 22 2011 The idea is very good, this thing is very usable and still very easy to use. I hope you correct it a bit... Have a nice day! :) - Jan 26 2011 Amarok 2.x Scripts by Manolob 5 comments Plasma 4 Extensions by mbleichner 72 comments I have several monitors and on some of them red/green balls look identically, so I probably can say that it looks like a form of daltonism. Pluses and minuses are very clear to see, and the idea of coloring their state changes can be accommodated on background of (+) and (-) - Nov 09 2010 Graphic Apps by kleag 35 comments Plasma 4 Extensions by mbleichner
https://www.pling.com/u/molostoff/
CC-MAIN-2020-50
refinedweb
591
62.58
Hi, I have a Pythonscript which transforms input featureclass and tables into several output tables and one featureclass. The output tables are connected to the featureclass and to each other with relationship classes (everything in one single GDB). For avoiding nested loops, i initially put the input data into pythonic lists ("data" in the code). I use ArcGIS 10.3.1, Python 2.7.8, here's the code (nothing special): def insertRows(workspace, fields, data): edit.startOperation() with arcpy.da.InsertCursor(workspace, fields) as cursor: for row in data: try: cursor.insertRow(row) except: err = "" for elm in row: err = err + str(elm) + "|" arcpy.AddError("Error at row: " + err) arcpy.AddError(sys.exc_info()[0]) edit.stopOperation() Stacktrace: Traceback (most recent call last): File "XX.py", line 600, in <module> insertRows(xGDB + os.sep + "BP_Plan", fields_BP_Plan, dict_BP_Plan) File "XX.py", line 255, in insertRows cursor.insertRow(row) RuntimeError: Feld kann nicht bearbeitet werden. # Field is not editable Filling the tables with more than 8000 rows is no problem, but the code breaks exactly on inserting record #1000 into output featureclass. The row data itself has no problem (when I switch inputdata's OID sort direction, it also breaks on record #1000). The list objects are also filled. Maybe there are some known limitations on editsessions when many relationship classes are involved. I would appreciate any hints. hi, I just solved the problem by using the with statement before calling the function insertRows: it seems, that the construct with startEditing/startOperation is only working up to 1000 records. Thanks for your help anyway
https://community.esri.com/thread/169204
CC-MAIN-2019-18
refinedweb
262
60.72
The Question is: Hello! I use "sys$create_galaxy_lock_table" for creating lock table on one galaxy instance. For map this lock table on another instance, i use the same function and same parameters for this function. If i run my program on first and second instance under equal u ser (e.g. Ant and Ant),then table lock created on first instance successfuly mapped in second instance. If i run my program on first and second instance under different user (e.g. Ant and Boris in different group),then table lock created on first instance don't mapped in second instance, and system create the own table lock. Both instance share UAF information. What can i make, so that on second instance my lock table mapped without dependency from user who create this table on another instance. This strings from my code (i based on CGU$BALANCER example) /* Get the size of a Galaxy lock */ status = sys$get_galaxy_lock_size(&min_size,&max_size); if (_failed(status)) { printf("Error sys$get_galaxy_lock_size\n"); return (status); } status = sys$create_galaxy_lock_table("TEST_GLOCK_TB",PSL$C_USER, PAGESIZE,GLCKTBL$C_PROCESS,0,min_size,&glock_table_handle); Thank you in advance. Anton Yelin The Answer is : By default, lock resource names are specific to the UIC group. Locks specified as system-wide locks are not specific to the UIC group.
http://h71000.www7.hp.com/wizard/wiz_7123.html
CC-MAIN-2015-11
refinedweb
214
55.44
I think moving to blueprint is great particularly if the r4.2 spec release is imminent. It seems like it should be getting close since it has moved to "public draft" recently, but I am not sure if there is an ETA. I'm sure someone here is plugged in to that process ;-) Chris -- Chris Custine FUSESource :: My Blog :: Apache ServiceMix :: Apache Directory Server :: 2009/4/28 Richard S. Hall <heavy@ungoverned.org> > Well, if you are going to switch, now seems like the time. > > -> richard > > > On 4/28/09 9:45 AM, Guillaume Nodet wrote: > >> The past days, I've been working on the blueprint implementation >> inside Geronimo [1]. >> The spec is still being written so the implementation is not really >> stable and is still missing a lot of features. >> However, it's already somewhat usable and as I've hacked Karaf to >> start using blueprint instead of spring-dm in a branch [2]. >> Tests do not even compile, but I've been able to start the console, so >> I thought I would talk about it a bit. >> >> This raises the question whether we want to switch to blueprint >> instead of spring-dm. >> I think we should, and even have to, given that Spring-DM will switch >> to support Blueprint at some point in the future too. Also the >> blueprint spec is way better than spring-dm wrt to namespace handlers >> (that are considered dependencies, so we would not have problems with >> namespace handlers not being available when a bundle is started) and >> classloading (i think classes loaded for namespace handlers will be >> loaded from the namespace handler bundle, thus freeing the bundle to >> import all the namespace handlers packages), though those areas are in >> flux. >> >> If so, we might even want to do that before renaming the packages, as >> the patch is quite big and would be quite broken after the rename imho >> ... >> >> As for tests, we'd have to switch to something else, which could be >> junit4osgi from iPojo or pax-exam for example. >> >> Feedback welcome. >> >> [1] >> [2] >> >> >> >> >
http://mail-archives.apache.org/mod_mbox/felix-dev/200904.mbox/%3C43b026c70904290915w38740f7bg19a15958874a3e8d@mail.gmail.com%3E
CC-MAIN-2018-13
refinedweb
341
65.05
There are many situations where we find that our code runs too slow and we don’t know the apparent reason. For such situations it comes very handy to use the python cProfile module. The module enables us to see the time individual steps in our code take, as well as the number of times certain functions are being called. In the following paragraphs, I will explore it’s capabilities a bit more. However first let’s remember the quote by Donald Knuth: “premature optimization is the root of all evil (or at least most of it) in programming”. So make sure that you don’t start optimizing before you even have a working code! In many cases you will not be able to determine the bottlenecks beforehand and might spend a lot of extra effort in the wrong places. Profiling with cProfile The easiest way of using the cProfile module from within a Python script can look as follows import cProfile pr = cProfile.Profile() pr.enable() call_function() pr.disable() pr.print_stats(sort='time') In the code we create a Profile object and enable it, then execute the code that is of interest to us, disable the profiling and view the results.
https://blog.alookanalytics.com/2017/03/
CC-MAIN-2018-51
refinedweb
202
60.45
Just. The only example apps that seems to work are the ones for the SD card. Anyone shed some light on this? Thanks Dan Just. Hi, if you can share the error log and more details, it will be easy to look up the problem. Hi, Thanks for the response. After further investigation I see that there is no on-board LED on the Maixduino Board. I used the TX-Led on port 1 to verify the app was running. I also see that there is a CH552 uP which provides 2 channel USB capability; and that one of the channels is connected to the ESP8266. I still don’t know how to connect the ESP serial to the K210 Serial port 1 to enable WiFi with the K210. There must be some way to disable the 8266 to the USB and allow the K210 to gain access to it. I haven’t figured it out yet. As far as the OV2640 is concerned, I get the following errors. Maybe it’s using the wrong library. Anyway, lot’s of issues to be worked out. Still researching… Again, Thanks Dan $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ errors follow $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ selfie:7:15: error: cannot declare variable ‘camera’ to be of abstract type ‘Sipeed_OV2640’ Sipeed_OV2640 camera(FRAMESIZE_QVGA, PIXFORMAT_RGB565); ^~ In file included\Sipeed_OV2640\src/Sipeed_OV2640.h:36:7: note: because the following virtual functions are pure within ‘Sipeed_OV2640’: class Sipeed_OV2640 : public Camera{ ^ ~~ In file included from C:\Users\dpcon\AppData\Local\Arduino15\packages\Maixduino\hardware\k210\0.3.11\libraries\Sipeed_OV2640\src/Sipeed_OV2640.h:4,\Camera\src/Camera.h:79:18: note: ‘virtual void Camera::setRotation(uint8_t)’ virtual void setRotation(uint8_t rotation) = 0; ^ Multiple libraries were found for “Adafruit_GFX.h” Used: C:\Users\dpcon\Documents\Arduino\libraries\Adafruit_GFX_Library Not used: C:\Users\dpcon\AppData\Local\Arduino15\packages\Maixduino\hardware\k210\0.3.11\libraries\Adafruit-GFX-Library exit status 1 cannot declare variable ‘camera’ to be of abstract type ‘Sipeed_OV2640’ Thanks for the replay, which blink app you used ? can you share the code. The blink app is in the Maixduino examples under “ticker” #include <Arduino.h> #include <Ticker.h> // attach a LED to pPIO 13 #define LED_PIN 13 Ticker blinker(TIMER0); Ticker toggler(TIMER1); Ticker changer(TIMER2); float blinkerPace = 0.1; //seconds const float togglePeriod = 5; //seconds void change() { blinkerPace = 0.5; } void blink() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } void toggle() { static bool isBlinking = false; if (isBlinking) { blinker.detach(); isBlinking = false; } else { blinker.attach(blinkerPace, blink); isBlinking = true; } digitalWrite(LED_PIN, LOW); //make sure LED on on after toggling (pin LOW = led ON) } void setup() { pinMode(LED_PIN, OUTPUT); toggler.attach(togglePeriod, toggle); changer.once(30, change); } void loop() { } You can also just write out to the Serial() port. There’s an LED on that pin also. Writing to Serial1 doesn’t blink anything. I have MaixDuino (2626), and examples in python language work, especially the camera works. However, this is not the case with the arduino-ide example in cpp: selfie.ino. Procedure int Sipeed_OV2640::sensor_snapshot( ){ g_dvp_finish_flag = 0; uint32_t start = millis(); while (g_dvp_finish_flag == 0) { usleep(50); if(millis() - start > 300) return -1; } return reverse_u32pixel((uint32_t*)_dataBuffer, _width*_height/2); } returns minus one, which is why image pointer *img of selfie.ino is NULL. As the internet shows, i am not the only one with this problem.
https://forum.seeedstudio.com/t/maixduino-ai-dev-board/7670
CC-MAIN-2020-29
refinedweb
546
59.09
File Specific word wrap (vs. global enable) - Dan Rozwood last edited by Is it possible to get a setting that allows word wrap to only wrap a single file? Here and there I find that I don’t CARE what is on the end of a long line of code, except in a file where I am validating a line. Selecting this ON makes ALL files word wrap, which for all the files that I do NOT care to see wrapped lines of code I have to deselect word wrap. Not a big deal, I should probably just set a keyboard shortcut, but I thought I would ask to see if there is any interest in adding this. Maybe it would become part of the right click menu for the file tab? This way you can easily tell the difference between word wrap for JUST a file and word wrap (global). Thanks for an awesome app! Hello Dan-Rozwood , if you want a semiautomated way doing it you can use python script plugin and this script # this is the callback function which get called def npp_callback_BUFFERACTIVATED(args): # check if the current document should be wrapped if editor.getProperty(args['bufferID']) == '1': editor.setWrapMode(1) else: editor.setWrapMode(0) # to prevent multiple callback registration per editor set a variable if editor.getProperty('callback_already_set') != '1': editor.setProperty('callback_already_set', '1') # this registers the callback function notepad.callback(npp_callback_BUFFERACTIVATED, [NOTIFICATION.BUFFERACTIVATED ]) else: # if run the second time callback gets cleared notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED]) editor.setProperty('callback_already_set', '0') # get bufferid from current document current_bufferID = str(notepad.getCurrentBufferID()) if editor.getProperty(current_bufferID) != '1': editor.setProperty(current_bufferID, '1') editor.setWrapMode(1) else: editor.setProperty(current_bufferID, '0') editor.setWrapMode(0) and if you modify the contextMenu.xml you can have the script listed in the mouse right click conext menu. I just added the line <Item PluginEntryName=“Python Script” PluginCommandItemName=“file_word_wrap” /> at the end of the file. file_word_wrap is the name of the python script I created you can choose what ever you want. What does this script? It registers a callback function which gets called everytime you either open a new document or switch between documents. Then it checks if the current document, identified by its bufferID, is one which should get wordwrap enabled or not. The bufferID is retrieved when you execute the script and here there is a little drawback. If you want to have it set for multiple (but of course not all) files you need to run the script for every document. Which means you register multiple callbacks for the same purpose as each document gets an unique editor assigned. If you want to delete the wordwrap on a document, just run the script a second time. Cheers Claudia Hi Dan , and Claudia, Up to now, the individual properties, memorized by Notepad++, in the Session.xml configuration file, for each file and each view, are the following : - File firstVisibleLine - xOffset - scrollWidth - startPos - endPos - selMode - lang - encoding - filename - backupFilePath - originalFileLastModifTimestamp So, Claudia, your Python script, seems valuable, to customize N++, for some other properties, than Word Wrap, which can, only, be set for all the opened files. I thinking of : The show symbols The line numbers margin The bookmark margin The vertical edge line The smart highlighting The zoom level The text direction … So, I’m wondering, if these properties could be set, as the Word Wrap one, individually, for few opened files, only ? For instance, the Python script command, for displaying the line numbers margin, should be : Notepad.menuCommand(MENUCOMMAND.VIEW_LINENUMBER) Not sure, Claudia, that is the exact syntax, anyway !! Best Regards, guy038 Hi guy038, I disagree, the script is a global word wrap hack, correct, but it does what it was asking for. If you run this script on the opened document, only this document has the word wrap done. The other documents stay without having the word wrap done. It cannot be saved, not in the current state of it version, to survive a restart of npp but I can think of possible solutions to overcome this as well. Something like - create a file and store the status of the files which should have the word wrap - in startup.py, run code to load that file on npp startup. Just out of my mind, nothing tested but I strongly believe that it could be done. Cheers Claudia Hi guy038, I missed this one So, I’m wondering, if these properties could be set, as the Word Wrap one, individually, for few opened files, only ? Yes, I assume this can be done. Let me check it and do some tests. and in regards to Notepad.menuCommand(MENUCOMMAND.VIEW_LINENUMBER) yes, only change first letter to be lowercase. notepad.menuCommand(MENUCOMMAND.VIEW_LINENUMBER) then it will work. ;-) Cheers Claudia Btw. don’t know if you celebrate christmas, if so merry christmas ;-) Hi Claudia, I’ve already understood, as you clearly explained, that your script : allows to set the Word Wrap feature, for the current file A allows to reset the Word Wrap feature for the same current file A, by running file_word_Wrap, a second time So, in my previous post, I shouldn’t have spoken about the Session.xml file, which stores some parameters, for each file of a session, for the next sessions to come. This behaviour is quite different from your script’s behaviour, of course and my post was a bit confusing :-( However, I do think that your script could be useful for other properties than the Word Wrap one ! For instance, before sending a new post, I, generally, write it, first, in a text file, with N++. For these different text files, I usually don’t need the Line Numbers margin. So, it would be interesting, from time to time, to display the line numbers for one/two specific file(s), only :-) Cheers, guy038 P.S. : I think that we replied to each other, simultaneously ! Thanks for your correction. And I’m rather glad for getting my first right command, in the Python Script help file ! Have a look, again, at my post below. I added, in post-scriptum, the main differences between an Encoding and a Converting N++ action : Hi guy038, thanks for the hint to the updated encoding thread. Hard work done ;-) Regarding the line number, book mark, folding columns I did some test and discovered a slight inconsistency here. Assuming you have checked - display line number - display bookmark - display folding (doesn’t exist, I know you are aware, it’s just for completeness and should mean is visible) you can hide bookmark and folding columns for different documents but you cannot hide line number column. There is a flickering so I assumed that either npp or a plugin checked the visibility state of that column. I started notepad with only python script plugin and issue still existed, so, I guess it’s npp itself. OK, this means we need to revert the conditions and assume nothing has been checked and the script makes it visibile on demand. This works - no problem, as long as you do not switch between tabs to fast. I will see what else can be made and will come back on this. Cheers Claudia Hi guy038, here are some methods you were thinking about. Show Symbols - editor.setViewWS(1) # 0 to hide - editor.setViewEOL(1) # 0 to hide Margins (scintilla supports up to 5, npp uses only three 0, 1, 2) line numbers editor.setMarginWidthN(0, 38) # standard value bookmark margin editor.setMarginWidthN(1, 14) # standard value folding margin editor.setMarginWidthN(2, 14) # standard value First parameter is the margin id (0,1,2) and second parameter means width in pixel. A second parameter being 0 hides the margin line numbers editor.setMarginWidthN(0, 0) bookmark margin editor.setMarginWidthN(1, 0) folding margin editor.setMarginWidthN(2, 0) Show Vertical edge line notepad.menuCommand(MENUCOMMAND.VIEW_EDGELINE) # MENUCOMMAND.VIEW_EDGENONE to hide Zoom level editor.setZoom(+5) A positive number to increase font size, a negativ to decrease or 0 to reset to standard Text direction notepad.menuCommand(MENUCOMMAND.RTL) # or MENUCOMMAND.LTR (left-to-right) Indentation Guides editor.setIndentationGuides(1) # 0 to hide I didn’t found a MENUCOMMAND equivalent for smart highlighting, maybe this hasn’t been ported. A more generic version of the script. def func2call(i): if i == 1: editor.setWrapMode(0) editor.setMarginWidthN(0,0) editor.setMarginWidthN(1,0) editor.setMarginWidthN(2,0) editor.setViewWS(0) editor.setViewEOL(0) editor.setIndentationGuides(0) editor.setZoom(0) notepad.menuCommand(MENUCOMMAND.VIEW_EDGENONE) notepad.menuCommand(MENUCOMMAND.EDIT_LTR) else: editor.setWrapMode(1) # activate word wrap editor.setMarginWidthN(0,38) # show line number column editor.setMarginWidthN(1,14) # show bookmark column editor.setMarginWidthN(2,14) # show folding column # editor.setMarginWidthN(3,0) # not used or usage not found yet # editor.setMarginWidthN(4,0) # not used or usage not found yet editor.setViewWS(1) # show whitespaces editor.setViewEOL(1) # show end of line chars editor.setIndentationGuides(1) # show indention guides editor.setZoom(+5) # ZOOM notepad.menuCommand(MENUCOMMAND.VIEW_EDGELINE) # show edge line notepad.menuCommand(MENUCOMMAND.EDIT_RTL) # text right to left def npp_callback_BUFFERACTIVATED(args): if editor.getProperty(args['bufferID']) == '1': func2call(0) else: func2call(1) if editor.getProperty('callback_already_set') != '1': notepad.callback(npp_callback_BUFFERACTIVATED, [NOTIFICATION.BUFFERACTIVATED ]) editor.setProperty('callback_already_set', '1') else: notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED]) editor.setProperty('callback_already_set', '0') current_bufferID = str(notepad.getCurrentBufferID()) if editor.getProperty(current_bufferID) != '1': editor.setProperty(current_bufferID, '1') func2call(0) else: editor.setProperty(current_bufferID, '0') func2call(1) The margin columns seem to be special cases. One issue I had when trying to hide the line column even when setting to display has been enabled and another one is the folding column. It reapears if pixel width is set to 0 by switching to different document. Hmm … ??? Assume that both are handled by npp and/or lexer as well. Will see if I can work around. Cheers Claudia Hi Claudia, I’ve just installed the Python Script plugin, on the last v6.8.8 version and I tested your script, choosing successively a particular property : It worked nice ! Of course, we get, from time to time, some weird effects. One example : I previously changed your script, in order to ONLY use the Word Wrap feature ( I put the other lines in comments ) I suppose that the Word wrap is UNSET, on starting N++, and that it contains four opened tabs Select tab #2 and run your script, then select tab #4 and run your script again. Well, if you select from tab #1 to #4, tabs #2 and #4 have the property Word wrap ENABLED and tabs #1 and #3 DON’T. Logical ! Then, click again on tab #2 and run your script => all the tabs seem to have the Word Wrap DISABLED ? Finally, click, a last time, on tab #2 and run your script => Again the tab #2 ( as well as tab #4 !! ) have, again, the property Word Wrap ENABLED :-)) There are some other cases like that. However, Claudia, it doesn’t matter. The main fact is that a displaying property, which is managed, on the whole, by N++, for all the opened files, can be set, with a Python script, individually, for 1 or few files ONLY :-)) This valuable script may be useful, from time to time. Many thanks, for your “Python” work ! Cheers, guy038 Hi guy038, your welcome but you are right, strange, need to dig deeper to see what happens there. Let’s see if we find the bug ;-) Cheers Claudia - Claudia Frank last edited by Claudia Frank Hello guy038, I guess I found the problem and a work around because I’m not 100% convinced of this solution. I did some additional console.write statement wihtin the code and found out, that the notepad callback needs to be set once only. Indeed it was the source of the problem as it seems that it has confused the python script plugin. So what needs to be done is to comment (or delete) the following lines # if editor.getProperty('callback_already_set') != '1': # editor.setProperty('callback_already_set', '1') # notepad.callback (npp_callback_BUFFERACTIVATED, [NOTIFICATION.BUFFERACTIVATED ]) # console.write('{0}\n'.format('callback registered')) # else: # notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED]) # editor.setProperty('callback_already_set', '0') # console.write('{0}\n'.format('callback deleted')) and add the line before or afterwards the commented block. notepad.callback (npp_callback_BUFFERACTIVATED, [NOTIFICATION.BUFFERACTIVATED ]) The changes do have a drawback so, it means that the script doesn’t do the clearcallback anymore. Not sure if this is an issue but if so, you can always run notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED]) from python script console or restart npp. ;-) Cheers Claudia Hi Claudia, I tested your changed script. It woks great, indeed ! Referring to my last try, each time I ran this new version of your script, the state of the word wrap option, for the current file was changed into the opposite state, even, when using two simultaneous views ! And, when running the command, below : notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED]) In the Python console, I noticed that it sets the Word wrap state of the current document of each view, to all the opened documents of that associated view ! Of course, after using the Python script, you can’t, seriously, rely on the visual appearance, of the Word Wrap button and/or the v indication, in menu View - Word wrap, as well as a click action, on this button/option ! Just remember to use the Claudia script, exclusively, to get the right state of the Word Wrap ( or an other property ! ) that you want, for the current document ! Thanks again, Claudia, for that nice Notepad++'s improvement ! Cheers, guy038 P.S : However, there’s, still, a limitation. For instance, if your create two ( almost ) identical scripts : The first one, to modify a displaying property of the current document The second one, to modify an OTHER property, of the current document The python script get confused and the properties can’t be set, simultaneously. Rather normal, however. We just have to be aware about this fact ! - Scott Sumner last edited by @Claudia-Frank 's FIRST Pythonscript in this thread really shines if the Wrap status is added to the status bar using the technique shown in the following thread:. In that thread, the read-only status of the current file is shown (based upon a script in yet-another thread…sorry), but that can be modified to show the wrap status as follows: Change line_col_sel_info_for_sb = 'Ln : {user_line} Col : {user_col} Sel : {sel} {ro}r'.format( user_line=curr_line+1, user_col=curr_col+1, sel=sel_part, ro='+' if editor.getReadOnly() else '-' ) to line_col_sel_info_for_sb = 'Ln : {user_line} Col : {user_col} Sel : {sel} {w}'.format( user_line=curr_line+1, user_col=curr_col+1, sel=sel_part, w='W' if editor.getWrapMode() == 1 else '' # show 'W' in status bar if wrap mode is on for this file ) Scott, don’t dig to deep to find my all of my youthful follies. ;-) Cheers Claudia - Scott Sumner last edited by Yea, I can tell that is earlier code from you, but it works! - Clyfton In last edited by I know this topic old but I tried the referenced solution and could not get it to work. I went to PLUGINS > PYTHON SCRIPT > NEW SCRIPT and saved the example code as file_word_wrap. When I go to PLUGINS > PYTHON SCRIPT > SCRIPTS and click on file_word_wrap I get error: AN EXCEPTION OCCURRED DUE TO PLUGIN: PYTHONSCRIPT.DLL EXCEPTION REASON: ACCESS VIOLATION I also added … <Item PluginEntryName=“Python Script” PluginCommandItemName=“file_word_wrap” /> … at the bottom of contextMenu.xml as instructed but did not see it as a right-click option.
https://community.notepad-plus-plus.org/topic/10985/file-specific-word-wrap-vs-global-enable
CC-MAIN-2020-10
refinedweb
2,577
56.76
Wikiversity talk:Content development From Wikiversity Wikiversity:Project namespace talk page. (this is an open forum) [edit] About About links to every single page. It's in the center of the bottom line. Acknowledgement of the source at the lower right-hand corner might shift the focus toward MediaWiki. A quick glance at the lower left-hand corner shows the reason we look for results. Sensitivity to the other two members of the bottom line could increase the potential of the object at the upper left-hand corner. In every instance it's up to the person represented in the upper right-hand corner to control content development at this project. Follow me? CQ 11:32, 30 January 2007 (UTC)
http://en.wikiversity.org/wiki/Wikiversity_talk:Content_development
crawl-002
refinedweb
120
57.37
#include "HalideRuntime.h" Go to the source code of this file. Routines specific to the Halide Hexagon host-side runtime. Definition in file HalideRuntimeHexagonHost.h. Definition at line 19 of file HalideRuntimeHexagonHost.h. Definition at line 21 of file HalideRuntimeHexagonHost.h. Power modes for Hexagon. Definition at line 107 of file HalideRuntimeHexagonHost.h. Power modes for Hexagon. Definition at line 66 of file HalideRuntimeHexagonHost.h. Check if the Hexagon runtime (libhalide_hexagon_host.so) is available. If it is not, pipelines using Hexagon will fail. The device handle for Hexagon is simply a pointer and size, stored in the dev field of the halide_buffer_t. If the buffer is allocated in a particular way (ion_alloc), the buffer will be shared with Hexagon (not copied). The device field of the halide_buffer_t must be NULL when this routine is called. This call can fail due to running out of memory or being passed an invalid device handle. The device and host dirty bits are left unmodified. Disconnect this halide_buffer_t from the device handle it was previously wrapped around. Should only be called for a halide_buffer_t that halide_hexagon_wrap_device_handle was previously called on. Frees any storage associated with the binding of the halide_buffer_t and the device handle, but does not free the device handle. The device field of the halide_buffer_t will be NULL on return. Return the underlying device handle for a halide_buffer_t. If there is no device memory (dev field is NULL), this returns 0. Power HVX on and off. Calling a Halide pipeline will do this automatically on each pipeline invocation; however, it costs a small but possibly significant amount of time for short running pipelines. To avoid this cost, HVX can be powered on prior to running several pipelines, and powered off afterwards. If HVX is powered on, subsequent calls to power HVX on will be cheap. Set a performance target for Hexagon. Hexagon applications can vote for the performance levels they want, which may or may not be respected by Hexagon. Applications should be careful not to leave Hexagon in a high power state for too long. These functions can significantly increase standby power consumption. Use halide_hexagon_power_default to reset performance to the default power state. Set the default priority for Halide Hexagon user threads:
https://halide-lang.org/docs/_halide_runtime_hexagon_host_8h.html
CC-MAIN-2020-50
refinedweb
371
68.77
Pydia: A package installer for Pythonista - ProfSpaceCadet Pydia Installer.py: Source Code: your installer is a bit broken (missing imports, site-packages is nit a valid far name) also, PLEASE PLEASE do not import UIKit and import Foundation. First, you did not include these in your installer. Second, these are neither past nor future proof, as not everything steven aliased is available in older ios versions, or may be available in future versions. no try/except makes this very fragile code. If you really don't want to alias only the classes you need, at least use this, as it will work with every ios version that pythonista works on or will work on. from objc_util import * c= ObjCClass.get_names(prefix='UI')+ObjCClass.get_names(prefix='NS') for cls in c: if not cls.startswith('_'): try: globals()[cls]=ObjCClass(cls) except ValueError: pass it also seems as if the main script is not quite complete, at least as installed from the installer. Several imports don't work ( i think the direcotry structure was changed).. I can't wait to try this, the ui built from almost pure objc should be pretty interesting Here's a shorter method of loading all UI...classes into the global namespace, if you really want to do that (I find it a bit wasteful): from objc_util import ObjCClass globals().update({n: ObjCClass(n) for n in ObjCClass.get_names('UI')}) @JonB The startswith('_')check seems unnecessary, given that the class names are already filtered by prefix. Also, a ValueErrorshouldn't really happen because get_namesonly returns names of classes that actually exist.
https://forum.omz-software.com/topic/2876/pydia-a-package-installer-for-pythonista/?
CC-MAIN-2021-49
refinedweb
266
55.34
One of my biggest beefs about hMod was how it handled onChat. None of the plugins could interact with each other. Bukkit looks like it'll solve it sort of. Right now, you've got an event object that all plugin now interact with. Awesome since now people can edit the player and message object that's passed into it. That's~ about it though. We have an output message and a player object that I'm assuming will be formated as such: <player.getName> message Oh joys. 90% of plugins that hook onChat want to skin the entire message or at least, not edit that part of the message. That won't do. Bukkit is rather simple right now, inDev and all, but here's my take on it. My first idea was to have a global format string defined in the config and plugins can register their arguments into it. Adding a new plugin could mess up that order, and you don't want every bit of information flowing in for each line. Edit: Or do you? Now that I reflect on it a bit most things could get by with this. Still, you'd want some inGame editing to the order of things. Next up comes the method where you insert the format string in the event directly for plugins to interact with. Problem here is that each plugin would have to deal with a relative path. This would then force the admin to order the plugins (or at least their importance) carefully. You also still have to incorporate those would want to make channels, or only let select people view what he/she said. Truthfully, channels without client side work makes it crap, but we'll have to make do. Anyways, even if we pass a list of players for the plugins to decide what get's sent to who, we could still end up with plugins fighting over messages (the focus of a players output). The only way to fix that is to move all channel related stuff into the server itself (ahhhh fuck). Loathing as that might be, it's how most games work normally (but MC was never designed for bigness). You could also just leave it and either one focus based plugin or have channels need prefixed command calls instead (/talk #bukkit Blah blah blah / .local chat powah!). This is probably simplest since most of the smaller server's don't need channels. The alternative is that we just make a collossal mess of one chat plugin that does everything. __________________________ Now we come to the section where I post pointless code. PHP: // CraftBukkit start PlayerChatEvent event = new PlayerChatEvent(Type.PLAYER_CHAT, player, s, server.getOnlinePlayers()); server.getPluginManager().callEvent(event); s = MessageFormat.format(event.getFormat(), event.getFormatArgs()); for (Player receivingPlayer : event.getReceivingPlayers()) receivingPlayer.sendMessage(s); //s = (new StringBuilder()).append("<").append(event.getPlayer().getName()).append("> ").append(event.getMessage()).toString(); // CraftBukkit stop a.info(event.getLogString()); //d.f.a(new Packet3Chat(s)); PHP: public class PlayerChatEvent extends PlayerEvent implements Cancellable { private boolean cancel = false; private String message, format, logString; private List<Player> receivingPlayers; private ArrayList<String> formatArgs; public PlayerChatEvent(final Type type, final Player player, final String message) { super(type, player); this.message = message; } public PlayerChatEvent(final Type type, final Player player, final String message, Player[] receivingPlayers) { super(type, player); this.message = message; this.setLogString("<" + player.getName() + "> " + message); this.setReceivingPlayers(Arrays.asList(receivingPlayers)); this.addFormatArg(player.getName()); this.addFormatArg(message); this.format = "<{0}> {1}"; } PHP: // Plugin// Could also return the ChatCall instance as well.public void onChat(ChatCall cc) { // Simple message string replacement. cc.setMessage(cc.getMessage().replaceAll("monkeys", "gorrilas")); // Change the skin completely cc.setFormat("{0}: {1}"); // Insert a value into the format eg: "[HP: 20] Player: blarg" boolean result = cc.insertIntoFormat( cc.getFormat().indexOf("{0}"), "[HP: {"+cc.getNextFormatArgIndex()+"}] "); if (result) cc.addFormatArg((String)player.getHealth()); // Send to only allies (aka remove everyone else) for (int i = cc.getRecievers().size(); i >= 0; i--) { Player player = cc.getRecievers().get(i); if (!guildPluginVariableThingy.isAlly(cc.talker, player)) cc.removeReciever(i); } // Send to only allies (aka get online allies from plugin) cc.setRecievers(guildPluginVariableThingy.getOnlineAllies(cc.talker));} PS: I doubt that code is runnable. Disreguard the ChatCall class thing. I sketched up that code before I found the chat call in craftbucket and it's related event.
https://dl.bukkit.org/threads/chat.107/
CC-MAIN-2020-50
refinedweb
720
50.94
Hey, Jobs- to view all the spark jobs Stages- ...READ MORE Hi@akhtar Generally, Spark streaming is used for real time ...READ MORE package com.dataguise.test; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.spark.SparkContext; import org.apache.spark.SparkJobInfo; import ...READ MORE Option c) Mapr Jobs that are submitted READ MORE Comparison between Spark RDD vs DataFrame 1. Release ...READ MORE Some of the issues I have faced ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/41392/what-are-the-spark-job-and-spark-task-and-spark-staging
CC-MAIN-2022-21
refinedweb
106
55
26 April 2007 17:02 [Source: ICIS news] NEW DELHI (ICIS news)--?xml:namespace> ?xml:namespace> The group also reaffirmed its commitment to recently announced petrochemical projects. Reliance Life Sciences (RLS) said it has incorporated a subsidiary at The RCRS is expected to grow over the next few years through acquisitions, new services and improved technology platforms. RLS also announced that it had become limited partner in MPM BioVentures IV, the newest fund floated by MPM Capital, L.P, a US-based global investment management firm focused solely on healthcare investment business. BioVentures IV fund expected to invest in select emerging life sciences
http://www.icis.com/Articles/2007/04/26/9024290/indias-ril-unveils-new-business-initiatives.html
CC-MAIN-2015-22
refinedweb
103
55.03
Apriori Associative Learning Algorithm Reading time: 30 minutes | Coding time: 10 minutes Apriori Algorithm is a associative learning algorithm which is generally used in data mining. It follows the principle that people who bought this will also buy this. It analyzes the data present in database and extend the number of data items present in that record. It determines the certain amount of association rules which used to determine the trend in data and based on that data items are added or extended. Its most used case is Market Basket Analysis. It is beneficial for both customer and seller. It helps customer to buy thing and also increase the sales for seller. It also been used in health care for detection of adverse drug reaction. It also used in recommendation system as it learns from the trend according to user preference and recommend data based on that. To understand apriori we should understand the association rules. Association Rules As discussed above apriori define associative rules. Basis on which it performs its whole process. These rules are generally used to determine the relation between each data item present in database. - Let I={i1,i2,i3,…,in} are called items. - D={t1,t2,…,tn} are the transaction. Every transaction, ti in D has a unique transaction ID, and it consists of a subset of itemsets in I. An association rule can be intrepreted as A⟶B where A and B are subsets of I(X,Y⊆I), and they have no element in common which means both the events are mutually exclusive i.e., X∩Y = 0. Association rules generally tells the general trend in the database. The above data contain records which specifies the movies liked by each user. After analyzing data certain rules are determined. These rules states that if a person like movie 1 then it will also like movie 2. Same for the case movie 2 and movie 4. Apriori are used to determine these rules and extend the items in the individual records after analyzing from whole data. Association rules involves calculation of various constraints. Support It signifies amount of specific data appear in whole database records. In other words, how many times movie1 appears in other records too. Support for movie M will be: Support(M) = User Watchlist containing Movie M / Number of Movies in User Watchlist Using above example, support(movie1)= 5/6 = 0.8 It signifies that movie1 is liked by 80% of user Confidence It determines a relation between different items. Like referring above example, it signifies the liklihood of movie1 is liked while movie2 is also liked. Confidence of Movie M1 and M2: Confidence(M1-->M2) = User Watchlist containing Movie M1 and M2 / User watchlist containing Movie M1 Using above example, confidence(Movie1--->Movie2)= 4/6 = 0.6 This means 60% of users like both movie1 and movie2 Lift This signifies the likelihood of the movie1 being liked when movie2 is liked while taking into account the popularity of movie1. List of Movie M1 and M2 will be: Lift(M1-->M2) = Confidence(M1-->M2) / Support(M1) If value is greater than movie2 is oftenly liked by user if they liked movie1 Using above example lift(movie1--->movie2) = 0.8/0.6 = 1.3 Working of Apriori Algorithm It sets a minimum support and confident. A value is set based on which filtering of unnecessary data from dataset. Support and confident value of each data item should more than this minimum values It takes all subsets in transaction having higher support than minimum support. After comparing support and confident values of all data items, items whose values satisfy condition are stored in a location. It take all the rule of these subsets having higher confidence than minimum confidence. Association rules are applied on these data items and will extend items based on that rule It sort the rules by decreasing lift Go through this image to understand how Apriori - Associative Learning Algorithm works. We have explained it following the image. We will first create the frequency of all items present in dataset. We will set a minimum support value which means we will consider only those items which occur in more than 3 records. For this we determine the threshold support. And the support value of each item should be more than threshold value. After that we will make all the possible pairs of items without any repetition. We will create a frequency table of these pair and will only consider those pair whose support value is greater than threshold support. After that we will determine support and confidence of each pair and using the data we will add a item based on the trend in data. Implementation We will use a dataset which contains shopping list of various customer. The dataset contains record of different market items in basket of each customer. Each record specify the different items chosen by customers. Amount of items varies for each customer. We will try to find relation between items using apriori algorithm. We will load all the necessary libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd We will import the dataset and transform it into required form for training dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None) transactions = [] for i in range(0, 7501): transactions.append([str(dataset.values[i,j]) for j in range(0, 20)]) We will train our model for purpose from apyori import apriori rules = apriori(transactions, min_support = 0.003, min_confidence = 0.2, min_lift = 3, min_length = 2) Our results: Advantages - It is easy to implement and understand - It can be applied to large datasets Limitations - In some cases large number of rules are generated which makes the problem complex - Calculation of constraints is time cosuming and expensive as it have to go through whole dataset With this, you should have a good understanding of Apriori - Associative Learning Algorithm. Enjoy.
https://iq.opengenus.org/apriori-associative-learning/
CC-MAIN-2020-24
refinedweb
983
54.83
Accessing the LED flashlight Is it possible to access the LED flashlight of an iPhone using Pythonista? Sorry, this isn't possible. Not even with all your new ctypes tricks? Turning on and off the iPhone flashlight appears to be not many lines of Objective C. In particular, this codeor this codeseemed to be quite compact. @ccc That's a great idea! Just tried it out, and yes, this works (in the current beta): from ctypes import c_void_p, c_char_p, c_int, c_bool, cdll objc = cdll.LoadLibrary(None)) def toggle_flashlight(): AVCaptureDevice = cls('AVCaptureDevice') device = msg(AVCaptureDevice, c_void_p, 'defaultDeviceWithMediaType:', [c_void_p], nsstr('vide')) has_torch = msg(device, c_bool, 'hasTorch') if not has_torch: raise RuntimeError('Device has no flashlight') current_mode = msg(device, c_int, 'torchMode') mode = 1 if current_mode == 0 else 0 msg(device, None, 'lockForConfiguration:', [c_void_p], None) msg(device, None, 'setTorchMode:', [c_int], mode) msg(device, None, 'unlockForConfiguration') if __name__ == '__main__': toggle_flashlight() Thank you very much. I'll test it and will give feedback. May take some time though. Background on my app: I am currently writing an app which translates text to the NATO phonetic alphabet and also Morse code. The translated text is spoken by using the speech modul in several languages (works really well) and the Morse code of the translation shall be flashing on pushing a button. I'll also have predefined radio text and so on. ()```
https://forum.omz-software.com/topic/1554/accessing-the-led-flashlight
CC-MAIN-2022-27
refinedweb
224
55.13
It was always a 20th-century dream that there will be an era when every electrical apparatus at home will be controlled by a single click from any web enabled device, such as a PC, tablet, or smart TV, from everywhere. Τhis era has come, and today we will present you with a way to control any electrical device with a single click from any other device that has access to the web. We will use a spotlight as an example, but this could be easily substituted with a refrigerator, a washing machine, or an electric coffee pot, for example. We did one simplification, however, which is to electrify the spotlight with 12V DC instead of 220V AC current, primarily for safety reasons. We encourage the users of this guide to do the same, as it is very easy to expose oneself to hazardous electric shocks! The relay module we use with the ODROID-C2 in this project can easily be connected to a 220V power source, driving any electric device (up to 10A). Experienced users can try to work with these voltages, making sure to take all safety precautions. Let us delve into the endless potential of the ODROID-C2. Hardware requirements - ODROID-C2 () - 5V 1/2/4/8 Channel Relay Board Module ARM AVR DSP PIC () - Lamba JM/84211 3W 3000K 12V or any other compatible spotlight - Dupon wires female-to-female, male-to-male () - 4 X LS 14500 3.7V 2300mAh Li-ion batteries () Software requirements - Ubuntu 16.04 v2.0 from Hardkernel () - Python 2.3 or 3.3 preinstalled with Ubuntu - WiringPi Library for controlling the ODROID-C2 GPIO pins. You can learn how to install this at - CoffeeCup Free HTML Editor () - PuTTY * – We are going to need to be able to connect to our ODROID-C2 via SSH, and PuTTY is the perfect client to do this () - FileZilla – We are going to need a way to transfer files onto the ODROID-C2 using SFTP, which is FTP over SSH () Connecting it together The design of this project is very simple, and the Songle relay plays the most critical role. We have connected the GND of the Songle relay with the pin6 of ODROID-C2 (GND). The VCC pin of the relay is connected directly to pin2 of ODROID-C2, which provides 5V to this circuit and electrifies the electric coil of the relay). Finally, the INT1 pin of the relay is connected with pin7 of our ODROID, which is the pin that actually controls the relay, which is the ONs and OFFs of this device. From the other side of the Songle relay, there is a simple switch on which we have connected the spotlight through the battery or the mains. Please refer to the schematic in Figure 1 for a clear idea of this circuity. As a technical reference regarding the ODROID-C2 pins, we have used the excellent PIN Map provided by Hardkernel at. According to this map, pin2=5V, pin6=GND and pin7=GPIOX.BIT21 (General Purpose Input/Output Pin). All of the connections were made by using the Dupon female-to-female, male-to-male or male-to-female wires. Now that our hardware is ready, let us see how to build the software and bring it all together. Designing a simple web page We used the free CoffeeCup HTML editor to design a simple HTML web page for controlling the spotlight. On this page, we added the images of two buttons in order to control the spotlight, represented by the ON and the OFF buttons. Please refer to Figure 2 for a view of this page. The whole project is controlled by using a Web UI. In order to achieve this, we have hyperlinked those buttons to the relevant Python scripts songleon.py and songleoff.py that control the ON and OFF of the spotlight. Instructions on how to write those programs in Python are provided on the section called “Connecting the Application to the Web below. When you finally design your website, make sure that your home page is called index.php and not index.html, just to keep things uniform. However, we are only going to be using two PHP scripts, songleon.php and songleoff.php, to control the spotlight. The Python and PHP code we need to write is very simple and well documented. Installing the server In order to use the ODROID-C2 as a web server in this project, we have to install all of the necessary server software components. In addition, since we want a simple HTML server, we will install Apache with PHP (server-side scripting-language) support on the ODROID-C2. The following steps can be performed with PuTTY. Accessing the ODROID-C2 with this SSH client is well documented. All you need is the ODROID-C2’s IP address. Apache server software is the most widely used web server software today. Here’s how to install Apache with PHP support: odroid@odroid:~# sudo apt-get install apache2 php libapache2-mod-phpWhen prompted to continue, enter “y” for yes. Next, enable and start Apache: odroid@odroid:~# systemctl enable apache2 odroid@odroid:~# systemctl start apache2 odroid@odroid:~# systemctl status apache2 Test Apache Open your web browser and navigate to or. This is the address of your ODROID-C2 on your local network. You can find it by just typing: odroid@odroid:~# ifconfigYou will see a page similar to one shown in Figure 3. Test PHP To test PHP, create a sample testphp.php file in Apache document root folder: odroid@odroid:~# sudo nano /var/www/html/testphp.phpAdd the following lines and save the file: Restart the Apache service. $ sudo systemctl restart apache2Navigate to. It will display all the details about PHP such as, version, build date and commands, to name a few. Pleaser refer to Figure 4 below. Installing FTP Install an FTP server such as vsftpd using the following command: $ sudo apt-get install vsftpdEdit the FTP configuration file by typing: $ sudo nano /etc/vsftpd.confand make the the following changes: - Hit ctrl+W and search for anonymous_enable=YES, and change it to anonymous_enable=NO - Remove the # from in front of local_enable=YES - Remove the # from in front of write_enable=YES - Skip to the bottom of the file and add force_dot_files=YES - Hit ctrl+X to exit and enter y to save and hit to confirm: Then, restart vsftpd: $ sudo service vsftpd restart Publishing to the web By now, you should have a website that you can transfer over to the ODROID-C2. Once you have performed all the previous steps and have verified that you can view your website on another computer, we can move onto making the website turn ON our lamp using the 5V 1/2/4/8 Channel Relay Board Module ARM AVR DSP PIC. Inside your website directory, create a new PHP file called songleon.php containing the following code snippet, then save the file:Next, create a folder in the website directory called “scripts”, then create a subfolder inside it called “lights”, and inside there, create a new file called songleon.py. This will be the python script that turns our lamp on. Inside there, enter the following code, then save the file: import wiringpi2 as odroid odroid.wiringPiSetup() odroid.pinMode(7,1) odroid.digitalWrite(7,0)Go back to your web page in design/edit mode, and make sure the hyperlink for your “on” button links to the songleon.php. Now, when you click the button, the songleon.php script will execute the songleon.py python script, resulting in the lamp turning on. We are finally ready to make it turn off. Inside the website directory, create a new file called songleoff.php. Inside this, file enter the following code snippet, then save it: <!--?php system("echo odroid | sudo -S python /var/www/html/scripts/lights/songleoff.py"); header( 'Location: 'index.php' ) ; ?-->Again, make sure your file path is the same, so that this works. Also, set your redirection rules to redirect to the page of your choice. Then, make a new file in the scripts\lights\ folder called sognleoff.py. Inside this file, enter the following code, then save the file: import wiringpi2 as odroid odroid.wiringPiSetup() odroid.pinMode(7,1) odroid.digitalWrite(7,1)Add a hyperlink to songleoff.php to your “off” button, which should make your lamp turn off. You now have a website that can control your lights! Transfer to Apache It is very easy to login into your ODROID-C2 apache web server with Filezilla as soon as you know the ODROID-C2’s IP address. If you have previously logged in with SSH into your ODROID-C2 with PuTTY, you can find it out by typing: odroid@odroid:~# ifconfigYou have to give your name and password of “odroid” and “odroid”. You will be immediately taken to the ODROID-C2 root file system. From there, navigate to /var/www/html/ folder, and inside this directory, copy the files from your local drive to the above directory. Here are all the files and folders that you have to copy from this local directory: - index.php - songleon.php - songleoff.php and finally the folder /scripts/lights/ with - songleon.py and songleoff.py Now you are done with the main part of project. One final word of advice: in order for you to have access to the execution of the scripts controlling the spotlight (songleon.py and songleoff.py), you have to change the permissions/rights of all the files and folders previously mentioned. We recommend just for the sake of this project to give them full access with read, write, and execute privileges for root: $ sudo chown 755 /var/www/html/index/phpIn addition, you have to modify the sudoers file with nano editor: $ sudo nano /etc/sudoersProvide your password for any modifications and add the following line: www-data ALL=(ALL) NOPASSWD ALL after this line: %sudo ALL=(ALL:ALL) ALL Testing the applications Let’s see if everything is working. From your computer, laptop, or tablet, navigate to your ODROID-C2’s IP address in the browser, and click the “on” button. Are your spotlights lightening up your room? Now it’s the click the “off” button. Click it and see your room’s spotlight switched off. Success! Final notes We could give you further guidance on how to control any electrical device remotely from the office, during travelling, or you are in an emergency. This is not a difficult step now that you’ve got the basic circuit working in your local network, but be advised that such a step comes with a security risk. Hackers may be interested in controlling your server by taking advantage of a weak password, a commonly used port, or wrong router settings. For that reason, we advise you to make your network secure and even change the password for the user ODROID-C2 to a stronger one if you are implementing electric device control. You now have the knowledge you need to build something innovative and inspiring for you and your peers. Be the first to comment
https://magazine.odroid.com/article/control-electrical-device-odroid-c2-sample-project/
CC-MAIN-2019-09
refinedweb
1,856
62.58
Alibabacloud.com offers a wide variety of articles about thread class, easily find your thread class information here online. MySQL employs a cost-based optimizer to determine the most solution to the processing of queries. In many cases, MySQL is able to compute the best possible query plan, but in some cases MySQL does not xml| Monitoring Constantly sending different types of meaningful XML data to the client to simulate the different states of the production system. Given the simplicity of the function, the server only sends a random type of data to the clien Creation and initiation of threads The Java language has built-in multithreaded support, and all classes that implement the Runnable interface can be started with a new thread that executes the run ( Because a thread can enter a blocked state, and because the object may have a "sync" method--the thread cannot access that object unless the synchronization lock is lifted--so one thread is entirely likely to wait for another object, another object i First C # program: Classic Routines Hello World "Hello World" can be said to be the first routine to learn every programming language. We can enter the following C # code in any editor such as Notepad, WordPad, and Save as HelloWorld.cs, and finally The Java platform is designed to be a multithreaded environment from the outset. When your main program executes, other tasks such as fragmentation collection and event handling are done in the backgr The Java platform is designed to be a multithreaded environment from the outset. When your main program executes, other tasks such as fragmentation collection and event handling are done in the background. Essentially, you can think of these jobs as Peer-to-peer previously in the use of VB to achieve multithreading, found that there is a certain degree of difficulty. Although there are also such methods, but not satisfactory, but in C #, to write multithreaded applications is quite simple. This J2ee First, the basic question and answer 1. Which of the following classes can be inherited? Java.lang.Thread (T) Java.lang.Number (T) Java.lang.Double (F) Java.lang.Math (F) Java.lang.Void (F) Java.lang.Class (F) Java.lang.ClassLoader (T) 2. The di Problem Sys.put ("ProxyHost", "myHTTP.proxyserver.com"); Sys.put ("ProxyPort", "80"); System.setproperties (SYS); u = new URL (website); Connect = (httpurlconnection) u.openconnection (); ..... Q: The Swing component JList list data has been m /** * <p>title: Thread group </p> * <p>description: Manages multiple threads below through a thread group. </p> * <p>copyright: Python provides several modules for multithreaded programming, including thread, threading, and queue. The thread and threading modules allow programmers to create and manage threads. The thread module provides basic thread and lock support, while th The role of the thread pool: The thread pool function is to limit the number of threads executing in the system. According to the environment of the system, can automatically or manually set the number of threads to achieve the best effect of the o What is a process? When a program starts running, it is a process that includes the memory and system resources used by the running programs and programs. And a process is made up of multiple thread . NET Framework | safety | security principal objects The principal object is an instance of the class that implements the IPrincipal interface, which represents the user and includes the user's identity information. The System.Security.Principal na As our starting point, consider a program that needs to perform some CPU-intensive calculations. Because the CPU "wholeheartedly" for those computing services, so the user's input is very slow, almost no response. Here, we use a composite applet/appl Summary I guess everyone is very familiar with the scanners such as the time of Banyan, there is no impulse to write one's own. Recently Microsoft pushed it into practice. NET strategy, C # is the main push language, you are interested in using C # using multithreading in Java programs is much easier than in C or C + +, because the Java programming language provides language-level support. This article demonstrates how intuitive multithreading i Coding | procedure | specification Code specification for Java programs Li Xiaomin Software Engineer December 2000 content:Naming conv Import java.io.*; //Multithreaded programming public class multithread { public static void Main (String args[]) { System.out.println ("I am the main thread!"); //Below Create thread instance Thr
https://topic.alibabacloud.com/zqtag/thread-class_107875.html
CC-MAIN-2019-30
refinedweb
734
53.92
. Many of the CircuitPython boards also run Arduino. But how do you switch between the two? Switching between CircuitPython and Arduino is easy. If you're currently running Arduino and would like to start using CircuitPython, follow the steps found in Welcome to CircuitPython: Installing CircuitPython. If you're currently running CircuitPython and would like to start using Arduino, plug in your board, and then load your Arduino sketch. If there are any issues, you can double tap the reset button to get into the bootloader and then try loading your sketch. Always backup any files you're using with CircuitPython that you want to save as they could be deleted. That's it! It's super simple to switch between the two. We often reference "Express" and "Non-Express" boards when discussing CircuitPython. What does this mean? Express refers to the inclusion of an extra 2MB flash chip on the board that provides you with extra space for CircuitPython and your code. This means that we're able to include more functionality in CircuitPython and you're able to do more with your code on an Express board than you would on a non-Express board. Express boards include Circuit Playground Express, ItsyBitsy M0 Express, Feather M0 Express, Metro M0 Express and Metro M4 Express. Non-Express boards include Trinket M0, Gemma M0, QT Py, Feather M0 Basic, and other non-Express Feather M0 variants. CircuitPython runs nicely on the Gemma M0, Trinket M0, or QT Py M0 but there are some constraints Small Disk Space Since we use the internal flash for disk, and that's shared with runtime code, its limited! Only about 50KB of space. No Audio or NVM Part of giving up that FLASH for disk means we couldn't fit everything in. There is, at this time, no support for hardware audio playpack or NVM 'eeprom'. Modules audioio and bitbangio are not included. For that support, check out the Circuit Playground Express or other Express boards. However, I2C, UART, capacitive touch, NeoPixel, DotStar, PWM, analog in and out, digital IO, logging storage, and HID do work! Check the CircuitPython Essentials for examples of all of these. For the differences between CircuitPython and MicroPython, check out the CircuitPython documentation. Python (also known as CPython) is the language that MicroPython and CircuitPython are based on. There are many similarities, but there are also many differences. This is a list of a few of the differences. Python Libraries Python is advertised as having "batteries included", meaning that many standard libraries are included. Unfortunately, for space reasons, many Python libraries are not available. So for instance while we wish you could import numpy, numpy isn't available (look for the ulab library for similar functions to numpy which works on many microcontroller boards). So you may have to port some code over yourself! Integers in CircuitPython On the non-Express boards, integers can only be up to 31 bits long. Integers of unlimited size are not supported. The largest positive integer that can be represented is 230-1, 1073741823, and the most negative integer possible is -230, -1073741824. As of CircuitPython 3.0, Express boards have arbitrarily long integers as in Python. Floating Point Numbers and Digits of Precision for Floats in CircuitPython Floating point numbers are single precision in CircuitPython (not double precision as in Python). The largest floating point magnitude that can be represented is about +/-3.4e38. The smallest magnitude that can be represented with full accuracy is about +/-1.7e-38, though numbers as small as +/-5.6e-45 can be represented with reduced accuracy. CircuitPython's floats have 8 bits of exponent and 22 bits of mantissa (not 24 like regular single precision floating point), which is about five or six decimal digits of precision. Differences between MicroPython and Python For a more detailed list of the differences between CircuitPython and Python, you can look at the MicroPython documentation. We keep up with MicroPython stable releases, so check out the core 'differences' they document here.
https://learn.adafruit.com/adafruit-grand-central/circuitpython-expectations
CC-MAIN-2021-21
refinedweb
672
64.61
I am pleased to announce the release of *ycecrean* 1.3.5. Do you ever use `print()` or `log()` to debug your code? If so, *ycecream*, or `y` for short, will make printing debug information a lot sweeter. And on top of that, you get some basic benchmarking functionality. *Ycecream* is available on GitHub: and on PyPI. For this who know the *icecream* package, here's an overview of the differences: ---------------------------------------------------------------------------------------- characteristic ycecream IceCream ---------------------------------------------------------------------------------------- colourize no yes (can be disabled) platform Python 2.7, >=3.6, PyPy Python 2.7, =3.5, PyPy default name y ic dependencies none many number of files 1 several usable without installation yes no can be used as a decorator yes no can be used as a context manager yes no PEP8 (Pythonic) API yes no sorts dicts no by default, optional yes supports compact, indent and depth parameters of pprint yes no use from a REPL limited functionality no external configuration via json file no observes line_length correctly yes no indentation 4 blanks (overridable) dependent on length of prefix forking and cloning yes no test script pytest unittest ---------------------------------------------------------------------------------------- Recent changes: version 1.3.5 2021-04-20 ========================= New functionality (0) --------------------- The attribute delta can now be used as an ordinary attribute, including propagation and initialization from json. New tests (0) ------------- Tests for propagation of attributes added. Tests for delta setting/reading added. Bugfix (0) ---------- The recently introduced show_traceback facility didn't work under Python 2.7. Fixed. version 1.3.4 2021-04-16 ========================= New functionality (0) --------------------- Introduced a new attribute: show_traceback / st . When show_traceback is True, the ordinary output of y() will be followed by a printout of the traceback, similar to an error traceback. from ycecream import y y.show_traceback=True def x(): y() x() x() prints y| #4 in x() Traceback (most recent call last) File "c:\Users\Ruud\Dropbox (Personal)\Apps\Python Ruud\ycecream\x.py", line 6, in <module> x() File "c:\Users\Ruud\Dropbox (Personal)\Apps\Python Ruud\ycecream\x.py", line 4, in x y() y| #4 in x() Traceback (most recent call last) File "c:\Users\Ruud\Dropbox (Personal)\Apps\Python Ruud\ycecream\x.py", line 7, in <module> x() File "c:\Users\Ruud\Dropbox (Personal)\Apps\Python Ruud\ycecream\x.py", line 4, in x y() The show_traceback functionality is also available when y is used as a decorator or context manager. Documentation change (0) ------------------------ The description of ycecream on PyPI is now (nearly) the same as the readme.md file. version 1.3.3 2021-04-14 ========================= New functionality (0) --------------------- Introduced a new attribute: enforce_line_length / ell . If True, all output lines will be truncated to the current line_length. This holds for all output lines, including as_str output. Example: y.configure(enforce_line_length=True, line_length=15) s = "abcdefghijklmnopqrstuvwxyz" y(s) y(show_time=True) prints something like |y| | s: 'abcdefg |y| #35 @ 08:14: New functionality (0) --------------------- New shorthand alternatives: sdi for sort_dicts i for indent de for depth wi for wrap_indent ell for enforce_line_length version 1.3.2 2021-04-07 ========================= New functionality (0) --------------------- y.new() has a new parameter ignore_json that makes it possible to ignore the ycecream.json file. Thus, if you don't want to use any attributes that are overridden by an ycecream.json file: y = y.new(ignore_json=True) Internal changes (0) -------------------- The PY2/PY3 specific code is clustered now to make maintenance easier. In the pprint 3.8 module, the PrettyPrinter class is not even created for PY2, so no more need to disable specifically several dispatch calls. version 1.3.1 2021-04-02 ========================= New functionality (0) --------------------- The ycecream.json file may now also contain shorthand names, like p for prefix. New functionality (1) --------------------- The attribute compact now has a shorthand name: c So, y(d, compact=True) is equivalent to y(d, c=1) Changes in install ycecream.py (0) ---------------------------------- install ycecream.py will now also copy ycecream.json to site-packages, if present. Older versions of Python support (0) ------------------------------------ Ycecream now runs also under Python 2.7. The implementation required a lot of changes, most notably phasing out pathlib, f-strings, some syntax incompatibilities and function signatures. Under Python 2.7, the compact and sort_dicts attributes are ignored as the 2.7 version of pprint.pformat (which is imported) does not support these parameters. Also, the test script needed a lot of changes to be compatible with Python 2.7 and Python 3.x Under Python 2.7, the scripts install ycecream.py and install ycecream from github.py require pathlib to be installed. It is most likely that ycecream will run under Python 3.4 and 3.5, but that has not been tested (yet). python-announce-list@python.org
https://mail.python.org/archives/list/python-announce-list@python.org/thread/NT3QC7QF46S37ZVXDY3AQGOSYZJILCQX/
CC-MAIN-2022-33
refinedweb
785
58.48
MongoDB and Python – Avoiding Pitfalls by Using an “ORM” – ETL Part 3 Want to share your content on python-bloggers? click here. Avoiding MongoDB Pitfalls by Using an ORM In my previous post, I showed how you can simplify your life by using MongoDB compared to a traditional relational SQL database. To put it simply, it is trivial to provide extra depth in MongoDB (or any document database) by nesting data structures. However, this level of simplicity has its drawbacks, and you need to be aware of these as a new user. Let’s start by looking at a potential problem with the workflow from my previous post. We have a user in our app with the following information: username, hashed password, favorite integer, favorite float, and state. Typically, an app would only allow for unique usernames to avoid confusion. However, our previous application would simply continue to add users regardless of duplication. Rules would have to be added at the database level and it’s not trivial to do that. However, if we use an ORM like mongoengine, we can solve this problem easily. If you are familiar with the sqlalchemy package in Python, you are probably already aware of the benefits of an ORM. If you are not familiar with this concept, there are plenty of great resources out there to look at ( ). Those resources will be better than what I can provide, so feel free to use those. The short version is: an ORM will make your life easier because it handles your schema, provides validation, improves querying capabilities, etc. Data in mongoengine can be represented with an object that defines the schema of the collection. Let’s consider the data from the last post in which a user has the following data points: username, hashed password, favorite floating point number, favorite integer, state, and favorite restaurants per state. The dictionary representation can be seen below. Previously, we simply took the user_data variable and inserted it using pymongo. inserted_data = collection.insert_one(user_data) It isn’t immediately apparent, but a major problem with this is that there are no restrictions. A username could be used multiple times, any data type could be passed in any field, etc. In order to handle these types of issues, you would have to write a lot of code. Instead, let’s take a look at how this can be represented in mongoengine. import datetime from mongoengine import Document, StringField, DateTimeField, IntField, FloatField, DictField, connect, disconnect_all class User(Document): created_at = DateTimeField(default=datetime.datetime.utcnow) username = StringField(required=True, unique=True) hashed_password = StringField(required=True) favorite_integer = IntField() favorite_float = FloatField() state = StringField() favorite_restaurants = DictField() meta = {'collection': 'users'} This is incredibly simple and the code almost speaks for itself (I love when that happens). The new User class created simply inherits the Document class that does the heavy lifting for you. Let’s breakdown the individual items within the class: created_at – sets the field as a datetime type and defaults to utcnow when it is created username – sets the field as string type, requires it to be entered and makes sure it’s unique hashed_password = sets the field as a string type and requires it to be entered … meta = sets the collection name to ‘users’ (can be whatever you’d like) This simple little bit of code provides tremendous value. We’ll walk through some examples. Inserting data is trivial, simply create the object and use the save method: user1 = User( username=user_data['username'], hashed_password=user_data['hashed_password'], favorite_integer=user_data['favorite_integer'], favorite_float=user_data['favorite_float'], state=user_data['state'], favorite_restaurants=user_data['favorite_restaurants'] ) user1_insert = user1.save() That’s it! You have inserted the user into your database. Let’s try to create another user with the same username. It should fail. Perfect! This does not allow you to duplicate usernames. What happens if we try to insert a string instead of an integer to the favorite_integer field? It should fail. user1 = User( username='blah', hashed_password=user_data['hashed_password'], favorite_integer='one', favorite_float=user_data['favorite_float'], state=user_data['state'], favorite_restaurants=user_data['favorite_restaurants'] ) user1_insert = user1.save() Perfect! It recognizes we can’t enter a string where an integer should be. We don’t need to run through all of the fields, but this type checking works for all of them. How easy is it to query the data? You can easily create filters, groupings, etc. However, we’ll just pull the most recent data. All you do is iterate through User.objects for user in User.objects: print("USER DATA") print("----------") print(user.username) print(user.hashed_password) print(user.favorite_integer) print(user.state) print(user.favorite_restaurants) Output: That’s it! Trust me, you’ll want to use this over pymongo in many instances, but you will still need to know some MongoDB syntax when it comes time to create aggregation pipelines! Next time We’ll move beyond these basics to go through some slightly more complicated queries and aggregations. As always, the code for this can be found on our GitHub repository. Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2020/11/mongodb-and-python-avoiding-pitfalls-by-using-an-orm-etl-part-3/
CC-MAIN-2022-40
refinedweb
838
55.54
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <meta name="generator" content="HTML Tidy, see" /> <title>HTML TIDY - Release Notes< - Release Notes</h1> <p><a href="">Dave Raggett</a> <a href="mailto:dsr@w3.org">dsr@w3.org</a><3>Things awaiting further attention</h3> <p>These have been moved to the <a href="pending.html">pending page</a>, which includes all the suggestions for improvements and bug fixes. I am looking for volunteers to help with these as my current workload means that I don't get much time left to work on HTML Tidy.</p> <h2>August 2000</h2> <p.</p> <p.</p> <p>Jacques Steyn says that Tidy doesn't know about the HTML4 char attribute for col elements. Now fixed.</p> <p.</p> <p.</p> <p>Edward Zalta spotted that Tidy always removed newlines immediately after start tags even for empty elements such as img. An exception to this rule is the br element. Now fixed.</p> <h2>July 2000</h2> <p>Edward Zalta sent me an example, where Tidy was inadvertently wrapping lines after an image element. The problem was a conditional in pprint.c, now fixed.</p> <p.</p> <h2>June 2000</h2> <p>Fixed bug in NormalizeSpaces (== in place of =) on line 1699.</p> <p>I have added a new config option "gnu-emacs" following a suggestion by David Biesack. The option changes the way errors and warnings are reported to make them easier for Emacs to parse.</p> <p.</p> <p.</p> <p>Denis Barbier sent in details patches that suppresses numerous warnings when compiling tidy, especially:</p> <ul> <li>`static' declaration of subroutines when possible</li> <li>initialization of variables when it might be used before assignment</li> <li>change name of local variables when it overrides global ones (count, index, fp)</li> <li>suppression of long jump, buffers are closed in FatalError</li> </ul> <p>Fixed memory leak in CoerceNode. My thanks to Daniel Persson for spotting this. Tapio Markula asked if Tidy could give improved detection of spurious </ in script elements. Now done.</p> <p>My thanks to John Russell who pointed out that Tidy wasn't complaining about src attributes on hr elements. My thanks to Johann-Christian Hanke who spotted that Tidy didn't know about the Netscape wrap attribute for the text area element.</p> <p>Sebastian Lange has contributed a perl wrapper for calling Tidy from your perl scripts, see <a href="sl-tidy.pl">sl-tidy.pl</a>.</p> </p> <p>Henry Zrepa (sp?) reported that XHTML <param\> elements were being discarded. This was due to an error in ParseBlock, now fixed.</p> <p>Carole E. Mah noted that Tidy doesn't complain if there are two or more title elements. Tidy will now complain if there are more than one title element or more than one base element.</p> <h2>May 2000</h2> <p>Following a suggestion by Julian Reschke, I have added an option to add xml: when converting to XHTML.</p> <p>I have added support for CDATA marked sections which are passed through without change, e.g.</p> <pre> <![CDATA[ .. markup here has no effect .. ]]> </pre> <p>A number of people were interested in Tidied documents be marked as such using a meta element. Tidy will now add the following to the head if not already present:</p> <pre> <meta name="generator" content="HTML Tidy, see"> </pre> <p>If you don't want this added, set the option tidy-mark to no.</p> <p.</p> <p.</p> <p>Johannes Zellner spotted that newly declared preformatted tags weren't being treated as such for XML documents. Now fixed.</p> <h2>December 1999</h2> <p>Tidy now generates the XHTML namespace and system identifier as specified by the current <a href="">XHTML Proposed Recommendation</a>. In addition it now assumes the latest version of HTML4 - HTML 4.01. This fixes an omission in 4.0 by adding the name attribute to the img and form elements. This means that documents with rollovers and smart forms will now validate!</p> <p>James Pickering noticed that Tidy was missing off the xhtml- prefix for the XHTML DTD file names in the system identifier on the doctype. This was a recent change to XHTML. I have fixed lexer.c to deal with this.</p> <p>This release adds support for <a href=""> JSTE</a> psuedo elements looking like: <# #>. Note that Tidy can't distinguish between ASP and JSTE for psuedo elements looking like: <% %>. Line wrapping of this syntax is inhibited by setting either the wrap-asp or wrap-jste options to no.</p> <p>Thanks to Jacek Niedziela, The Win32 executable for tidy is now able to example wild cards in filenames. This utilizes the setargv library supplied with VC++.</p> <p>Jonathan Adair asked for the hashtables to be cleared when emptied to avoid problems when running Tidy a second time, when Tidy is embedded in other code. I have applied this to FreeEntities(), FreeAttrTable(), FreeConfig(), and FreeTags().</p> <p>Ian Davey spotted that Tidy wasn't deleting inline emphasis elements when these only contained whitespace (other than non-breaking spaces). This was due to an oversight in the CanPrune() function, now fixed.</p> <p().</p> <p.</p> <p>I have fleshed out the table for mapping characters in the Windows Western character set into Unicode, see Win2Unicode[]. Yahoo was, for example, using the Windows Western character for bullet, which is in Unicode is U+2022.</p> <p>David Halliday noticed that applets without any content between the start and end tags were being pruned by Tidy. This is a bug and has now been fixed.</p> <p.</p> <p>Darren Forcier asked for a way to suppress fixing up of comments when these include adjacent hyphens since this was screwing up Cold Fusion's special comment syntax. The new option is called: <i>fix-bad-comments</i> and defaults to yes.</p> <p!</p> .</p> <p>Richard Allsebrook would like to be able to map b/i to strong/em without the full clean process being invoked. I have therefore decoupled these two options. Note that setting logical-emphasis is also decoupled from drop-font-tags.</p> <h2>30th November 1999</h2> <p.</p> <p>I have also added page transition effects for the slide maker feature. The effects are currently only visible on IE4 and above, and take advantage of the meta element. I will provide an option to select between a range of transition effects in the next release.</p> <h2>November 1999</h2> <p>David Duffy found a case causing Tidy to loop indefinitely. The problem occurred when a blocklevel element is found within a list item that isn't enclosed in a ul or ol element. I have added a check to ParseList to prevent this.</p> .</p> .</p> <p.</p> <p.</p> <p>Emphasis start tags will now be coerced to end tags when the corresponding element is already open. For instance <u>...<u>. This behavior doesn't apply to font tags or start tags with attributes. My thanks to Luis M. Cruz for suggesting this idea.</p> <p.</p> <h2>October 1999</h2> <p.</p> <p>Darren Forcier reports that Cold Fusion uses the following syntax:</p> <pre> <CFIF True IS True> This should always be output <CFELSE> This will never output </CFIF> </pre> <p>After declaring the CFIF tag in the config file, Tidy was screwing up the Cold Fusion expression syntax, mapping 'True' to 'True=""' etc. My fix was to leave such pseudo attributes untouched if they occur on user defined elements.</p> <p>Jelks Cabaniss noticed that Tidy wasn't adding an id attribute to the map element when converting to XHTML. I have added routines to do this for both 'a' and 'map'. The value of the id attribute is taken from the name attribute.</p> <p.</p> <p.</p> <p>A number of people have asked for a config option to set the alt attribute for images when missing. The alt-text property can now be used for this purpose. Please note that YOU are responsible for making your documents accessible to people who can't view the images!</p> <p.</p> <p.</p> <p> <p().</p> <p.</p> <p.</p> <h2>September 1999</h2> <p.</p> <p.</p> <p)</p> <p>Change to table row parser so that when Tidy comes across an empty row, it inserts an empty cell rather than deleting it. This is consistent with browser behavior and avoids problems with cells that span rows.</p> <p.</p> <p:</p> <pre> tidy --break-before-br true --show-warnings false </pre> <p>Kenichi Numata discovered that Tidy looped indefinitely for examples similar to the following:</p> <pre> <font size=+2>Title <ol> </font>Text </ol> </pre> <p>I have now cured this problem which used to occur when a </font> tag was placed at the beginning of a list element. If the example included a list item before the </ol> Tidy will now create the following markup:</p> <pre> <font size=+2>Title</font> <blockquote>Text </blockquote> <ol> <li>list item</li> </ol> </pre> <p>This uses blockquote to indent the text without the bullet/number and switches back to the ol list for the first true list item.</p> <p.</p> <p>John Love-Jensen contribute a table for mapping the MacRoman character set into Unicode. I have added a new charset option "mac" to support this. Note the translation is one way and doesn't convert back to the Mac codes on output.</p> <p> <pre> <p><b><a href=foo>some text</i> which should be in the label</a></p> <p>next para and guess what the emphasis will be?</p> </pre> .</p> <p.</p> <p!</p> <p.</p> <p></br> is now mapped to <br> to match observed browser rendering. On the same basis, an unmatched </p> is mapped to <br><br>. This should improve fidelity of tidied files to the original rendering, subject to the limitations in the HTML standards described above.</p> <p.</p> </p> <p>I have fixed a bug on lexer.c which screwed up the removal of doctype elements. This bug was associated with the symptom of printing an indefinite number of doctype elements.</p> <h2>August 1999</h2> <p>Added lowsrc and bgproperties attributes to attribute table. Rob Clark tells me that select CustomerName from foo where x > 1 </cfquery> <cfoutput query="MyQuery"> <table> <tr> <td>#CustomerName#</TD> </tr> </table> </cfoutput> </pre> <p>but the next example <b>won't</b> since you can't as yet modify the content model for the table element:</p> <pre> <cfquery name="MyQuery" datasource="Customer"> select CustomerName from foo where x > 1 </cfquery> <table> <cfoutput query="MyQuery"> <tr> <td>#CustomerName#</TD> </tr> </cfoutput> </table> </pre> <p>I have been studying richer ways to support modular extensions to html using assertions and a generalization of regular expressions to trees. This work has led a tool for generating DTDs named <b>dtdgen</b> and I am in the process of creating a further tool for verification. More information is available in my note on <a href="">Assertion Grammars</a>. Please contact me if you are interested in helping with this work.</p> <p <i>empty</i>, i.e. has no content.</p> <p>Betsy Miller reports: <i>I tried printing the HTML Tidy page for a class I am teaching tomorrow on HTML, and everything in the "green" style (all of the examples) print in the smallest font I have ever seen (in fact they look like tiny little horizontal lines). Any explanation?</i>.</p> <p.</p> .</p> <p>Indrek Toom wants to know how to format tables so that tr elements indent their content, but td tags do not. The solution is to use <i>indent: auto</i>. <em>omit, auto, strict, loose</em> or a string specifying the fpi (formal public identifier).</p> <p.</p> <p>I have extended the support for the ASP preprocessing syntax to cope with the use of ASP within tags for attributes. I have also added a new option <tt>wrap-asp</tt> to the config file support to allow you to turn off wrapping within ASP code. Thanks to Ken Cox for this idea.</p> <p</p> .</p> <p.</p> <p>The new property <tt>indent-attributes</tt>> <p.</p> <p.</p> <p>Steffen Ullrich and Andy Quick both spotted a problem with attribute values consisting of an empty string, e.g. <tt></a> </pre> <p.</p> <h4>Chang Hyun Baek:</h4> <p>Reports a problem when generating XML using -iso2022. Tidy inserts ?/p< rather than </p>. I tried Chang's test file but it worked fine with in all the right places. Please let me know if this problem persists.</p> <h4>Christian Ruetgers:</h4> <p>When using -indent option Tidy emits a newline before which alters the layout of some tables.</p> <p!</p> <h4>Christian Pantel:</h4> <p.</p> <p>Christian also reports that <td><hr/></td> caused Tidy to discard the <hr/> element. I have fixed the associated bug in ParseBlock.</p> <h4>Chuck Baslock:</h4> <p>Points out that an isolated & is converted to & in element content and in attribute values. This is in fact correct and in agreement with the recommendations for HTML 2.0 onwards.</p> <h4>Craig Horman:</h4> <p>Reports that Tidy loops indefinitely if a naked LI is found in a table cell. I have patched ParseBlock to fix this, and now successfully deal with naked list items appearing in table cells, clothing them in a ul.</p> <h4>Craig Johnson:</h4> <p>Reports that Tidy gets confused by </comment> before the doctype. This is apparently inserted by some authoring tool or other. I have patched Tidy to safely recover from the unrecognized and unexpected end tag without moving the parse state into the head or body.</p> <h4>Daniel Vogelheim:</h4> <p().</p> <h4>Dan Rudman:</h4> <p>Would love a version of Tidy written in Java. This is a big job. I am working on a completely new implementation of Tidy, this time using an object-oriented approach but I don't expect to have this done until later this year. <b>DEFERRED</b></p> <h4>David Brooke:</h4> <p>Reports that when tidying an XMLfile with characters above 127 Tidy is outputting the numeric entity followed by the character. I have fixed this by a patch to PPrintChar() for XmlTags.</p> <h4>David Getchell:</h4> <p>Reports that Tidy thinks an ol list is HTML 4.0 when you use the type attribute. I have fixed an error in attrs.c to correct this feature to first appearing in HTML 3.2.</p> <h4>Drew Adams:</h4> <p>Reported problems when using comments to hide the contents of script elements from ancient browsers. I wasn't able to reproduce the problem, and guess I fixed it earlier.</p> <p>Drew also reported a problem which on further investigation is caused by the very weird syntax for comments in SGML and XML. The syntax for comments is really error prone:</p> <pre> <!--[text excluding --]--[[whitespace]*--[text excluding --]--]*> </pre> <p.</p> <p.</p> <p.</p> <p.</p> <h4>Guus Goos:</h4> <p?</p> <h4>Jack Horsfield:</h4> <p>Like a number of others would like list items and table cells to be output compactly where possible. I have added a flag to avoid indentation of content to tags.c that avoids further indentation when the content is inline, e.g.</p> <pre> <ul> <li>some text</li> <li> <p> a new paragraph </p> </li> </ul> </pre> <p>This behavior is enabled via "smart-indent: yes" and overrides "indent: no". Use "indent-spaces: 5" to set the number of spaces used for each level of indentation.</p> <h4>Jeff Young:</h4> <p>Has a few suggestions that will make Tidy work with XSL. Thanks, I have incorporated all of them into the new release.</p> <h4>Jelks Cabaniss:</h4> <p!).</p> <p>One thing I can satisfy right away is a mailing list for Tidy. html-tidy@w3.org has been created for discussing Tidy and I have placed the details for subscribing and accessing the Web archive on the Tidy overview page.</p> <h4>Johannes Koch:</h4> <p>Reports that Tidy isn't quite right about when it reports the doctype as inconsistent or not. I have tweaked HTMLVersion() to fix this. Let me know if any further problems arise.</p> <h4>John Tobler:</h4> <p.</p> <p.</p> <h4>Mathew Cepl:</h4> <p>Notes that dir and menu are deprecated and not allowed in HTML4 strict. I have updated the entry in the tags table for these two. I also now coerce them automatically to ul when -clean is set.</p> <h4>Maurice Buxton:</h4> <p.</p> <h4>Osma Ahvenlampi:</h4> <p>Found that Tidy is confused by map elements in the head. Tidy knows that map is only allowed in the body and thinks the author has left out the</p> .</p> <h4>Paul Ward:</h4> <p>Reports that Tidy caused JavaScript errors when it introduced linebreaks in JavaScript attributes. Tidy goes to some efforts to avoid this and I am interested in any reports of further problems with the new release.</p> <h4>Rafi Stern:</h4> <p>Would like Tidy to warn when a tag has an extra quote mark, as in <a href="xxxxxx"">. I have patched ParseAttribute to do this.</p> <h4>Rene Fritz:</h4> .</p> <h4>Shane McCarron:</h4> <p>Reports that Tidy sometimes wraps text within markup that occurs in the context of a pre element. I am only able to repeat this when the markup wraps within start tags, e.g. between attribute values. This is perfectly legitimate and doesn't effect rendering.</p> <h4>Steven Lobo:</h4> <p>Notes that Tidy doesn't remove entities such as &nbsp; or &copy; which aren't defined by XML 1.0. That is true - these entities <b>are<.</p> <h4>Steven Pemberton:</h4> <p>Comments that he would like Tidy to replace naked & in URLs by &. You can now use "quote-ampersands: yes" in the config file to ensure this. Note that this is always done when outputting to XML where naked '&' characters are illegal.</p> <p>Steven also asks for a way to allow Tidy to proceed after finding unknown elements. The issue is how to parse them, e.g. to treat them as inline or block level elements? The latter would terminate the current paragraph whereas the former would not.</p> .</p> <p>You can now declare new inline and block-level tags in the config file, e.g.:</p> <pre> define-inline-tags: foo, bar define-blocklevel-tags: blob </pre> <p.</p> <h4>Stuart Updegrave:</h4> <p.</p> <p>Stuart is also interested in having Tidy reading from and writing back to the Windows clipboard. This sounds interesting but I have to leave this to a future release.</p> <h4>Terry Cassidy:</h4> <p>Points out that Tidy doesn't like "top" or "bottom" for the align attribute on the caption element. I have added a new routine to check the align attribute for the caption element and cleaned up the code for checking the document type.</p> <h4>Xavier Plantefeve:</h4> <p.</p> <p>Xavier wonders whether name attributes should be replaced or supplemented by id attributes when translating HTML anchors to XHTML. This is something I am thinking about for a future release along with supplementing lang attributes by xml:lang attributes.</p> <h4>Zdenek Kabelac:</h4> <p>Asks for headings and paragraphs to be treated specially when other tags are indented. I have dealt with this via the new smart-indent mechanism.</p> <h2>22nd February 1999</h2> <p!</p> <h2>22nd January 1999</h2> <p>Tidy no longer complains about a missing </tr> before a <tbody>. Added link to a free <a href="">win32 GUI for tidy</a>.</p> <h2>11th January 1999</h2> <p>Added a link to the OS/2 distribution of Tidy made available by Kaz SHiMZ. No changes to Tidy's source code.</p> <h2>7th January 1999</h2> <p>Fixed bug in ParseBlock that resulted in nested table cells.</p> <p>Fixed clean.c to add the style property "text-align:" rather than "align:".</p> <p>Disabled line wrapping within HTML alt, content and value attribute values. Wrapping will still occur when output as XML.</p> <h2>16th December 1998</h2> <p.</p> <h2>14th December 1998</h2> <p>Rewrote parser for elements with CDATA content to fix problems with tags in script content.</p> <p>New pretty printer for XML mode. I have also modified the XML parser to recognize xml:space attributes appropriately. I have yet to add support for CDATA marked sections though.</p> <p>script and noscript are now allowed in inline content.</p> <p>To make it easier to drive tidy from scripts, it now returns 2 if any errors are found, 1 if any warnings are found, otherwise it returns 0. Note tidy doesn't generate the cleaned up markup if it finds errors other than warnings.</p> <p>Fixed bug causing the column to be reported incorrectly when there are inline tags early on the same line.</p> <p>Added -numeric option to force character entities to be written as numeric rather than as named character entities. Hexadecimal character entities are never generated since Netscape 4 doesn't support them.</p> <p>Entities which aren't part of HTML 4.0 are now passed through unchanged, e.g. &precompiler-entity; This means that an isolated & will be pass through unchanged since there is no way to distinguish this from an unknown entity.</p> <p>Tidy now detects malformed comments, where something other than whitespace or '--' is found when '>' is expected at the end of a comment.</p> <p>The <br> tags are now positioned at the start of a blank line to make their presence easier to spot.</p> <p>The -asxml mode now inserts the appropriate Voyager html namespace on the html element and strips the doctype. The html namespace will be usable for rigorous validation as soon as W3C finishes work on formalizing the definition of document profiles, see: <a href="">WD-html-in-xml</a>.</p> <h2>13th November 1998 and earlier releases</h2> <p>Fixed bug wherein <style type=text/css> was written out as <style type="text/ss">.</p> <p>Tidy now handles wrapping of attributes containing JavaScript text strings, inserting the line continuation marker as needed, for instance:</p> <pre> onmouseover="window.status='Mission Statement, \ Our goals and why they matter.'; return true" </pre> <p>You can now set the wrap margin with the -wrap option.</p> <p>When the output is XML, tidy now ensures the content starts with <?xml version="1.0"?>.</p> <p>The Document type for HTML 2.0 is now "-//IETF//DTD HTML 2.0//". In previous versions of tidy, it was incorrectly set to "-//W3C//DTD HTML 2.0//".</p> <p>When using the -clean option isolated FONT elements are now mapped to SPAN elements. Previously these FONT elements were simply dropped.</p> <p>NOFRAMES now works fine with BODY element in frameset documents.</p> </body> </html>
http://opensource.apple.com/source/tidy/tidy-15.3.6/tidy/htmldoc/release-notes.html
CC-MAIN-2014-49
refinedweb
3,895
65.52
I have to say, I spend a lot of time daily in Notepad++ text editor for Windows. I keep my “logbook” there. I record what I am doing now and what needs to be done. This allows me not to keep everything in my head and switch the context more efficiently. I can recommend this to everyone. And it is especially useful to note when you started working on a task and when you finished. This gives an understanding of what actually takes your time. I’m not a fan of very strict and formal techniques such as pomodoro, but using some form of time management is good. Recording timestamps manually is inconvenient. It would be much easier to press a key combination and automatically insert the current timestamp into the document. It turned out that this is possible, and even more – you can get the results of any Python script this way! I installed the PythonScript 1.5.2. plugin in Plugins->Plugins Admin. I got the new menu Plugins -> Python Script. Next, I needed to add my Python script, that I will execute. System scripts are in the folder “C:\Program Files\Notepad++\plugins\PythonScript\scripts”. User scripts are in “C:\Users\Alexander\AppData\Roaming\Notepad++\plugins\config\PythonScript\scripts”. You will see this path if you select Plugins -> Python Script -> New Script. So, I add my put_time.py script to the user scripts folder: import time time_value = time.strftime('%H:%M') editor.addText(time_value) Read more about Editor Object here. Then I added a menu item to run this script in Plugins -> Python Script -> Configuration: And now I can run it using the menu Plugins -> Python Script -> Scripts -> put_time But, of course, this is very inconvenient, so I go to Settings -> Shortcut Mapper and add a keyboard shortcut to run Plugin command. Now I can insert the timestamp using “Alt + T” Shortcut. What python binary is actually used? Not the system one! The dlls and libs are in C:\Program Files\Notepad++\plugins\PythonScript Here is the output of Plugins -> Python Script -> Show Console: Python 2.7.16 (v2.7.16:413a49145e, Mar 4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] Initialisation took 1000ms Ready. Python 2.7 is not good and you will have to install the modules manually. But on the other hand, nothing prevents you to make external calls, for example to run Python3: import time import subprocess time_value = time.strftime('%H:%M') editor.addText(time_value) command = '"C:\Program Files\Python38\python.exe" -V' editor.addText(subprocess.check_output(command, shell=True).decode('utf-8')) Output: 09:01Python 3.8.
https://avleonov.com/2020/06/03/run-python-scripts-in-notepad-using-keyboard-shortcuts/
CC-MAIN-2022-40
refinedweb
438
68.16
import "willnorris.com/go/imageproxy" Package imageproxy provides an image proxy server. For typical use of creating and using a Proxy, see cmd/imageproxy/main.go. cache.go data.go imageproxy.go transform.go NopCache provides a no-op cache implementation that doesn't actually cache anything. Transform the provided image. img should contain the raw bytes of an encoded image in one of the supported formats (gif, jpeg, or png). The bytes of a similarly encoded image is returned. type Cache interface { // Get retrieves the cached data for the provided key. Get(key string) (data []byte, ok bool) // Set caches the provided data. Set(key string, data []byte) // Delete deletes the cached data at the specified key. Delete(key string) } The Cache interface defines a cache for storing arbitrary data. The interface is designed to align with httpcache.Cache. type Options struct { // See ParseOptions for interpretation of Width and Height values Width float64 Height float64 // If true, resize the image to fit in the specified dimensions. Image // will not be cropped, and aspect ratio will be maintained. Fit bool // Rotate image the specified degrees counter-clockwise. Valid values // are 90, 180, 270. Rotate int FlipVertical bool FlipHorizontal bool // Quality of output image Quality int // HMAC Signature for signed requests. Signature string // Allow image to scale beyond its original dimensions. This value // will always be overwritten by the value of Proxy.ScaleUp. ScaleUp bool // Desired image format. Valid values are "jpeg", "png", "tiff". Format string // Crop rectangle params CropX float64 CropY float64 CropWidth float64 CropHeight float64 // Automatically find good crop points based on image content. SmartCrop bool } Options specifies transformations to be performed on the requested image. ParseOptions parses str as a list of comma separated transformation options. The options can be specified in in order, with duplicate options overwriting previous values. There are four options controlling rectangle crop: cx{x} - X coordinate of top left rectangle corner (default: 0) cy{y} - Y coordinate of top left rectangle corner (default: 0) cw{width} - rectangle width (default: image width) ch{height} - rectangle height (default: image height) For all options, integer values are interpreted as exact pixel values and floats between 0 and 1 are interpreted as percentages of the original image size. Negative values for cx and cy are measured from the right and bottom edges of the image, respectively. If the crop width or height exceed the width or height of the image, the crop width or height will be adjusted, preserving the specified cx and cy values. Rectangular crop is applied before any other transformations. The "sc" option will perform a content-aware smart crop to fit the requested image width and height dimensions (see Size and Cropping below). The smart crop option will override any requested rectangular crop. The size option takes the general form "{width}x{height}", where width and height are numbers. Integer values greater than 1 are interpreted as exact pixel values. Floats between 0 and 1 are interpreted as percentages of the original image size. If either value is omitted or set to 0, it will be automatically set to preserve the aspect ratio based on the other dimension. If a single number is provided (with no "x" separator), it will be used for both height and width. Depending on the size options specified, an image may be cropped to fit the requested size. In all cases, the original aspect ratio of the image will be preserved; imageproxy will never stretch the original image. When no explicit crop mode is specified, the following rules are followed: - If both width and height values are specified, the image will be scaled to fill the space, cropping if necessary to fit the exact dimension. - If only one of the width or height values is specified, the image will be resized to fit the specified dimension, scaling the other dimension as needed to maintain the aspect ratio. If the "fit" option is specified together with a width and height value, the image will be resized to fit within a containing box of the specified size. As always, the original aspect ratio will be preserved. Specifying the "fit" option with only one of either width or height does the same thing as if "fit" had not been specified. The "r{degrees}" option will rotate the image the specified number of degrees, counter-clockwise. Valid degrees values are 90, 180, and 270. The "fv" option will flip the image vertically. The "fh" option will flip the image horizontally. Images are flipped after being rotated. The "q{qualityPercentage}" option can be used to specify the quality of the output file (JPEG only). If not specified, the default value of "95" is used. The "jpeg", "png", and "tiff" options can be used to specify the desired image format of the proxied image. The "s{signature}" option specifies an optional base64 encoded HMAC used to sign the remote URL in the request. The HMAC key used to verify signatures is provided to the imageproxy server on startup. See for examples of generating signatures. Examples 0x0 - no resizing 200x - 200 pixels wide, proportional height x0.15 - 15% original height, proportional width 100x150 - 100 by 150 pixels, cropping as needed 100 - 100 pixels square, cropping as needed 150,fit - scale to fit 150 pixels square, no cropping 100,r90 - 100 pixels square, rotated 90 degrees 100,fv,fh - 100 pixels square, flipped horizontal and vertical 200x,q60 - 200 pixels wide, proportional height, 60% quality 200x,png - 200 pixels wide, converted to PNG format cw100,ch100 - crop image to 100px square, starting at (0,0) cx10,cy20,cw100,ch200 - crop image starting at (10,20) is 100px wide and 200px tall type Proxy struct { Client *http.Client // client used to fetch remote URLs Cache Cache // cache used to cache responses // AllowHosts specifies a list of remote hosts that images can be // proxied from. An empty list means all hosts are allowed. AllowHosts []string // Whitelist should no longer be used. Use "AllowHosts" instead. Whitelist []string // Referrers, when given, requires that requests to the image // proxy come from a referring host. An empty list means all // hosts are allowed. Referrers []string // DefaultBaseURL is the URL that relative remote URLs are resolved in // reference to. If nil, all remote URLs specified in requests must be // absolute. DefaultBaseURL *url.URL // SignatureKey is the HMAC key used to verify signed requests. SignatureKey []byte // Allow images to scale beyond their original dimensions. ScaleUp bool // Timeout specifies a time limit for requests served by this Proxy. // If a call runs for longer than its time limit, a 504 Gateway Timeout // response is returned. A Timeout of zero means no timeout. Timeout time.Duration // If true, log additional debug messages Verbose bool // ContentTypes specifies a list of content types to allow. An empty // list means all content types are allowed. ContentTypes []string // The User-Agent used by imageproxy when requesting origin image UserAgent string } Proxy serves image requests. func NewProxy(transport http.RoundTripper, cache Cache) *Proxy NewProxy constructs a new proxy. The provided http RoundTripper will be used to fetch remote URLs. If nil is provided, http.DefaultTransport will be used. ServeHTTP handles incoming requests. type Request struct { URL *url.URL // URL of the image to proxy Options Options // Image transformation to perform Original *http.Request // The original HTTP request } Request is an imageproxy request which includes a remote URL of an image to proxy, and an optional set of transformations to perform. NewRequest parses an http.Request into an imageproxy Request. Options and the remote image URL are specified in the request path, formatted as: /{options}/{remote_url}. Options may be omitted, so a request path may simply contain /{remote_url}. The remote URL must be an absolute "http" or "https" URL, should not be URL encoded, and may contain a query string. Assuming an imageproxy server running on localhost, the following are all valid imageproxy requests: String returns the request URL as a string, with r.Options encoded in the URL fragment. type TransformingTransport struct { // Transport is the underlying http.RoundTripper used to satisfy // non-transform requests (those that do not include a URL fragment). Transport http.RoundTripper // CachingClient is used to fetch images to be resized. This client is // used rather than Transport directly in order to ensure that // responses are properly cached. CachingClient *http.Client // contains filtered or unexported fields } TransformingTransport is an implementation of http.RoundTripper that optionally transforms images using the options specified in the request URL fragment. RoundTrip implements the http.RoundTripper interface. URLError reports a malformed URL error. Package imageproxy imports 30 packages (graph) and is imported by 5 packages. Updated 2019-03-17. Refresh now. Tools for package owners.
https://godoc.org/willnorris.com/go/imageproxy
CC-MAIN-2019-13
refinedweb
1,442
57.06
Building histograms using Rectangles and PolyCollections¶ Using a path patch to draw rectangles. The technique of using lots of Rectangle instances, or the faster method of using PolyCollections, were implemented before we had proper paths with moveto/lineto, closepoly etc in mpl. Now that we have them, we can draw collections of regularly shaped objects with homogeneous properties more efficiently with a PathCollection. This example makes a histogram -- it's more work to set up the vertex arrays at the outset, but it should be much faster for large numbers of objects. import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.path as path fig, ax = plt.subplots() # Fixing random state for reproducibility np.random.seed(19680801) # histogram our data with numpy data = np.random.randn(1000) n, bins = np.histogram(data, 50) # get the corners of the rectangles for the histogram left = bins[:-1] right = bins[1:] bottom = np.zeros(len(left)) top = bottom + n # we need a (numrects x numsides x 2) numpy array for the path helper # function to build a compound path XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T # get the Path object barpath = path.Path.make_compound_path_from_polys(XY) # make a patch out of it patch = patches.PathPatch(barpath) nrects = len(left) nverts = nrects*(1+3+1) verts = np.zeros((nverts, 2)) codes = np.ones(nverts, int) * path.Path.LINETO codes[0::5] = path.Path.MOVETO codes[4::5] = path.Path.CLOSEPOLY verts[0::5, 0] = left verts[0::5, 1] = bottom verts[1::5, 0] = left verts[1::5, 1] = top verts[2::5, 0] = right verts[2::5, 1] = top verts[3::5, 0] = right verts[3::5, 1] = bottom barpath = path.Path(verts, codes) References The use of the following functions, methods, classes and modules is shown in this example: matplotlib.patches matplotlib.patches.PathPatch matplotlib.path matplotlib.path.Path
https://matplotlib.org/3.4.3/gallery/misc/histogram_path.html
CC-MAIN-2022-27
refinedweb
318
60.51
I use an AS model (named AppGlobals.as) to store the application variables. I need to replace the hard-coded values of the elements to ones pulled from a database. As such, I need to iterate through the model to find all the elements that match my query results and then set the value of the elements to those returned from the database query. My current issue is that I have no clue how to iterate through the model to get the elements so that I can use them a parameters for my query. An example of AppGlobals.as follows... package com.models { [Bindable] public class AppGlobal { public var appAnnualMaintenanceAlert:String="The System is unavailable due to routine annual maintenance! Please check back after 2:00 PM Eastern on January 1, 2012!"; public var appAnnualMaintenanceStart:Date=new Date(2012, 11, 31, 18, 0, 0, 0); public var appAnnualMaintenanceEnd:Date=new Date(2013, 0, 1, 14, 0, 0, 0); public var appYearPrevious:String="2011"; public var appYear:String="2012"; public var appYearNext:String="2013"; public var dttm_landing_expected:String="1/1/2012 12:00:00 AM"; } } How can I iterate through the model to find all the var names and then match them with my query to return the corresponding values? Any help is appreciated. Thanks! Lee
https://forums.adobe.com/thread/1043125?tstart=0
CC-MAIN-2015-18
refinedweb
215
52.19
When I had a project to develop a Managed Event Sink for Exchange Server Store, I hunted for some information over the web; surprisingly I could not get links that would really help me to get started immediately! Later, it took some time to get an outline on how to create managed event sinks, and at last, when I cracked it, I thought I shall share it :-) Hence, this article. This article is targeted at intermediate users who have already developed event sinks in the COM World using VB/VC++ and others. If you are new to developing Event Sinks, I suggest that you read “Event Sinks” in the Exchange SDK documentation. The Exchange SDK has an excellent description on Event sinks. Anyways, I shall give a basic introduction to the Event Sinks. So, what does an Event Sink Really mean? Event Sink is a piece of code that gets triggered on predetermined events. A more classic jargon I can give as an example is “Hooks”, i.e. we hook and eye to an event [e.g.: a keyboard or event or a mouse event], and when the event occurs our custom code executes first and later the control is passed back to the original event if required. A similar concept is provided by Exchange Server, where in you can hook[!] or create event sinks for the events occurring at Exchange Server. Some of the events that can be hooked to are 1. Synchronous Events – Events that get triggered before an item [Mail, appointments, documents, tasks etc] is committed to the exchange server. These events pauses the exchange store thread until the event sink finishes executing. No other process can access the item during this event sink execution period as, event sink has the exclusive control over the items. Following are the events that are classified as Synchronous events. a. OnSyncSave – fires when the item is saved to exchange, but before the changes are committed. b. OnSyncDelete – fires when the item is deleted from exchange, but before the delete operation is committed. a. OnSyncSave – fires when the item is saved to exchange, but before the changes are committed. OnSyncSave b. OnSyncDelete – fires when the item is deleted from exchange, but before the delete operation is committed. OnSync 2.Asynchronous Events – Events that get fired after an item is committed to the exchange server. These Async events do not block the exchange store thread. Following are the Asynchronous events. a. OnSave – Fires after the item is saved to exchange and changes are committed b. OnDelete – Fires after the item is deleted from the exchange and changes are committed. a. OnSave – Fires after the item is saved to exchange and changes are committed OnSave b. OnDelete – Fires after the item is deleted from the exchange and changes are committed. On 3.System Events– Events that get fired based on some system wide actions on exchange server, the following are the system events. a. OnMDBStartUp – This fires up when the Exchange Database is started. b. OnMDBShutdown – This fires up when the Exchange Database is shut down. c. OnTimer – Executes a piece of code at predefined intervals. This is a very useful event, which runs irrespective of specific events. a. OnMDBStartUp – This fires up when the Exchange Database is started. OnMDBStartUp b. OnMDBShutdown – This fires up when the Exchange Database is shut down. OnMDBShutdown c. OnTimer – Executes a piece of code at predefined intervals. This is a very useful event, which runs irrespective of specific events. OnTimer Synchronous and Asynchronous events are tied to a specific item or folder in the exchange store. All these events are exposed in the Exchange CDOEX library [cdoex.dll] as interfaces. Fig 1.1 shows the object browser window of the CDOEX library. Some of the applications that can be developed using Event Sink are, Notification Subsystems Global Timer applications Workflow based applications Automatic Categorization subsystems Store maintenance for administrators Fire up your VS.NET and choose new C# Class library project and name the project, hmm... let’s call it as “MyEventSink”. On the Solution explorer, right click the project name and choose Properties, on the Project Properties page choose configuration properties choose build and set Register for COM Interop to True. True width="576" border="0" alt="Image 2" data-src="/KB/cs/csmanagedeventsinkshooks/interop.jpg" class="lazyload" data-sizes="auto" data-> Now, Copy the below files to the MyEventSink bin directory exoledb.dll from exchange server bin directory (\program files\exchsrvr\bin) cdoex.dll - \program files\common files\Microsoft Shared\CDO msado15.dll - \Program Files\Common Files\System\ADO Open up the VS.NET Command Prompt and navigate to MyEventSink bin folder, and create strong name keys for the above libraries. Key-in the following commands > Sn –k exoledb.key> Sn –k cdoex.key> Sn –k msado.key > Sn –k exoledb.key> Sn –k cdoex.key> Sn –k msado.key We need to create interop assemblies of the above library, in order to, create the interop assemblies we shall use the tlbimp tool. Key-in the following commands to create 3 interop assemblies. Copy these interop dll files to the debug folder. Switch back to VS.NET and add references to the above created interop DLL files. Modify the following attributes on the AssemblyInfo.cs Under General Information section, modify [assembly: AssemblyTitle("MyEventSink")] [assembly: AssemblyDescription("My Event Sink - Logu")] at version information section, create a new GUID and add [assembly: Guid("44E6847A-0012-42af-A317-1E1A9F0C853D")] [Tip: You can create a new GUID by clicking Tools->Create GUID] [assembly: Guid("44E6847A-0012-42af-A317-1E1A9F0C853D")] [Tip: You can create a new GUID by clicking Tools->Create GUID] at sign information section, modify [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("MyEventSink.key")] [assembly: AssemblyKeyName("MyEventSink")] Now, Choose Project Properties and set the “Wrapper assembly key file” to MyEventSink.key and “Wrapper assembly Key Name” to “My Event Sink” width="576" border="0" alt="Image 3" data-src="/KB/cs/csmanagedeventsinkshooks/wrapper.jpg" class="lazyload" data-sizes="auto" data-> Start the VS.NET Command Prompt and change directory to your project directory, and create a key, key-in the following, > sn –k MyEventSink.key Switch back to VS.NET IDE, and change the file name of class1.cs to a new name like “ExchEventSink.cs”, double click the .cs file to open. Add, using CDO; using ADODB; modify the class definition code to resemble like below, [Guid("16369924-5F32-4E26-AE89-8308B5C162E2")] public class ExchEventSink: ServicedComponent , IExStoreAsyncEvents { public string ClassID = "F92EFC3A-FDD8-4225-B005-13FD3D5D54D1"; public string InterfaceId = "704A413F-F8FE-476B-9206-69AB6300D752"; public string EventsId = "DCC71BD5-6627-4FBF-BB5A-DB8FEA1EB177"; if you observe the above code, you can notice that we are implementing the IExStoreAsyncEvents interface, which implements the asynchronous events methods namely onsave and ondelete. We shall implement the same now, add the following to your code [check the attached zip file for more information] IExStoreAsyncEvents public void OnSave(IExStoreEventInfo pEventInfo, string bstrURLItem, int lFlags) { try { if(System.Convert.ToBoolean(lFlags)) { CDO.Message iMessage=new CDO.MessageClass(); string sFrom; string sDate; try { iMessage.DataSource.Open(bstrURLItem,null, ADODB.ConnectModeEnum.adModeRead, ADODB.RecordCreateOptionsEnum.adFailIfNotExists, ADODB.RecordOpenOptionsEnum.adOpenSource,"",""); FileStream fs = new FileStream( @"c:\temp\MyEventSink.log",FileMode.OpenOrCreate); fs.Write(Encoding.ASCII.GetBytes(bstrURLItem),0, bstrURLItem.Length); sFrom = iMessage.From; sDate = iMessage.ReceivedTime.ToString(); fs.Write(Encoding.ASCII.GetBytes(sFrom),0,sFrom.Length); fs.Write(Encoding.ASCII.GetBytes(sDate),0,sDate.Length); fs.Close(); } catch (Exception ex) { throw (ex); } } } catch (Exception ex) { throw (ex); } } public void OnDelete(IExStoreEventInfo pEventInfo, string bstrURLItem, int lFlags) { try { } catch(Exception ex) {throw (ex);} } #endregion In the above code, we are processing an exchange item on onsave method, and we create a LOG file. This is a simple code example; modify it to your requirements. [Check Exchange SDK on the lflags as this is very important, ] Compile the class, you have your event sink component ready. Now, Open Component Services, under COM+ applications create new empty application and name it as “MyEventSink”, then, expand, components under MyEventSink and click “import components that are already registered” And choose “MyEventSink.ExchEventSink” from the populated list. width="503" border="0" alt="Image 4" data-src="/KB/cs/csmanagedeventsinkshooks/com.jpg" class="lazyload" data-sizes="auto" data-> Now, the event sink component is registered to the server. width="576" border="0" alt="Image 5" data-src="/KB/cs/csmanagedeventsinkshooks/comp.jpg" class="lazyload" data-sizes="auto" data-> We are done on our development part. Now, you can bind the component to any folder of exchange store, there are multiple ways to do this, I prefer the following, RegEvent.vbs - I’ve attached the VBS file along with the download zip, this script creates the event registration for the specified folder. The following command binds the event sink to my inbox folder, width="576" border="0" alt="Image 6" data-src="/KB/cs/csmanagedeventsinkshooks/onsave.jpg" class="lazyload" data-sizes="auto" data-> I’ve included the vbs file along with the zip file, you can also get more information about this at [ ] Exchange Explorer – this is a tool you get with Exchange SDK [check ] Alternatively, you can build your own event registration [that’s a separate article by itself :-) ] At last, we are done... We have created our own Managed Exchange Store Event Sink. You can also implement the Synchronous Events and the System Events as same as we have implemented the Asynchronous events. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here E:\Develop\MyEventSink\bin>regevent add "onsave;ondelete" MyEventSink.ExchEventSink Microsoft (R) Windows Script Host, Version 5.6 New Event Binding created: Event: onsave;ondelete Sink: MyEventSink.ExchEventSink FullBindingUrl: Error Commiting Transaction : -2141913011 Fehler bei der Ereignisregistrierung: Die angegebene Ereignissenke (progID: %1) kann nicht innerhalb von Prozessen ausgeführt werden. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/5673/Developing-Managed-Event-Sinks-Hooks-for-Exchange
CC-MAIN-2020-50
refinedweb
1,690
56.86
Builder Pattern – Creational In this post, I’d like to talk about the Builder Pattern. This pattern is part of the Creational grouping in which other patterns such as Factory and Singleton are also a part of. For what do we use the Builder Pattern? Sometimes we might need to have objects that work in the same way, however, have different components internally. Or we might just need two objects that are similarly built, but of course not the same. For those situations, we can make use of the Builder Pattern. The Builder does get rid of cases such as an explosion of subclasses to deal with the different configurations that an object can have; cases where classes have a big amount of constructors or cases where a class has a constructor with many parameters to try to deal with all possible configurations. Most important of all the Builder pattern separates the (maybe complex) construction of an object, from the representation of this object. Structure Here I’d like to define two ways that this is encountered: the formal way and another way that you see used quite a lot and in my opinion, it is slightly different than the formal definition. Formal Structure Here is the basic structure of the Builder Pattern (if you need a refresher on UML check this post and this post) in the way it is defined in the GoF Patterns Book: Builder The Builder is the interface which will define which defines the parts that the constructor accepts Concrete Builder This is the implementation of the builder interface. It will assemble the object accordingly to how it defines the object to be implemented Director It is simply the class that makes the use of the Builder in order to construct and get the object. Product The final object which the Builder is tasked to build. Example Scenario Let us use the scenario where we want to build a car. Now a car has the same structure: it has wheels, a transmission, a chassis, a motor, doors, etc. However, each of those components can vary itself in different ways. This is where the builder pattern shines! If we make use of the SportCarBuilder variant or the RegularCarBuilder variant we are in both cases getting a Car out of the builder! Implementation In this example, I won’t define all subtypes used in the code, but just the main parts. Alright so let’s define the Builder Interface: public interface CarBuilder { public void setEngine (Engine engine); public void setTransmission(Transmission transmission); public void setWheels (Wheel wheel); public void setChassis(Chassis chassis); } Alright with that we can define the concrete builder: public class CarBuilderImpl implements CarBuilder { private Engine engine; private Transmission transmission; private Chassis chassis; private Wheel wheel; @Override public void setEngine(Engine engine) { this.engine = engine; } @Override public void setTransmission(Transmission transmission) { this.transmission = transmission; } @Override public void setChassis(Chassis chassis) { this.chassis = chassis; } @Override public void setWheel(Wheel wheel) { this.wheel = wheel; } public Car getResult() { return new Car(engine, transmission, chassis, wheel); } } Note that the builder contains a method that will create the object and return it. Now our director which knows how the car type should be constructed: public class Director { private Builder builder; public Director(){ this.builder = new CarBuilderImpl(); } public Car construct(CarType type){ switch (type){ case SPORT: return constructSportsCar(); case REGULAR: default: return constructCityCar(); } } private Car constructSportsCar() { builder.setEngine(new Engine(3.0, 0)); builder.setTransmission(Transmission.AUTOMATIC); builder.setChassis(new SportsChassis()); builder.setWheels(new SportsWheel()); return builder.getResult(); } private Car constructCityCar() { builder.setEngine(new Engine(1.2, 0)); builder.setTransmission(Transmission.MANUAL); builder.setChassis(new TownCarChassis()); builder.setWheels(new RegularWheel()); return builder.getResult(); } } And finally, we can use the code we wrote. By passing a type to the Director.construct() method. “Out in the Wild” Structure Here is the basic structure of the Builder Pattern that you might come across while you work on your daily job or favorite open source code. They are quite similar, however, I find it nice to have an extra example: Builder The Builder is the class that takes care of building the product object correctly and eventually returning it to the requester class. You often see this class as an inner class from the Product Class itself, however, this is not a nice clean code approach. One should aim for 1 Class = 1 File. Director Just like the former case, this is simply the class that makes the use of the Builder in order to construct and get the object. Product The final object which the Builder is tasked to build. Example Scenario The scenario will be exactly the same as the above scenario but you will see the differences are in the code: Implementation First, we have the Builder itself which is not an interface and it will return a reference of itself so to allow the use of concatenation. It also makes use of the Fluent pattern which makes the code read more like a normal sentence. public class CarBuilder { Engine engine; Transmission transmission; Wheel wheel; Chassis; public CarBuilder withEngine (Engine engine){ /* Catch and throw illegal arguments here if you want to have certain guarantees */ this.engine = engine; return this; }; public CarBuilder withTransmission(Transmission transmission){ /* Catch and throw illegal arguments here if you want to have certain guarantees */ this.transmission = transmission; return this; }; public CarBuilder withWheels (Wheel wheel){ /* Catch and throw illegal arguments here if you want to have certain guarantees */ this.wheel = wheel; return this; }; public CarBuilder withChassis(Chassis chassis){ /* Catch and throw illegal arguments here if you want to have certain guarantees */ this.chassis = chassis; return this; }; public Car build(){ return new Car(this); }; } Note that we have the method call build() which order the builder to do what is supposed to do if its named “builder”. It passes itself to the car builder and with that avoids long lists of parameters. All the fields are also package-private which will make sense since the Car constructor will want to access these. Now before a quick word about the Car object, let us show how the Director gets when we use the structure above instead the formal one: public class Director { public Car construct(CarType type){ switch (type){ case SPORT: return constructSportsCar(); case REGULAR: default: return constructCityCar(); } } private Car constructSportsCar() { return new CarBuilder().withEngine(new Engine(3.0, 0)) .withTransmission(Transmission.AUTOMATIC) .withChassis(new SportsChassis()) .withWheels(new SportsWheel()) .build(); } private Car constructCityCar() { return new CarBuilder().withEngine(new Engine(1.2, 0)) .withTransmission(Transmission.MANUAL) .withChassis(new TownCarChassis()) .withWheels(new RegularWheel()) .build(); } } In my opinion, this is more concise. Finally the car object. In this case, we can have the constructor set to something like package-private since it should only get accessed by the Builder. It also will get a builder and it unpacks on to its variables: public class Car { private Engine engine; private Transmission transmission; private Wheel wheel; private Chassis; Car (CarBuilder builder){ this.engine = builder.engine; this.transmission = builder.transmission; this.wheel = builder.wheel; this.Chassis = builder.chassis; } // Getters and setters } As you can see the car class can get what it needs and even perform some functions on the variables before assigning it to its own fields. Conclusion So this is the Builder pattern! Hope you could clarify your doubts or even learn something new. Please comment away if you have any doubts or if I can help you with anything.
http://fdiez.org/builder-pattern-creational/?share=google-plus-1
CC-MAIN-2019-09
refinedweb
1,234
51.58
Building CHM using CHMBuilder Please see my blog about Sandcastle September 2007 release. With this release, we plan on shipping a new tool called CHMBuilder for CHM generation using Sandcastle. What is CHMBuilder? CHMBuilder is an executable that will be shipped under the Production Tools folder of Sandcastle. The HXS generation process in Sandcastle works much better than the CHM generation process. There are several reasons for this, but the central problem is that CHMs do not get the data to build TOC and indexes from the topic HTML files themselves. We have transforms under Production transforms folder that collect this data, but they are very slow () and are not localized Given HXS-ready Sandcastle output, ChmBuilder will produce HHP, HHC, and HHK files, and transform the HXS-ready topic files to CHM-ready topic files. Using CHMBuilder the user would no longer have to do separate BuildAssembler runs to generate CHM’s and HXSs. This also solved the internal scenario for our team where we build CHM and HxS for many products. CHMBuilder Usage: On input, htmlDirectory is a directory containing HTML topic files with XML data islands containing HXS metadata. The tocFile is the manifold TOC file, produced either using either the ReflectionToToc.xsl or DsTocToToc.xsl transforms. Upon completion, the outputDirectory contains the files projectName.HHP, projectName.HHC, projectName.HHI, and a directory with the same name and as htmlDirectory containing topic files with the same names and contents as the input topic files, but stripped of HXS-specific elements. CHMBuilder Details: 1. The HHP file produced references the HHC and HHK files produced, and the output topic directory. HHP file is generated with template read from config. Three items are replaced for a given project; they are {projectName}, {defaultTopic} and {language}. 2. The HHK entries are produced using the Term attributes on all <MSHelp:Keyword Index=”K” /> elements within the XML data island of all the topics. 3. The HHC file is produced using the structure defined in the tocFile, taking titles from the input topic files. If an <MSHelp:TOCTitle /> attribute is present, that title is used. Otherwise, the value in the HTML <title> element is used. 4. The output topic files do not contain the XML data island. All <MSHelp:link>linkText</MSHelp:link> elements are transformed into <span class=”nolink”>linkText</span>. Any other elements in the MSHelp namespace are removed. The topic documents are otherwise identical. 5. The input topic files are read with an XmlReader, and the output topic files are produced with an XmlWriter, for speed and low memory overhead. 6. The tool also successfully transforms topic files that do not appear in the TOC. 7. The tool supports htmlDirectorys with a directory substructure. The processing goes recursively through subdirectories and reproduces this structure in the output directory. 8. The tool supports Localization of TOC and Index. For HHK file, the encoding is “codepage” read from config file. For HHP file, the language option is set to “name” attribute from config. 9. The tool supports indented second level index. If there is a comma in K keyword, then only the second half of it will appear in index. Also this index entry is indented. 10. It also converts some special characters in index, eg: %3c (‘<’). CHMBuilder Config file Cheers. Anand..
https://docs.microsoft.com/en-us/archive/blogs/sandcastle/building-chm-using-chmbuilder
CC-MAIN-2022-05
refinedweb
550
57.37
const int chipSelectPin = 10; => const int chipSelectPin = 9; Could you teach me more about how to change SS pin or provide a link to RFID reader. #include <SPI.h>#include <Ethernet.h>// Enter a MAC address for your controller below.// Newer Ethernet shields have a MAC address printed on a sticker on the shieldbyte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server://IPAddress server(127.0.0.1); // numeric IP for Google (no DNS)char server[] = "ssciatesting.webege.com"; // name address for Google (using DNS)// Set the static IP address to use if the DHCP fails to assignIPAddress ip(192,168,0,104);// /cart/registration/register.php?phoneNumber=000000 HTTP/1.1"); client.println("Host: ssciatesting.webege.com"); client.println("Connection: close");); }} What can i do? Please give more detail, thank a lot. At least you have to define pin 9 as an output and drive it high (to disable it's bus usage). What is the function of Pin 12 (MISO)? Can i change pin 12 to other pin? Or i miss some code which share pin 12 to muti-devices? what does it mean? Does it mean : digitalWrite(ss, LOW); SPI.transfer(0); SPI.transfer(value); digitalWrite(ss, HIGH); pinMode(9, OUTPUT);digitalWrite(9, HIGH); Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=224279.0
CC-MAIN-2016-36
refinedweb
265
65.62
Is this a correct cron job? I tried to create a programmed action in one module. Declared this in my view. <record id="ir_cron_personnel_actions" model="ir.cron"> <field name="name">Run Personnel Actions Job</field> <field eval="True" name="active"/> <field name="user_id" ref="base.user_root"/> <field name="interval_number">1</field> <field name="interval_type">days</field> <field name="numbercall">-1</field> <field eval="'hr.personnel.action'" name="model"/> <field eval="'run_personnel_actions'" name="function"/> <field eval="'()'" name="args"/> </record> And then declared this on my .py file. def run_personnel_actions(self, cr, uid, ids, context=None): """Runs a determined action on the date set in the field effective_date. Returns None""" #This variables holds the objects we are going to be using in each action. hr_obj = self.pool.get('hr.employee') hr_cont_obj = self.pool.get('hr.contract') hr_cont_rate_obj = self.pool.get('hr.contract.rate') hr_holiday = self.pool.get('hr.holidays') hr_pay_obj = self.pool.get('hr.payslip') hr_payslip_obj = self.pool.get('hr.payslip.input') actions = self.browse(cr, uid, ids, context=None) #Loop for traversing all records in the hr.personnel.action table and if the status is for approved and the date is today, run them. for action in actions: #These variables hold the ids of the contract and payroll associated to the employee. hr_cont_id = hr_cont_obj.search(cr, uid, [('employee_id', '=', action.employee_id.id)], order='id', context=None) hr_pay_id = hr_pay_obj.search(cr, uid, [('employee_id', '=', action.employee_id.id)], order='id', context=None) hr_cont_record = hr_cont_obj.browse(cr, uid, hr_cont_id[-1], context=None) if action.states == 'approved' and action.effective_date == datetime.date.today(): if action.action_requested == '1': hr_payslip_obj.create(cr, uid, {'contract_id':hr_cont_id[-1], 'amount':action.proposed_bonus, 'name':"Bonus payment", 'code':1, 'payslip_id':hr_pay_id[0]}, context=None) self.write(cr, uid, ids, {'states':'applied'}, context=None) But so far it doesn't run when is supposed to, and doesn't raisee any error at all. Hi, thanks for the answer. I try changing it like you suggested and make a button that called the same function. The button did what's supposed to, but still the action pass and nothing happens. I know the job is running as i can see how it changes the next date to be performed. I am thinking, if i pass the function the args (self, cr, uid, ids, context=None) that ids i supposed to take all the records in my table, right? Maybe that is the issue, what do you think?
https://www.odoo.com/ar/forum/help-1/question/is-this-a-correct-cron-job-25508
CC-MAIN-2019-26
refinedweb
401
54.29
Set(Int32, String) method must be used. If there is no field of a given tag number available in the message, this member creates an association. If the field already exists, this member updates its value with the new value. Also, there are Set methods for each standard type, e.g. Set(Int32, Int32). SetV methods, e.g. SetV(Int32, Int32). need to serialize such values, however, if you perform a large amount of typed set/get operations with the message object on the critical path, then these methods are the best choice from the performance point of view. To get a field value, the Get(Int32) method must be used. Also, there are typed Get. and TryGet. methods, e.g GetInteger(Int32), TryGetInteger(Int32, Int32). Such methods perform the conversion of stored value to the corresponding type. Typed Get. methods throw an exception if the conversion fails and typed TryGet. methods return false in such cases. To check the field presence, the Contain(Int32) method must be used. To remove a field, the Remove(Int32) method must be used. The following example demonstrates the basic operations over message fields. The following interface does not allocate temporary string objects and gives an ability to manipulate fields without a GC pressure: Please see the "Using GC-free interface" article of the Low Latency Best Practices page for details. Message class supports the IEnumerable interface, therefore you can use a Message object in the foreach operator to enumerate fields of the message. Additionally, the Fields property exposed by the Message class to obtain the collection of all fields currently available in the message. When you enumerate fields of a message, this does not include fields from a repeating group. To enumerate fields of the repeating group you need to get the corresponding GroupInstance object from the repeating group, please see the FIX Repeating Groups. The following example dumps all message fields onto the system console. In each sub-namespace, which corresponds to certain FIX version (like FIXForge.NET.FIX.FIX44), there is a Tags class defined. This class contains the constants for all-known tag numbers. Additionally, there are classes, which contains the constants for all-known tag values. The usage of all of these constants makes the source code more readable.
https://ref.onixs.biz/net-fix-engine-guide/manipulating-message-fields.html
CC-MAIN-2022-27
refinedweb
380
57.37
You can subscribe to this list here. Showing 3 results of 3 On 11/12/2011 06:32 PM, JP Moresmau wrote: > Maybe one day we'll integrate Hare as a refactoring tool. sure, re-factoring would be a welcome addition. (and without, I don't see much compelling reason to use an IDE in the first place) (but see below) last I checked (but it's been a while) HaRe only parses/transforms Haskell98, so, no hierarchical module names (? although it's not quite clear from the report) If true, this would be an absolute show-stopper. (Well and I seem to be unable to compile HaRe with ghc-6.12.3 or 7.0.4) JP - could you please add (perhaps on the eclipsefp FAQ page) how much static information is available in eclipsefp and where it comes from. E.g., completion/hinting does use the fully type-checked AST? You get it from ghc-API? Completion is based on names/namespaces only? Or does it use type inference somehow? Sure, these may not be your typical Haskell newbie questions, but you are targetting the experts here (you want them to switch from emacs or vi ...) Best regards, and keep up the good work. - Johannes. Hi, does anybody know if renaming function works with eclipsefp. I tried selecting a function name and right click -> refactor -> rename and it throws this. Thanks Pradeep
http://sourceforge.net/p/eclipsefp/mailman/eclipsefp-develop/?viewmonth=201111&viewday=12
CC-MAIN-2014-23
refinedweb
234
83.25
I am sorry but I have messed up the numbering of the PRs here: They should read 30922, 30879 and 30870. I have corrected my source ChangeLog accordingly. Paul On 3/12/07, Paul Richard Thomas <paul.richard.thomas@gmail.com> wrote: > :ADDPATCH fortran: > > These three PRs have quite lightweight fixes, which are certainly > straightforward: > > PR30922: > > This involves IMPORT and interfaces and the part in resolve.c is due > to Tobias; to which I objected at the time:) I was worried that by > preventing the test for blocking of host association by same name > symbols that this would allow host association into interfaces. > Fortunately, there are other mechanisms that prevent this and the test > only concerns derived types, anyway. In addition to Tobias' > contribution, I have added a fix in decl.c that prevents gfortran from > compiling the only example on IMPORT in Metcalfe, Reid and Cohen. > Interfaces, within procedures, need to access the parent namespace via > the proc_name symbol. The testcase is based on the reporter's > original with fig. 18.4 from Metcalfe, Cohen and Reid. > > PR30870: > > This PR is concerned with data values in DATA statements. gfortran is > presently unable to use derived type components, either for the repeat > counts or the data. The fix uses gfc_match_rvalue and a test for > EXPR_STRUCTURE to do the matching, before going on to try to match a > name. The test is the reporter's. > > PR30870: > > gfortran currently rejects a generic actual argument, even if there is > a specific interface with the same name. This is fixed by going > through the generic interface to look for a specific interface with > the same name. If this is found, an error is not flagged. The > testcase is the reporter's. > > Bootstrapped and regtested on x86_ia64/FC5 - OK for trunk and, when > unblocked, 4.2? > > Paul > > 2007-03-12 Tobias Burnus <burnus@gcc.gnu.org> > Paul Thomas <pault@gcc.gnu.org> > > PR fortran/30922 > * decl.c (gfc_match_import): If the parent of the current name- > space is null, try looking for an imported symbol in the parent > of the proc_name interface. > * resolve.c (resolve_fl_variable): Do not check for blocking of > host association by a same symbol, if the symbol is in an > interface body. > > 2007-03-12 Paul Thomas <pault@gcc.gnu.org> > > PR fortran/30883 > * decl.c (match_data_constant): Before going on to try to match > a name, try to match a structure component. > > PR fortran/30870 > * resolve.c (resolve_actual_arglist): Do not reject a generic > actual argument if it has a same name specific interface. > > 2007-03-12 Paul Thomas <pault@gcc.gnu.org> > > PR fortran/30922 > * gfortran.dg/import5.f90.f90: New test. > > PR fortran/30883 > * gfortran.dg/data_components_1.f90: New test. > > PR fortran/30870 > * gfortran.dg/generic_13.f90: New test. > > -- Anon: "Ignorantibus veritatem dicere semper utile est." Abraham Lincoln: "It is better to be thought a fool than to speak and remove all doubt."
https://gcc.gnu.org/pipermail/gcc-patches/2007-March/212070.html
CC-MAIN-2021-43
refinedweb
481
68.77
Red Hat Bugzilla – Full Text Bug Listing This is my first package to Fedora and I'm seeking for someone to sponsor it. Spec URL: SRPM URL: Description: Skanlite is a light-weight scanning application based on libksane. rpmlint output: --------------- /home/rpmbuild/rpmbuild/RPMS/i386/skanlite-0.2-1.fc11.i386.rpm /usr/share/rpmlint/Pkg.py:16: DeprecationWarning: The popen2 module is deprecated. Use the subprocess module. import popen2, 2 warnings. A quick note: Version number is incorrect, since you are using a SVN snapshot. Is there any reason for this? You can obtain a stable release at e.g. You're correct, I was using SVN snapshot because I didn't knew that the packages do exist for extragear in KDE's ftp-site. Spec URL: SRPM URL: rpmlint output: --------------- /usr/share/rpmlint/Pkg.py:16: DeprecationWarning: The popen2 module is deprecated. Use the subprocess module. import popen2 skanlite.i386: W: dangling-symlink /usr/share/doc/HTML/sv/skanlite/common /usr/share/doc/HTML/sv//common skanlite.i386: W: symlink-should-be-relative /usr/share/doc/HTML/sv/skanlite/common /usr/share/doc/HTML/sv//common skanlite.i386: W: dangling-symlink /usr/share/doc/HTML/uk/skanlite/common /usr/share/doc/HTML/uk//common skanlite.i386: W: symlink-should-be-relative /usr/share/doc/HTML/uk/skanlite/common /usr/share/doc/HTML/uk//common skanlite.i386: W: dangling-symlink /usr/share/doc/HTML/pt/skanlite/common /usr/share/doc/HTML/pt//common skanlite.i386: W: symlink-should-be-relative /usr/share/doc/HTML/pt/skanlite/common /usr/share/doc/HTML/pt//common, 8 warnings. Some notes: * License - Strictly speaking, the license tag of this package should be "GPLv2 and GPLv3". * Source tarball - There is another "0.2" released tarball under and this is actually different from the one under 4.1.3. Would you update the tarball? Also: ------------------------------------------------------------ my wiki page: (Check "No one is reviewing") Review guidelines are described mainly on: ------------------------------------------------------------ By the way: - Currently on my system there are no such directories named /usr/share/doc/HTML/{pt,sv,uk}/common and no package seem to provide such directories. I think either - all symlinks pointing to these directories should be removed - or all symlinks pointing to these directories should be changed to point to /usr/share/doc/HTML/en/common . $ rpm -q -f /usr/share/doc/HTML/pt kde-filesystem-4-23.fc10.noarch There is in skanlite.desktop Icon=skanlite but skanlite.png is absent and probably should be added. (In reply to comment #6) > $ rpm -q -f /usr/share/doc/HTML/pt > kde-filesystem-4-23.fc10.noarch Please be careful: # LANG=C rpm -qf /usr/share/doc/HTML/pt/common error: file /usr/share/doc/HTML/pt/common: No such file or directory Turns out, those translations aren't entirely useful, unless kde-l10n-pt is installed, which owns said symlink. We could alternatively include the common symlink in kde-filesystem too. But, shrug, addressing all that is outside the scope of this review (else, *every* kde app would be guilty). (In reply to comment #9) > Turns out, those translations aren't entirely useful, unless kde-l10n-pt is > installed, which owns said symlink. Well, I already examined what package owns /usr/share/doc/HTML/pt/common by repoquery, but no package is returned (please see the filed bug 491247) ping? ping again? Again ping? I will close this bug as NOTABUG if no response is received from the reporter within ONE WEEK. Once closing. If someone wants to import this package into Fedora, please submit a new review request and mark this bug as a duplicate of the new one. Thank you! *** This bug has been marked as a duplicate of bug 507475 ***
https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=479147
CC-MAIN-2016-40
refinedweb
621
51.34
From: Eric Niebler (eric_at_[hidden]) Date: 2008-04-01 13:44:31 David Abrahams wrote: > Eric Niebler wrote: >> 1) The aliasing issue (proto::_left as a typedef for >> proto::transform::left) will be resolved by eliminating the "transform" >> namespace and everything in it. > > I'm sorry, I don't recall having any aliasing issue. Can you relate > this to something specific I wrote? Sure, our exchange went like this: >> proto::transform::foo is the primitive transform, and >> proto::_foo is an alias for proto::transform::foo. > > Hmm, that's hard to keep track of. If you dopped the alias it would be > a little simpler. I suggest dropping the proto::transform::foo and keeping proto::_foo. >>. OK, but I didn't like your suggestions of "function_obj" or "object". So now I leaning back toward "functional". There is some prior art for that term: the <functional> header is where the std:: function objects live. It would be nice to come up with something we can all agree on. I'm going to press to get function object equivalents to Fusion's free functions. They should be in the fusion::functional namespace if we decide to go that way. >> 5) You can override an expression's domain with >> "proto::as_expr<Domain>(expr)". > > "You" meaning "end users of libraries built with proto?" Yes. >> This gives a way to mix expressions from >> different domains in the same expression. > > I take it as_expr already exists? Correct, and it was undefined what as_expr<D>(e) does when e is an expression in a domain other than D. This just gives it an obvious and useful meaning: treat e as an expression in domain D. -- Eric Niebler Boost Consulting Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2008/04/135363.php
CC-MAIN-2019-47
refinedweb
304
68.06
Need some help on making the def fact(n) puts 'Please input a non-negative integer:' n = gets.chomp.to_i puts "The factorial of #{n} is #{factorial} n = gets.chomp.to_i def fact(n) #!/user/bin/ruby def fact(n) if n==0 1 else n * fact(n-1) end end puts fact(ARGV[0].to_i) You actually seem to be asking for two different things. The first thing you want is an application that does something like this $ ruby factorial.rb > Please input a non-negative integer (GET USER INPUT) > The factorial of (USER INPUT) is (FACTORAIL OF USER INPUT) And a command line tool that does something like this $ fact 10 > 3628800 The first one could look something like this def fact(n) (1..n).inject(:*) end puts 'Please input a non-negative integer' a = gets.to_i puts "The factorial of #{a} is #{fact(a)}" The second one could look something like this #!/usr/bin/ruby puts (1..ARGV[0].to_i).inject(:*)
https://codedump.io/share/zZjalKCMHCEK/1/user-input-to-create-factorial
CC-MAIN-2018-09
refinedweb
164
57.87
We'd like to thank all our organizers who agreed to participate (yes, even whose events did not work out. A great deal of effort was still made) in hosting and attending our 10 Million Members celebrations. Each organizer found attendees, picked a central location, an itinerary, and corralled everyone as the date approached. We cannot thank you enough. As an online community we barely ever see each others faces and for our 10 million celebration we wanted to do something a little more personal. It's a proud moment for our company, our staff, and these celebrations are a testament to the kind of members and readers we're honoured and privileged to have. You all make CodeProject what it is and we thank you. We were very proud to host the CodeProject 10 Million Member celebrations here in Brazil. The event took place at the Ludus Luderia, Bar e Café at July 21st, 2013. Although the day began rainy and cold, around the lunch time when the event started the sun was slowly showing up and then the winter day became quite hot. Luderia is a gaming bar located at the same street that holds one of the most traditional Italian festivals of São Paulo: Festa de Nossa Senhora da Achiropita. As the name suggests, the place is a bar where you can drink and savor your meals and along with the food menu you also ask for a "games" menu, so that you and your friends can decide which games you want to play. Interestingly, only board-like games, no videogames included. The waiters then bring your food, drinks and games, and if you want to try a new game you don’t know yet, waiters are at your command to explain how it works. alt="Image 2" data-src="/KB/scrapbook/669615/image002.gif" class="lazyload" data-sizes="auto" data-> Despite being a nerdy event for nerdy people in a nerdy place, we also invited families to attend, and although no alcohol was served, the gaming activities made it a lot easier for people to blend in and get to know each other. At the end the event was lots of fun and quite successful. And we know that not only from people who attended, but also from people who had to spend the beautiful Sunday somewhere else and regretted not being there with other CodeProject fans and their families. Between gaming, foods and drinks, we managed to do some short interviews with our friends there. Ricardo Drizin is an IT Manager at the insurance company Terra Brasis Resseguros, and co-founder of TV Map Guia de TV, and has been a CodeProject reader since 2002, when he hadn't played with the .NET Framework yet. He describes CodeProject as "together with Stack Overflow, the best reference for developers to learn, share code and get questions answered." (I share the same opinion, and while Stack Overflow seems to have taken the mind share for Q & A, CodeProject is second to none when it comes to cutting edge technology, original articles and full working source code). Ricardo is a big fan of reverse engineering, and recalls reading a CP article about API Hooking, some 10 years ago. He would like to see articles analyzing the anatomy of code of mainstream open source libraries, so that people could understand the internals of jQuery, or Entity Framework, for example. He believes that, since CodeProject is a place where many programming and technology enthusiasts get together, the website could introduce a place where enterpreneurs could find technical co-founders for their startup companies, and vice-versa. Artur Bath lives in Dois Vizinhos, Paraná. Artur is Microsoft Student Partner and works as programmer at Precisa Fábrica de Software. He has followed CodeProject since 2011, and thinks the website is an invaluable source of tech knowledge, especially for students. Speaking of students, he is constantly attending IT lectures, diving into cutting edge Microsoft technology such as Windows 8.1, Windows Azure and XBox & Kinect capabilities: Artur has just finished this term paper on facial recognition and skeleton recognition using Kinect, so he would be very pleased to see more CodeProject articles featuring these technologies (Artur has just posted an article on Kinect, and I hope some day we’ll see his work in CodeProject too). Jessé Lemos, Senior Systems Analyst at Grupo LTM, and knows quite a bit about search engine optimization and web services. He is a CodeProject reader since 5 years ago, and considers its articles "life savers", the last one being about details of SoapHeaders mechanism in WCF. In his wish list, Jessé would put on top: CP could provide more successful case studies about solutions that helped leverage businesses in real companies. João Talles, who is web and mobile developer and since long a technology enthusiast (ALM, web servers, cloud, mobile, science stuff, music ... actually it’s easier to say an area where he is not an enthusiast!), is also an editor of the InfoQ website (I so want him to write CP articles too!). João is a CodeProject Newsletter subscriber for 4 years now, and has been helped by a number of articles. For example, one about scalability of web applications and another one on how to backup Office files. He would love to see more architecture-centered articles, though. Thiago Prestes is solution architect at ILang Educação and started using CodeProject as his IT architecture and programming source since 4 years ago. Thiago is an experienced analyst with deep knowledge in learning management system (LMS). he’d like to see articles featuring Elastic Search, which is what he’s working with now. Thiago somehow dislikes the new CP´s "Metro" webdesign, but as he points out, maybe it´s just a question of opinion. Marcos Guimarães also works at ILang Educação as web developer, and has followed CodeProject for two years now. There is an article he recalls well: "HTML to Image in C#", which helped him create a base class for document printing that is now part of the company’s framework. He would love to see articles about Single Page Applications. Marcos believes CP could have more complete cases in some articles. Alex Martins is analyst developer at CI Systems and founder of 3Code Solutions and has known of CodeProject for 8 years. He loves the fact that CP articles have full working projects (instead of just code snippets) and are completely free. Among the several CP articles that saved his life he mentioned one about SMTP. He also would like to see articles about namespaces in webservices, WinForms animation, skin creation, web site creation from .psd file and stored procedure version control. He thinks CP would do better if it had features such as removal of non-working projects, Facebook comments and more social interaction. César Roberto de Souza is a long time Code Project fellow. He is a software development specialist at Daitan Labs S/A and CP member since 2005, with 7 articles published and 3 times winner of best article of the month. He regards CodeProject as a knowledge hub, promoting not only technology learning worldwide, but also a tool that anyone can use to write an article about interesting stuff and make his/her work visible around the world. When asked about what CP article has helped him more, he emphatically points out to Andrew Kirillov’s outstanding work about AForge.Net open source. Kirillov’s article definitely guided César through his entire academic life, inspiring him into experimenting with artificial intelligence from the very beginning of his college years. As time went by, the simplicity of components and interfaces created by Andrew helped César to create his own tools and more complex ideas. As a result, César´s Accord.Net is a direct child of Andrew´s article published in CodeProject years ago. Back to the interview: he would like to see more articles on aritificial intelligence and machine learning using .NET framework. alt="Image 5" data-src="/KB/scrapbook/669615/image005.gif" class="lazyload" data-sizes="auto" data-> After weeks of planning, and an initial commitment from 8 people, the Central Ohio Codeproject meetup eventually took place on August 25th Sunday at BJ’s brew house in the Polaris area. Unfortunately, half the group had to pull out at the last minute due to unexpected issues. The ones that turned up were Gary Wheeler, Smitha Vijayan, Rohan Nishant, and yours truly (Nish). Now this might suspiciously sound like a family get-together with Gary, but no - it was a proper CPian get-together. Smitha and I wore our CP t-shirts, and I gave Gary his t-shirt that Sean had sent me. alt="Image 6" data-src="/KB/scrapbook/669615/DSC_1412.JPG" class="lazyload" data-sizes="auto" data-> We tried a couple of different draught beers that BJ’s brew themselves, and also had some great food to go along with that. Thanks to Sean and CodeProject for funding the lunch/drinks. We talked about the old days when the active CPians were small enough that everyone knew each other personally (offline/online), how CP has grown into a major voice in the IT media world, about other CPians, about Microsoft, .NET, C++, and Windows tablets and phones. alt="Image 7" data-src="/KB/scrapbook/669615/DSC_1421.JPG" class="lazyload" data-sizes="auto" data-> Overall, I enjoyed it thoroughly, and based on their comments afterwards, so did Gary and Smitha. Rohan was more focused on his unhealthy kid’s meal, although he did frown occasionally at geeky jokes, and pretended to be interested in variadic templates at one point. We’ll probably do this again, and maybe next time, more people will turn up. Once again, cheers to the CodeProject team! Editor's Note: Shai Raiten was kind enough to host this event for us in Israel. And as you can see from the pictures, it turned out great! Thank you kindly Shai - Sean alt="Image 8" data-src="/KB/scrapbook/669615/IMG_20130822_184302.jpg" class="lazyload" data-sizes="auto" data-> alt="Image 9" data-src="/KB/scrapbook/669615/IMG_20130822_185029.jpg" class="lazyload" data-sizes="auto" data-> First of all, as part of CodeProject (India) members, Congratulations to CodeProject for reaching a high milestone of 10 million members. Also our sincere thanks to Sean, Chris and the entire CodeProject team for arranging a regional meet-ups of members. Like the other regional groups, we also had the opportunity to arrange a local meet-up with the developers, designers and testers who are directly or indirectly connected with CodeProject. We planned the same for a month or two, then decided the venue and date. It was Saturday, 17th August, just after the Independence Day in India when we celebrated CodeProject 10 million members’ meet-up event. We were 10 people from different parts of the town, gathered in a place Saturday afternoon. We all were already fed up of the daily crowd of the city and decided to go somewhere outside it, roam around some places under the clean sky, gossip in greenery, have dinner and then return to our own house at night. Let’s first introduce all the members (from left): Atul Koshta, Amit Sijaria, Me (Kunal Chowdhury), Supreet Tare, Vivek Vishwakarma, Sharad Rathore, Mohit Parihar, Atul Vishwakarma, Yogendra Kanojia and Neelesh Vishwakarma (the hidden man with the camera): alt="Image 10" data-src="/KB/scrapbook/669615/image001.jpg" class="lazyload" data-sizes="auto" data-> It was nice, clean weather when we started our journey but there were a few clouds as it was a rainy season. So, we had the fear about heavy shower but still we did not care and started our journey by bike to have some fun, get to know each other very well, discuss about community activities and more. alt="Image 11" data-src="/KB/scrapbook/669615/image002.jpg" class="lazyload" data-sizes="auto" data-> Finally after traveling approx. 15km by bike, we reached a village and it was our first shot in camera. I didn’t notice that anyone was tired as everyone was just enjoying the ride. We told lots of jokes and had lots of activities in that place and then started the journey again to enjoy the beautiful river and glistening rocks. alt="Image 12" data-src="/KB/scrapbook/669615/image003.jpg" class="lazyload" data-sizes="auto" data-> In the meantime we visited many other places like river ghat, temples, and whatever was on our way to Bhedadeep. We enjoyed every moment of the beautiful scenery and the places. alt="Image 13" data-src="/KB/scrapbook/669615/image004.jpg" class="lazyload" data-sizes="auto" data-> Finally, we reached the place called Bhedadeep surrounding by small and big rocks. People started giving various poses to capture the beautiful moment inside the camera. The rocks were very slippery due to rain as you can see in the picture, but everyone started climbing together like a great team. alt="Image 14" data-src="/KB/scrapbook/669615/image005.jpg" class="lazyload" data-sizes="auto" data-> Then we found one monk in the place wearing jeans & a shirt. He was in a deep austerities but was smiling when he realized that we were taking some snaps of him. OK ... so he is not a monk but one of the member (Neelesh) of the group who came with us and participated in this meet-up. We got couple of his very good poses. After roaming for an hour here and there, we sat into a place and started getting to knowing each other, had a very good discussion of the current technology front, our usergroup meets and many other online/offline activities. A few of them also came to know more about CodeProject and how they can be benefited from the site in terms of their career growth. It was a complete journey all together and we really enjoyed the open discussion, river, rocks and other side screens. After seeing a beautiful sunset from the top of the rocks, we decided to leave the place immediately as it would be dangerous to get down from there in the dark. There was a nice wind blowing on but we had no other choice rather than leaving the place. We took the bikes and started for a good restaurant nearby that place to have the dinner. Like the journey we also enjoyed the food over there. alt="Image 16" data-src="/KB/scrapbook/669615/image007.jpg" class="lazyload" data-sizes="auto" data-> alt="Image 17" data-src="/KB/scrapbook/669615/image008.jpg" class="lazyload" data-sizes="auto" data-> Around 10 PM, it was the time to leave for our home. We were feeling bad as we have to leave at that moment. This small time with each other made a good friendship among us. It reminded me the previous CodeProject meet-up that we had unofficially in 2010. Again, thanks to the entire CodeProject team for supporting us to do a get-together with the local developer community folks. I will never forget this day like the one we had earlier. Also, my sincere thanks to everyone who participated and shared their time to make this journey all together. alt="Image 18" data-src="/KB/scrapbook/669615/4__1_.jpg" class="lazyload" data-sizes="auto" data-> CodeProject, congratulations on your 10 Million Members celebration! We are pleased that you have chosen our area for the event. The members of Bangladesh have observed your success and hope that we will become active members of your organization. We are happy to host the CodeProject 10 Million Member celebrations here in Dhaka, Bangladesh. The CP local members have enjoyed their first meet up. Here are our valuable member’s words from the event: alt="Image 19" data-src="/KB/scrapbook/669615/DSC_7734.JPG" class="lazyload" data-sizes="auto" data-> Shuvro Paul: Thanks for giving me the chance to say something at this memorable event. First I would like to give thanks to one man for his excellent effort behind this event, Monjurul Habib, without whom we possibly could not have gathered here today! I would also like to thank all .Netter volunteers who did such a great job organizing the event. In July, 2013 a Facebook post from CP drew my attention. I made a post on the CP Facebook page about my interest to arrange such a meet-up event in our country, and made another post on the CP Lounge. For discussing with members we opened a Facebook page for the event, since then my senior fellow Monjurul Habib continued the discussion with CodeProject and shared everything with us regarding the event. Thanks to everyone for their own contribution behind the event and I am looking forward for such meet-up event in near future. alt="Image 20" data-src="/KB/scrapbook/669615/DSC_7826.JPG" class="lazyload" data-sizes="auto" data-> Monjurul Habib: Hello and welcome. I was excited about making it a jam-packed session. But as this is the first meet-up, we we will simply be introducing ourselves and sharing experiences with each other. I hope we all already know that CodeProject is a very good place for not only learning about technology worldwide, but also a tool that anyone can use to write an article about interesting stuff and make his/her work visible around the world. So, we are here to discuss how to create a networking for CP members in a pleasant, comfortable environment. We should be able to raise more CP awareness among professionals, leaders, students and IT professionals. We’ll probably do this kind of event again and maybe next time more people will turn up. Once again, cheers to the CodeProject team and special thanks to Sean for the sponsorship and awesome communication. Also thanks to all .Netter volunteers for making this day! Have a good time. Thanks! alt="Image 21" data-src="/KB/scrapbook/669615/DSC_7765.JPG" class="lazyload" data-sizes="auto" data-> Ahsan Habib: Is a Technical Lead in a well reputed company. He is currently working on Microsoft .NET Technology. He has more than 10 years of experience. He is an active CP member with 8 articles, 6 tips/tricks and also has nice contributions to the Quick Answers section. He talked about the benefits of participation on CodeProject. The summary of his speech is that "Writing articles and contributing to CodeProject improve your own skills and validate your thoughts with other experts all over the world." alt="Image 22" data-src="/KB/scrapbook/669615/DSC_7817.JPG" class="lazyload" data-sizes="auto" data-> Shahriar Iqbal Chowdhury: A Software Architect working on Microsoft .NET Technology with almost 8 years of industry experience. He is an active CP member with 10 articles, 14 tech blogs, 4 tips/tricks and also has nice contributions to the Quick Answers section. He is also an award winner for the "Best Web Dev. article of July 2013." He also talked about the benefits of participation on CodeProject and the benefits of open source contribution. As this evening is all about community contributions, it's a good platform for motivating all professionals to contribute more. He talked about the firsts steps of starting contributions and the challenges professionals faces when they start to contribute. Then he broke out some tips which could help developers overcome these challenges. He followed up with an interesting talk about how CP could improve individuals to be better developers in their careers. alt="Image 23" data-src="/KB/scrapbook/669615/DSC_7686.JPG" class="lazyload" data-sizes="auto" data-> Wahid Bin Ahsan: Chief UX Architect at desme BD / Founder at UX Saturday with Wahid. Every member enjoyed his excellent presentation from the beginning to end. alt="Image 24" data-src="/KB/scrapbook/669615/DSC_7872.jpg" class="lazyload" data-sizes="auto" data-> Though the total number of participants is less than expected we had very good discussions on how to improve the engagement in the future. We discussed Q/A sections, writing articles with good and informative contents, technical blog entries and tip/tricks. We also discussed how to engage and encourage other people like students, and other industry professionals to contribute to CP. Next, we presented a gift to the initial initiator (Shuvro Paul). And finally, we took feedback from the participants. alt="Image 25" data-src="/KB/scrapbook/669615/DSC_7890.JPG" class="lazyload" data-sizes="auto" data-> Feedback The following is the feedback from the participants: alt="Image 26" data-src="/KB/scrapbook/669615/DSC_7941.JPG" class="lazyload" data-sizes="auto" data-> Hasibul Haque: It was a great event. I am so pleased I got the chance to attend. Special thanks go to Shuvro Pal, DotNetters & the Code Project. I hope in future there will be more events like this. alt="Image 27" data-src="/KB/scrapbook/669615/DSC_7895.JPG" class="lazyload" data-sizes="auto" data-> Palash Debnath: I was really happy to participate in the CodeProject 10M members meet-up in Bangladesh. It was a fantastic evening. Lots of skilled developers from reputed software companies were present there. We had a good conversation about CodeProject and how we can enlarge the community through our participation. Also, some of senior members of the community described the culture and purpose of CodeProject. As a part of the organizing members I would like to thank CodeProject for helping us arrange such an event for the first time in our country. I hope they will continue their contributions in the near future. Thanks! Shuvro Pal: It was a great experience to meet with senior CodeProject members and top professionals from our country. It was also great to be inspired by them to contribute to CodeProject in the future, which is just what I had dreamt about recently. I would like to say the event was more fabulous than what I had imagined! I am looking forward to such meet-up events in the near future. Thanks to all for their own contribution behind the event. Pritom Nandy: It was a great event to attend. I believe this meet-up will inspire CodeProject members of Bangladesh to contribute more. We talked about different aspects of CodeProject and also shared our thoughts on how to enrich the community. We spent a very good evening with skilled software professionals and I hope to see you all again. Thank you very much. Sudipta K Paik: I was really happy to attend the 'Code Project Ten Million Members Meet-up- Bangladesh.' I got chance to meet with top level Bangladesh Developers and learn many things from them. I am grateful to DotNetters and the CodeProject Team, as well as the volunteers who arranged this nice event at Dhaka. Wahid Bin Ahsan: It was nice to be with the bright and brilliant CodeProject contributors and software professionals from reputed companies. I definitely look forward to attending more effective gatherings such as this in the future. Thank you! Munir Hassan: It was a great pleasure to attend the CodeProject 10 Million Members Meet-up in Bangladesh. I have been waiting for a long time for this type of event, where we .NET professionals can meet each other and share our knowledge. It makes our bonds stronger and helps each other improve one anothers skills. Thanks to the event organizer and CodeProject. Sobuzj Alam: It was a grand experience to attend the CodeProject "10M Meet up in Bangladesh." Thank You! Nilim Ahsan: It was a really great initiative and nice meeting with potential BD Code Projects members. Thank you! The following .Netters volunteers helped to organize the event, so a big thank goes to them for their hard work. Thank you guys! This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) K. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/669615/CodeProject-10-Million-Members-Celebration
CC-MAIN-2022-33
refinedweb
4,004
62.88
SyncSemPost(), SyncSemPost_r() Increment a semaphore Synopsis: #include <sys/neutrino.h> int SyncSemPost( sync_t* sync ); int SyncSemPost_r( sync_t* sync ); Since: BlackBerry 10.0.0 Arguments: - sync - A pointer to the synchronization object for the semaphore that you want to increment. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The SyncSemPost() and SyncSemPost_r() kernel calls increment the semaphore referenced by the sync argument. If any threads are blocked on the semaphore, the one waiting the longest is unblocked and allowed to run. These functions are identical, except for the way they indicate errors. See the Returns section for details. You should use the POSIX sem_post() function instead of calling SyncSemPost() directly. Returns: The only difference between these functions is the way they indicate errors: Errors: - EAGAIN - Not enough memory for the kernel to create the internal sync object. - EFAULT - Invalid pointer. - EINTR - A signal interrupted this function. - EINVAL - The sync argument doesn't refer to a valid semaphore. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/syncsempost.html
CC-MAIN-2014-35
refinedweb
191
52.05
On 01 Aug 2005 08:38:14 +0200, Matthieu MOY wrote: > > Mikhael Goikhman said: > > > > missing --categories and company, > > --categories and --branches are missing. Personnally, I think adding them > to rbrowse would complexify the code (and the spec, since the current > rbrowse never displays categories and branches individually, I don't know > what the output of baz rbrowse --categories should be) a lot for very > little benefit. The format is the same as with --versions, just with less components. Filtering by category and branch will always be useful. Otherwise why you would want to use a/c-b-v namespace in the first place? It is only the question whether such filtering should be done in individual frontends or in baz. I think the second, like it is done now. Anyway, I think abrowse should not be obsoleted for several months if you remove the concept of category and branch in the new browse command. > > full match rather than prefix match. > > If you mean "full match of category, branch, or version", this means the > spec will have to change again with the future namespace change. I > strongly prefer opting for the flat namespace now, and not having to > change anything later. If I have branches project--main, project--manpages, project--maintenance then I can't think about a use case when I would want to receive all versions (or revisions) given limit "project--ma" (I would use limit "project" for this) or receive "maintenance" in "project--main" query. I speak about non-regexp (exact) mode here. I don't care much about the logic for regexp mode, that is non-exact by definition. you may define a different behaviour of "project--ma", "project--ma.*" or ".*ma.*" for it. > If you mean "full match of the version", this means the string match will > match only one version, which is rather useless for rbrowse. I don't agree that limit that is version is generally useless. However it obviously should not be the only limit. The limit may be anything that abrowse currently accepts, i.e. full archive, full category and so on. Regards, Mikhael.
http://lists.gnu.org/archive/html/gnu-arch-users/2005-08/msg00004.html
CC-MAIN-2015-14
refinedweb
352
62.98
view raw In the documentation for public Object get(Object obj) Field The value is automatically wrapped in an object if it has a primitive type. public void set(Object obj, Object value) If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type. getInt setInt public class Test{ int i = 1; public static void main(String[] args) throws Exception{ Test inst = new Test(); Class<?> clazz = inst.getClass(); Field fi = clazz.getDeclaredField("i"); int ii = (int) fi.get(inst); Integer iii = new Integer(ii * 2); fi.set(inst, iii); } } It's for both type-safety and efficiency. Think about it the other way - the get*() methos are the intended way to access primitive fields, and doing so via get() just happens to work as well but requires boxing/unboxing. In other words the only reason to use get() on a primitive field is if you don't know its type ahead of time.
https://codedump.io/share/42WRLTEAw460/1/whats-the-purpose-of-the-primitive-gettersetter-in-field
CC-MAIN-2017-22
refinedweb
168
62.68
In C++, there are two statements break; and continue; specifically to alter the normal flow of a program. Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate it immediately without checking the condition. For example: You want to loop through data of all aged people except people aged 65. Or, you want to find the first person aged 20. In scenarios like these, continue; or a break; statement is used. C++ break Statement The break; statement terminates a loop (for, while and do..while loop) and a switch statement immediately when it appears. Syntax of break break; In real practice, break statement is almost always used inside the body of conditional statement (if...else) inside the loop. How break statement works? Example 1: C++ break C++ program to add all number entered by user until user enters 0. // C++ Program to demonstrate working of break statement #include <iostream> using namespace std; int main() { float number, sum = 0.0; // test expression is always true while (true) { cout << "Enter a number: "; cin >> number; if (number != 0.0) { sum += number; } else { // terminates the loop if number equals 0.0 break; } } cout << "Sum = " << sum; return 0; } Output Enter a number: 4 Enter a number: 3.4 Enter a number: 6.7 Enter a number: -4.5 Enter a number: 0 Sum = 9.6 In the above program, the test expression is always true. The user is asked to enter a number which is stored in the variable number. If the user enters any number other than 0, the number is added to sum and stored to it. Again, the user is asked to enter another number. When user enters 0, the test expression inside if statement is false and body of else is executed which terminates the loop. Finally, the sum is displayed. C++ continue Statement It is sometimes necessary to skip a certain test condition within a loop. In such case, continue; statement is used in C++ programming. Syntax of continue continue; In practice, continue; statement is almost always used inside a conditional statement. Working of continue Statement Example 2: C++ continue C++ program to display integer from 1 to 10 except 6 and 9. #include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; ++i) { if ( i == 6 || i == 9) { continue; } cout << i << "\t"; } return 0; } Output 1 2 3 4 5 7 8 10 In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is skipped inside the loop using continue; statement.
https://cdn.programiz.com/cpp-programming/break-continue
CC-MAIN-2020-24
refinedweb
428
65.32
Lucene is a free text-indexing and -searching API written in Java. To appreciate indexing techniques described later in this article, you need a basic understanding of Lucene's index structure. As I mentioned in the previous article in this series, a typical Lucene index is stored in a single directory in the filesystem on a hard disk.. The exact number of files that constitute each segment varies from index to index, and depends on the number of fields that the index contains. All files belonging to the same segment share a common prefix and differ in the suffix. You can think of a segment as a sub-index, although each segment is not a fully-independent index. -rw-rw-r-- 1 otis otis 4 Nov 22 22:43 deletable -rw-rw-r-- 1 otis otis 1000000 Nov 22 22:43 _lfyc.f1 -rw-rw-r-- 1 otis otis 1000000 Nov 22 22:43 _lfyc.f2 -rw-rw-r-- 1 otis otis 31030502 Nov 22 22:28 _lfyc.fdt -rw-rw-r-- 1 otis otis 8000000 Nov 22 22:28 _lfyc.fdx -rw-rw-r-- 1 otis otis 16 Nov 22 22:28 _lfyc.fnm -rw-rw-r-- 1 otis otis 1253701335 Nov 22 22:43 _lfyc.frq -rw-rw-r-- 1 otis otis 1871279328 Nov 22 22:43 _lfyc.prx -rw-rw-r-- 1 otis otis 14122 Nov 22 22:43 _lfyc.tii -rw-rw-r-- 1 otis otis 1082950 Nov 22 22:43 _lfyc.tis -rw-rw-r-- 1 otis otis 18 Nov 22 22:43 segments Example 1: An index consisting of a single segment. Note that all files that belong to this segment start with a common prefix: _lfyc. Because this index contains two fields, you will notice two files with the fN suffix, where N is a number. If this index had three fields, a file named _lfyc.f3 would also be present in the index directory. The number of segments in an index is fixed once the index is fully built, but it varies while indexing is in progress. Lucene adds segments as new documents are added to the index, and merges segments every so often. In the next section we will learn how to control creation and merging of segments in order to improve indexing speed. For more information about the files that make up a Lucene index, please see the File Formats document on Lucene's web site. You can find the URL in the Reference section at the end of this article. The previous article demonstrated how to index text using the LuceneIndexExample class. Because the example was so basic, there was no need to think about speed. If you are using Lucene in a non-trivial application, you will want to ensure optimal indexing performance. The bottleneck of a typical text-indexing application is the process of writing index files onto a disk. Therefore, we need to instruct Lucene to be smart about adding and merging segments while indexing documents. When new documents are added to a Lucene index, they are initially stored in memory instead of being immediately written to the disk. This is done for performance reasons. The simplest way to improve Lucene's indexing performance is to adjust the value of IndexWriter's mergeFactor instance variable. This value tells Lucene how many documents to store in memory before writing them to the disk, as well as how often to merge multiple segments together. With the default value of 10, Lucene will store 10 documents in memory before writing them to a single segment on the disk. The mergeFactor value of 10 also means that once the number of segments on the disk has reached the power of 10, Lucene will merge these segments into a single segment. (There is a small exception to this rule, which I shall explain shortly.) For instance, if we set mergeFactor to 10, a new segment will be created on the disk for every 10 documents added to the index. When the 10th segment of size 10 is added, all 10 will be merged into a single segment of size 100. When 10 such segments of size 100 have been added, they will be merged into a single segment containing 1000 documents, and so on. Therefore, at any time, there will be no more than 9 segments in each power of 10 index size. The exception noted earlier has to do with another IndexWriter instance variable: maxMergeDocs. While merging segments, Lucene will ensure that no segment with more than maxMergeDocs is created. For instance, if we set maxMergeDocs to 1000, when we add the 10,000th document, instead of merging multiple segments into a single segment of size 10,000, Lucene will create a 10th segment of size 1000, and keep adding segments of size 1000 for every 1000 documents added. The default value of maxMergeDocs is Integer#MAX_VALUE. In my experience, one rarely needs to change this value. Now that I have explained how mergeFactor and maxMergeDocs work, you can see that using a higher value for mergeFactor will cause Lucene to use more RAM, but will let Lucene write data to disk less frequently, which will speed up the indexing process. A smaller mergeFactor will use less memory and will cause the index to be updated more frequently, which will make it more up-to-date, but will also slow down the indexing process. Similarly, a larger maxMergeDocs is better suited for batch indexing, and a smaller maxMergeDocs is better for more interactive indexing. To get a better feel for how different values of mergeFactor and maxMergeDocs affect indexing speed, take a look at the IndexTuningDemo class below. This class takes three arguments on the command line: the total number of documents to add to the index, the value to use for mergeFactor, and the value to use for maxMergeDocs. All three arguments must be specified, must be integers, and must be in this order. In order to keep the code short and clean, there are no checks for improper usage. import org.apache.lucene.index.IndexWriter; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.StopAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; /** * Creates an index called 'index' in a temporary directory. * The number of documents to add to this index, the mergeFactor and * the maxMergeDocs must be specified on the command line * in that order - this class expects to be called correctly. * * Note: before running this for the first time, manually create the * directory called 'index' in your temporary directory. */ public class IndexTuningDemo { public static void main(String[] args) throws Exception { int docsInIndex = Integer.parseInt(args[0]); // create an index called 'index' in a temporary directory String indexDir = System.getProperty("java.io.tmpdir", "tmp") + System.getProperty("file.separator") + "index"; Analyzer analyzer = new StopAnalyzer(); IndexWriter writer = new IndexWriter(indexDir, analyzer, true); // set variables that affect speed of indexing writer.mergeFactor = Integer.parseInt(args[1]); writer.maxMergeDocs = Integer.parseInt(args[2]); long startTime = System.currentTimeMillis(); for (int i = 0; i < docsInIndex; i++) { Document doc = new Document(); doc.add(Field.Text("fieldname", "Bibamus, moriendum est")); writer.addDocument(doc); } writer.close(); long stopTime = System.currentTimeMillis(); System.out.println("Total time: " + (stopTime - startTime) + " ms"); } } Here are some results: prompt> time java IndexTuningDemo 100000 10 1000000 Total time: 410092 ms real 6m51.801s user 5m30.000s sys 0m45.280s prompt> time java IndexTuningDemo 100000 1000 100000 Total time: 249791 ms real 4m11.470s user 3m46.330s sys 0m3.660s As you can see, both invocations created an index with 100,000 documents, but the first one took much longer to complete. That is because it used the default mergeFactor of 10, which caused Lucene to write documents to the disk more often than the mergeFactor of 1000 used in the second invocation. Note that while these two variables can help improve indexing performance, they also affect the number of file descriptors that Lucene uses, and can therefore cause the "Too many open files" exception. If you get this error, you should first see if you can optimize the index, as will be described shortly. Optimization may help indexes that contain more than one segment. If optimizing the index does not solve the problem, you could try increasing the maximum number of open files allowed on your computer. This is usually done at the operating-system level and varies from OS to OS. If you are using Lucene on a computer that uses a flavor of the UNIX OS, you can see the maximum number of open files allowed from the command line. Under bash, you can see the current settings with the built-in ulimit command: prompt> ulimit -n Under tcsh, the equivalent is: prompt> limit descriptors To change the value under bash, use this: prompt> ulimit -n <max number of open files here> Under tcsh, use the following: prompt> limit descriptors <max number of open files here> To estimate a setting for the maximum number of open files allowed while indexing, keep in mind that the maximum number of files Lucene will open is (1 + mergeFactor) * FilesPerSegment. For instance, with a default mergeFactor of 10 and an index of 1 million documents, Lucene will require 110 open files on an unoptimized index. When IndexWrite's optimize() method is called, all segments are merged into a single segment, which minimizes the number of open files that Lucene needs.
http://www.onjava.com/pub/a/onjava/2003/03/05/lucene.html
crawl-002
refinedweb
1,571
62.58
Those are called namespace packages. Zope and Plone (ab)use them > extensively. The intended usage is to break up a big, monolithic package > [0] in parts that can be distributed independently. To implement a > namespace package, you need an empty __init__.py file with only these > lines [1]: > > from pkgutil import extend_path > __path__ = extend_path(__path__, __name__) > > But think carefully if you really need namespace packages; they solve a > specific problem, aren't a general purpose technique. See [2] for a > discussion. > > [0] Think of a huge behemoth with a "Z O P E" sign on both sides :) > [1] > [2] > > Hm.. We are using pkg_resources.declare_namespace(__name__) but I think pkgutil is much better. And we are using buildout so the omelette might help me. Link [2] very interesting. Thank you, Gabrial. -- Andrew Degtiariov DA-RIPE -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-list/2010-February/567307.html
CC-MAIN-2014-15
refinedweb
143
69.28
Structure is nothing but a group of different or same data types. While making an application in C programming language, you may come across a place wherein you may have found various variables related to each other, which doesn’t make sense without each other, however you had to store them in different-2 arrays as their data types were different. So to avoid such headache we have a powerful concept in C, which are structures. We generally use struct keyword while using them, which is nothing but short form of structured data type. How to create structure? struct struct_name { DataType member1_name; DataType member2_name; DataType member3_name; … } Here struct_name can be anything of your choice. Member’s data type can be of any type, they can be same as well as different. After this declaration struct struct_name would act as a data type. How to create variable of a structure? struct struct_name var_name; How to access data members of a structure through a struct variable? var_name.member1_name; var_name.member2_name; … How to assign values to struct members? There are three ways – 1) Using Dot(.) operator var_name.memeber_name = value; 2) Whole structure’s variables assignment in one go – struct struct_name var_name = {value for memeber1, value for memeber2 …so on for all the members} 3) Designated initializers – We will learn this at the end of this post. Complete Example: #include <stdio.h> /* I have created structure of name – StudentData*/ struct StudentData{ char *stu_name; int stu_id; int stu_age; } int main() { /* student is a variable of data type – StudentData*/ struct StudentData student; /*below I’m accessing struct members through variable –student*/ student = {"Chaitanya", 1234, 25}; printf("Student Name is: %s", student.stu_name); return 0; } There are two things to notice in above example – 1) Both the below code snippets are same. student = {"Chaitanya", 1234, 25}; OR(both are same!!) student.stu_name = "Chaitanya"; student.stu_id = 1234; student.stu_age = 25; 2) Dot (.) operator can be used to assign values to individual members of structure or can be used to access values stored in structure’s individual members. Struct inside another struct You can use a structure inside another structure, which is fairly possible. As I explained you above that once you declared a structure, the struct struct_name would act as a new data type so you can include it in another struct just like a normal data member of any data type. Sounds confusing? Don’t worry. Below example would clear your doubts – Structure 1: struct stu_addres { int street; char *state; char *city; char *country; } Structure 2: struct stu_data { int stu_id; int stu_age; char *stu_name; struct stu_address stuAddress; } Observe above code – I have nested a structure inside another structure. With the above example you would have understood the need also Assignment for struct inside struct (Nested struct) If I take the above example then assignment of values would happen in this way – struct stu_data mydata = {123, 25, “Chaitanya”, 55, {“UP”, “Delhi”, “India”}} Did you notice braces inside braces? Nested values are for nested struct’s members. How to access nested struct members? Using chain of “.” operator. Suppose you want to display the city alone from nested struct – printf("%s", mydata.stuAddress.city); Above I have used like this struct_variable.nested_struct_variable.member_name. Use of typedef typedef makes the code short and improves readability. In the above discussion we have seen that while using structs every time we have to use the lengthy syntax, which makes the code confusing, lengthy, complex and less readable. The simple solution to this issue is use of typedef. It is like an alias of struct. Code without typedef struct home_address { int local_street; char *town; char *my_city; char *my_country; }; … … struct home_address var1 = {55, "Dayal bagh", "Agra", "India"}; Code using tyepdef typedef struct home_address{ int local_street; char *town; char *my_city; char *my_country; }addr; .. .. addr var1 = {55, "Dayal bagh", "Agra", "India"}; What did you find above? I could see that instead of using struct home_address, I can use addr(type name) anywhere in the code. Remember the typedef syntax – typedef before struct keyword and the type name after closing braces and before semicolon(;). Designated initializers to set values We have already learnt two ways to set the values of a struct member, there is another way to do the same using designated initializers. typedef struct home_address{ int local_street; char *town; char *my_city; char *my_country; }addr; addr var = {.city = "Agra", .street =55}; It is useful when you want to initialize few variables in struct. A gist of above discussion 1) A struct is a collection of other data types. 2) The length of a struct is fixed based on the data type of the members. 3) A struct can be nested. 4) typedef creates a type name for a struct and makes the code easier and readable. 5) struct fields can be accessed using Dot(.) operator. Thank you.My mini project became easier after seeing your examples.
http://beginnersbook.com/2014/01/c-structures-examples/
CC-MAIN-2016-50
refinedweb
809
62.98
Hello, my assignment is to create a word filter that prompts for the forbidden word and replacement word, then scans an arbitrary amount of text and prints out the cleaned up version of the text, and also print the number of replaced words at the end. I understand the loop structure (I have a flow chart written out) but I am completely confused on the syntax of getting the program to scan individual words and then move on to the next after it gets a result. Do I need a variable that will act as a middle ground so it can do this or not? Also I only need to account for full words. If night was the forbidden word I wouldn't have to replace it within the word knight. Here's my code: Thank you!Thank you!Code Java: import java.util.Scanner; public class Project2 { public static void main(String[] args) { String forbidword; String replaceword; int numreplaced = 0; System.out.println("Enter word to be filtered out:"); Scanner keyboard = new Scanner(System.in); forbidword = keyboard.next(); System.out.println("Enter replacement word:"); replaceword = keyboard.next(); System.out.println("Enter text to filter. Hit Control-Z to stop."); while(keyboard.hasNext()); { if (keyboard.next().equals(forbidword)) // I know /\ this /\ is wrong but I don't know what else to put there. { numreplaced = numreplaced + 1; // Supposed to somehow move on to the next word here? } else { // This will be the same as the 'if' part except without the counter } } System.out.println("A total of " + numreplaced + " words were replaced."); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/5253-word-filter-assignment-help-printingthethread.html
CC-MAIN-2014-41
refinedweb
260
66.94
Find the key of a dictionary entry (returns a shareable string object handle) #include <strm.h> const strm_string_t *strm_dict_key_rstr( const strm_dict_t *dict, size_t n ); libstrm The function strm_dict_key_rstr() finds the (n+1)th entry in the specified dictionary and returns a handle to the entry's key. For example, if n is 3, a handle to the the key of the fourth entry is returned. The returned shareable string object handle is owned by the dictionary, and remains valid until the dictionary handle is destroyed. A shareable string object handle to the key of the specified entry if it's found, or a null pointer if it isn't found. QNX Neutrino
http://www.qnx.com/developers/docs/6.6.0_anm11_wf10/com.qnx.doc.mm_renderer/topic/dict_obj_api/strm_dict_key_rstr.html
CC-MAIN-2018-22
refinedweb
112
58.42
class in UnityEngine.Networking A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on clients, but not generate warnings. This custom attribute is the same as the [Client] custom attribute, except that it does not generate a warning in the console if called on a server. This is useful to avoid spamming the console for functions that will be invoked by the engine, such as Update() or physics callbacks. using UnityEngine; using UnityEngine.Networking; public class Example : MonoBehaviour { [ClientCallback] void OnTriggerEnter2D(Collider2D collider) { // make explosion } } This will make the explosion code only run when the trigger is hit on the client.
https://docs.unity3d.com/ja/2017.3/ScriptReference/Networking.ClientCallbackAttribute.html
CC-MAIN-2020-50
refinedweb
110
61.87
10 May 2012 07:55 [Source: ICIS news] TOKYO (ICIS)--?xml:namespace> Sumitomo Chemical registered extraordinary losses of Y26.0bn during the full year to 31 March 2012 due to a write-down of investment in an unnamed affiliated company, it said in a statement. Operating profit during the 12 months fell 31% year on year to Y60.7bn from Y88.0bn, while net sales were down 1.7% to Y1,947.9bn from Y1,982.4bn. Full-year operating profit in the petrochemicals and plastics segment declined 45% to Y11.1bn from the previous year, while net sales rose 3.1% to Y679.6bn. This was a result of decrease in shipments of synthetic resins and petrochemical products year on year due to the scheduled maintenance shutdowns of Sumitomo Chemical’s plants in Besides, the impact of the 11 March 2011 earthquake and subsequent lower demand also contributed to the decline in earnings. On the other hand sales rose on the back of higher market prices overseas and increased selling prices in (
http://www.icis.com/Articles/2012/05/10/9558111/japans-sumitomo-chemical-full-year-net-profit-falls.html
CC-MAIN-2015-06
refinedweb
173
67.76
Current Version: Linux Kernel - 3.80 Synopsis #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); Description - (aq\0aq) until data is actually written into the gap. Seeking file data and holes - (since Linux 3.8) Return Value Errors - EBADF - fd is not an open file descriptor. - EINVAL - whence is not valid. Or: the resulting file offset would be negative, or beyond the end of a seekable device. - SEEK_DATA and SEEK_HOLE are nonstandard extensions also present in Solaris, FreeBSD, and DragonFly BSD; they are proposed for inclusion in the next POSIX revision (Issue 8). Notes. Colophon License & Copyright Copyright (c) 1980, 1991 Regents of the University of California. and Copyright (c) 2011, @(#)lseek.2 6.5 (Berkeley) 3/10/91 Modified 1993-07-23 by Rik Faith Modified 1995-06-10 by Andries Brouwer Modified 1996-10-31 by Eric S. Raymond Modified 1998-01-17 by Michael Haardt Modified 2001-09-24 by Michael Haardt Modified 2003-08-21 by Andries Brouwer 2011-09-18, mtk, Added SEEK_DATA + SEEK_HOLE
https://community.spiceworks.com/linux/man/2/lseek
CC-MAIN-2018-34
refinedweb
172
58.89
Created 07-07-2021 09:07 AM I have a spark cluster with one master and two workers on different servers. I have copied hive-site.xml in spark conf on all 3 servers and started thrift server on master server pointing to spark master. Using this to connect beeline to thrift server and run spark sql queries. I created a scala application to load data from csv to dataframe and then to a spark sql table backed by S3 parquet. Metadata is in MySQL. I am using spark submit command to run the scala app on the cluster. I do not see the table created by the scala app in beeline. However, when I use spark shell on master connected to spark master and do the same loading of a csv file and creating a table, I can see it in beeline. Am I missing something with the scala app? Also do we need HDFS to make this work? hive.metastore.uris in hive-site.xml is not set currently. Not sure what I should set that to, since I dont have anything running on the 9083 port. Also I started thrift server(which runs on port 10000) from spark sbin directory like this : /opt/spark/sbin/start-thriftserver.sh --master spark://<master-ip>:7077 --total-executor-cores 1 This is my scala code: def main(args : Array[String]) { println( "Hello World!" ) val warehouseLocation = "/home/ubuntu/test/hive_warehouse" val spark = SparkSession .builder() .appName("Spark SQL basic example") .config("spark.sql.warehouse.dir", warehouseLocation) .enableHiveSupport() .getOrCreate() val df = spark.read.format("csv").load(args(0)) df.createOrReplaceTempView("my_temp_table") spark.sql("create table test1_0522 location 's3a://<test-bucket>/data/test1_0522' stored as PARQUET as select * from my_temp_table") spark.sql("SHOW TABLES").show() } @SparkNewbie Can you add the redcline between your 2 commands spark.sql("create table test1_0522 location 's3a://<test-bucket>/data/test1_0522' stored as PARQUET as select * from my_temp_table") REFRESH TABLE test1_0522; spark.sql("SHOW TABLES").show() That should resolve the problem. Happy hadooping Created 07-07-2021 04:34 PM Thank you for your response. I tried as you suggested but the table didn't show up in beeline. I checked in mysql metastore db as well. The new table info does not show up there. 21/07/07 23:07:56 INFO MetaStoreDirectSql: Using direct SQL, underlying DB is DERBY I still see the above in the stderr file eventhough my hive-site.xml is set to use mysql. Not sure if I am missing something else. <name>hive.metastore.db.type</name> <value>mysql</value> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:mysql://<mysql end point>:3306/metastore_db</value> Bingo you are using the derby DB, which is only recommended for testing. There are three modes for Hive Metastore deployment: In Hive by default, metastore service runs in the same JVM as the Hive service. It uses embedded derby database stored on the local file system in this mode. Thus both metastore service and hive service runs in the same JVM by using embedded Derby Database. But, this mode also has its limitation that, as only one embedded Derby database can access the database files on disk at any one time, so only one Hive session could be open at a time. 21/07/07 23:07:56 INFO MetaStoreDirectSql: Using direct SQL, underlying DB is DERBY Derby is an embedded relational database in Java program and used for online transaction processing and has a 3.5 MB disk-space footprint. Depending on your software HDP or Cloudera ensure the hive DB is plugged to an external Mysql database For CDH using Mysql For HDP using mysql Check your current hive UI backend metadata databases !! After installing MySQL then you should toggle hive config to point to the external Mysql database .. Once done your commands and the refresh should succeed Please let me know if you need help Happy hadooping
https://community.cloudera.com/t5/Support-Questions/Unable-to-see-table-created-by-scala-app-in-spark-beeline/m-p/320152
CC-MAIN-2021-31
refinedweb
654
65.93
FORK(2) Linux Programmer's Manual FORK(2) NAME fork - create a child process SYNOPSIS #include <sys/types.h> #include <unistd.h> pid_t fork(void); DESCRIPTION fork() creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited. Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to dupli- cate the parent's page tables, and to create a unique task structure for the child. RETURN VALUE On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of exe- cution.. EXAMPLE See pipe(2) and wait(2). SEE ALSO clone(2), execve(2), setrlimit(2), unshare(2), vfork(2), wait(2), capa- bilities(7) Linux 2.6.6 2004-05-27 FORK(2)
http://man.yolinux.com/cgi-bin/man2html?cgi_command=fork
CC-MAIN-2016-07
refinedweb
168
63.9
On Wed, 2008-04-16 at 15:59 +0200, Ondrej Certik wrote: > Thanks for the reply. As I said, I am not questioning new SONAME bumps > going into NEW. > > The question is, whether the DMs should be allowed to upload SONAME > bumps to NEW by themselves or not. Umm, I would have to say no. Sorry. SONAME bumps are just too disruptive IMHO. > I agree there should be a special > attention to SONAME bumps and that's what the NEW is for (or any other > queue as you said). NEW is a step that can help with SONAME bumps but it is not sufficient on its own. SONAME transitions MUST be coordinated amongst all the DD's (and upstreams) involved. Such uploads can take months to arrange and coordinate - your sponsor is best placed to deal with these issues. More haste, less speed. DDs can make mistakes but DMs are not full DDs and as such, the intervention of a DD is appropriate when the potential upload could cause havoc in the rest of Debian (IMHO). > It's all about how much trust you give to DMs. Imho if they are > allowed to upload new revisions and even new upstream (if the name of > all the binaries and the number of them stays the same), they can > screw up a lot of things. Not as many as a SONAME transition. Any library upload can mistakenly result in a broken API/ABI but normally that only affects one part of the library functionality. A new SONAME is a completely NEW library - there is nothing that says that libfoo1 has to have *anything* in common with libfoo2 at a binary or source code level. It might do the same things on the surface but during a SONAME change, the library upstream can change 100% of the API and touch 100% of the source code. Every single header filename, function prototype, typedef, macro, struct and variable. e.g. some SONAME bumps have involved a complete renaming of the functions and variables to a new namespace - FooFunc becoming foo_func etc. and with structs going the opposite way from foo_data to FooData. Yes, the principle of the library stays the same and it works in a similar manner once the reverse dependencies are rebuilt but nothing else is the same. After all, Debian is STILL carrying gtk1 - that should give you some idea of the disruption caused by SONAME bumps. The consequences of a single upload can take YEARS to resolve (and still involve the removal of otherwise usable packages). A new application can change 100% of the source code without problems - many do change as much as 50% at each major release. Changing the behaviour of a shared library has far wider implications. The two simply cannot be compared. I maintain (and co-maintain) a range of libraries, some upstream too - I can honestly say that I would not consider any of those as suitable for DM-Upload, even without changing a SONAME. > So giving them the right to also upload new > binary packages to NEW imho belongs to the same cathegory. Not even close. IMHO, the very fact that you equate those two makes me doubt that you properly understand shared libraries and SONAME bumps in Debian.. -- Neil Williams ============= Attachment: signature.asc Description: This is a digitally signed message part
https://lists.debian.org/debian-devel/2008/04/msg00486.html
CC-MAIN-2017-30
refinedweb
557
71.04
. # Execute this cell to define this variable # Either click Cell => Run from the menu or type # ctrl-Enter to execute. See the Help menu for lots # of useful tips. Help => IPython Help and # Help => Keyboard Shortcuts are especially # useful. message = "I want to mine the social web!" # The variable 'message is defined here. Execute this cell to see for yourself print message # The variable 'message' is defined here, but we'll delete it # after displaying it to illustrate an important point... print message del message # The variable message is no longer defined in this cell or two cells # above anymore. Try executing this cell or that cell to see for yourself. print message # Try typing in some code of your own! This section of the notebook introduces a few Python idioms that are used widely throughout the book that you might find very helpful to review. This section is not intended to be a Python tutorial. It is intended to highlight some of the fundamental aspects of Python that will help you to follow along with the source code, assuming you have a general programming background. Sections 1 through 8 of the Python Tutorial are what you should spend a couple of hours working through if you are looking for a gentle introduction Python as a programming language. If you come from a web development background, a good starting point for understanding Python data structures is to start with JSON as a reference point. If you don't have a web development background, think of JSON as a simple but expressive specification for representing arbitrary data structures using strings, numbers, lists, and dictionaries. The following cell introduces some data structures. Execute the following cell that illustrates these fundamental data types to follow along. an_integer = 23 print an_integer, type(an_integer) print a_float = 23.0 print a_float, type(a_float) print a_string = "string" print a_string, type(a_string) print a_list = [1,2,3] print a_list, type(a_list) print a_list[0] # access the first item print a_dict = {'a' : 1, 'b' : 2, 'c' : 3} print a_dict, type(a_dict) print a_dict['a'] # access the item with key 'a' Assuming you've followed along with these fundamental data types, consider the possiblities for arbitrarily composing them to represent more complex structures: contacts = [ { 'name' : 'Bob', 'age' : 23, 'married' : False, 'height' : 1.8, # meters 'languages' : ['English', 'Spanish'], 'address' : '123 Maple St.', 'phone' : '(555) 555-5555' }, {'name' : 'Sally', 'age' : 26, 'married' : True, 'height' : 1.5, # meters 'languages' : ['English'], 'address' : '456 Elm St.', 'phone' : '(555) 555-1234' } ] for contact in contacts: print "Name:", contact['name'] print "Married:", contact['married'] print As alluded to previously, the data structures very much lend themselves to constructing JSON in a very natural way. This is often quite convenient for web application development that involves using a Python server process to send data back to a JavaScript client. The following cell illustrates the general idea. import json print contacts print type(contacts) # list # json.dumps pronounced (dumps stands for "dump string") takes a Python data structure # that is serializable to JSON and dumps it as a string jsonified_contacts = json.dumps(contacts, indent=2) # indent is used for pretty-printing print type(jsonified_contacts) # str print jsonified_contacts A couple of additional types that you'll run across regularly are tuples and the special None type. Think of a tuple as an immutable list and None as a special value that indicates an empty value, which is neither True nor False. a_tuple = (1,2,3) an_int = (1) # You must include a trailing comma when only one item is in the tuple a_tuple = (1,) a_tuple = (1,2,3,) # Trailing commans are ok in tuples and lists none = None print none == None # True print none == True # False print none == False # False print # In general, you'll see the special 'is' operator used when comparing a value to # None, but most of the time, it works the same as '==' print none is None # True print none is True # False print none is False # False As indicated in the python.org tutorial, None is often used as a default value in function calls, which are defined by the keyword def def square(x): return x*x print square(2) # 4 print # The default value for L is only created once and shared amongst # calls def f1(a, L=[]): L.append(a) return L print f1(1) # [1] print f1(2) # [1, 2] print f1(3) # [1, 2, 3] print # Each call creates a new value for L def f2(a, L=None): if L is None: L = [] L.append(a) return L print f2(1) # [1] print f2(2) # [2] print f2(3) # [3] For lists and strings, you'll often want to extract a particular selection using a starting and ending index. In Python, this is called slicing. The syntax involves using square brackets in the same way that you are extracting a single value, but you include an additional parameter to indicate the boundary for the slice. a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print a_list[0] # a print a_list[0:2] # ['a', 'b'] print a_list[:2] # Same as above. The starting index is implicitly 0 print a_list[3:] # ['d', 'e', 'f', 'g'] Ending index is implicitly the length of the list print a_list[-1] # g Negative indices start at the end of the list print a_list[-3:-1] # ['e', 'f'] Start at the end and work backwards. (The index after the colon is still excluded) print a_list[-3:] # ['e', 'f', 'g'] The last three items in the list print a_list[:-4] # ['a', 'b', 'c'] # Everything up to the last 4 items a_string = 'abcdefg' # String slicing works the very same way print a_string[:-4] # abc Think of Python's list list comprehensions idiom as a concise and efficient way to create lists. You'll often see list comprehensions used as an alternative to for loops for a common set of problems. Although they may take some getting used to, you'll soon find them to be a natural expression. See the section entitled "Loops" from Python Performance Tips for more details on some of the details on why list comprehensions may be more performant than loops or functions like map in various situations. # One way to create a list containing 0..9: a_list = [] for i in range(10): a_list.append(i) print a_list # How to do it with a list comprehension print [ i for i in range(10) ] # But what about a nested loop like this one, which # even contains a conditional expression in it: a_list = [] for i in range(10): for j in range(10, 20): if i % 2 == 0: a_list.append(i) print a_list # You can achieve a nested list comprehension to # achieve the very same result. When reading or writing # list comprehension. When written with highly readable # indention like below, note the striking similarity to # the equivalent code as presented above. print [ i for i in range(10) for j in range(10, 20) if i % 2 == 0 ] In the same way that you can concisely construct lists with list comprehensions, you can concicely construct dictionaries with dictionary comprehensions. The underlying concept involved and the syntax is very similar to list comprehensions. The following example illustrates a few different way to create the same dictionary and introduces dictionary construction syntax. # Literal syntax a_dict = { 'a' : 1, 'b' : 2, 'c' : 3 } print a_dict print # Using the dict constructor a_dict = dict([('a', 1), ('b', 2), ('c', 3)]) print a_dict print # Dictionary comprehension syntax a_dict = { k : v for (k,v) in [('a', 1), ('b', 2), ('c', 3)] } print a_dict print # A more appropriate circumstance to use dictionary comprehension would # involve more complex computation a_dict = { k : k*k for k in xrange(10) } # {0: 0, 1: 1, 2: 4, 3: 9, ..., 9: 81} print a_dict lst = ['a', 'b', 'c'] # You could opt to maintain a looping index... i = 0 for item in lst: print i, item i += 1 # ...but the enumerate function spares you the trouble of maintaining a loop index for i, item in enumerate(lst): print i, item Conceptually, Python functions accept lists of arguments that can be followed by additional keyword arguments. A common idiom that you'll see when calling functions is to dereference a list or dictionary with the asterisk or double-asterisk, respectively, a special trick for satisfying the function's parameterization. def f(a, b, c, d=None, e=None): print a, b, c, d, e f(1, 2, 3) # 1 2 3 None None f(1, 3, 3, d=4) # 1 2 3 4 None f(1, 2, 3, d=4, e=5) # 1 2 3 4 5 args = [1,2,3] kwargs = {'d' : 4, 'e' : 5} f(*args, **kwargs) # 1 2 3 4 5 It's often clearer in code to use string substitution than to concatenate strings, although both options can get the job done. The string type's built-in format function is also very handy and adds to the readability of code. The following examples illustrate some of the common string substitutions that you'll regularly encounter in the code. name1, name2 = "Bob", "Sally" print "Hello, " + name1 + ". My name is " + name2 print "Hello, %s. My name is %s" % (name1, name2,) print "Hello, {0}. My name is {1}".format(name1, name2) print "Hello, {0}. My name is {1}".format(*[name1, name2]) names = [name1, name2] print "Hello, {0}. My name is {1}".format(*names) print "Hello, {you}. My name is {me}".format(you=name1, me=name2) print "Hello, {you}. My name is {me}".format(**{'you' : name1, 'me' : name2}) names = {'you' : name1, 'me' : name2} print "Hello, {you}. My name is {me}".format(**names) Although great care has been taken to try and ensure that you won't have to use a secure shell to login to the virtual machine, there is great value in learning how to use an SSH client to login to a machine and be productive in a terminal session, and there will inevitably be times when you may need to troubleshoot on the virtual machine despite our best efforts. If you are already comfortable using a secure shell, you'll simply type vagrant ssh from the vagrant folder where your Vagrantfile is located, and you'll get automatically logged in if you have an SSH client already installed. If you are a Mac or Linux user, you will already have an SSH client installed and your remote login should "just work", but if you are a Windows user, you will likely not have an SSH client installed unless you're already using a tool like PuTTY or Git for Windows. In any event, if you've used an SSH client before, you'll have no troubles using vagrant ssh to perform a remote login. If you have not used an SSH client before, you won't necessarily need to learn to use one, but it might be in your overall best interest to learn how to use one at your leisure. Even without an SSH client, however, there are a couple of creative ways that you can use a Python script and IPython Notebook to give you much of the same functionality that you would achieve by performing a remote login to gain terminal access. The following sections introduce some of the possibilities. Although you're probably better off to configure and use an SSH client to login to the virtual machine most of the time, you could even interact with the virtual machine almost as though you are working in a terminal session using IPython Notebook and the envoy package, which wraps the subprocess package in a highly convenient way that allows you to run arbitrary commands and see the results. The following script shows how to run a few remote commands on the virtual machine (where this IPython Notebook server would be running if you are using the virtual machine). Even in situations where you are running a Python program locally, this package can be of significant convenience. import envoy # pip install envoy # Run a command just as you would in a terminal on the virtual machine r = envoy.run('ps aux | grep ipython') # show processes containing 'ipython' # Print its standard output print r.std_out # Print its standard error print r.std_err # Print the working directory for the IPython Notebook server print envoy.run('pwd').std_out # Try some commands of your own... An alternative to using the envoy package to interact with the virtual machine through what is called "Bash Cell Magic" in IPython Notebook. The way it works is that if you write %%bash on the first line of a cell, IPython Notebook will automatically take the remainder of the cell and execute it as a Bash script on the machine where the server is running. In case you come from a Windows background or are a Mac user who hasn't yet encountered Bash, it's the name of the default shell on most Linux systems, including the virtual machine that runs the IPython Notebook server. Assuming that you are using the virtual machine, this means that you can essentially write bash scripts in IPython Notebook cells and execute them on the server. The following script demonstrates some of the possibilities, including how to use a command like wget to download a file. %%bash # Print the working directory pwd # Display the date date # View the first 10 lines of a manual page for wget man wget | head -10 # Download a webpage to /tmp/index.html wget -O /tmp/foo.html # Search for 'ipython' in the webpage grep ipython /tmp/foo.html %%bash ls ../ # Displays the status of the local repository git status # Execute "git pull" to perform an update IPython Notebook has some handy features for interacting with the web browser that you should know about. A few of the features that you'll see in the source code are embedding inline frames, and serving static content such as images, text files, JavaScript files, etc. The ability to serve static content is especially handy if you'd like to display an inline visualization for analysis, and you'll see this technique used throughout the notebook. The following cell illustrates creating and embedding an inline frame and serving the static source file for this notebook, which is serialized as JSON data. from IPython.display import IFrame from IPython.core.display import display # IPython Notebook can serve files relative to the location of # the working notebook into inline frames. Prepend the path # with the 'files' prefix static_content = 'files/resources/appc-pythontips/hello.txt' display(IFrame(static_content, '100%', '600px')) The Vagrant virtual machine maps the top level directory of your GitHub checkout (the directory containing README.md) on your host machine to its /vagrant folder and automatically synchronizes files between the guest and host environments as an incredible convenience to you. This mapping and synchronization enables IPython Notebooks you are running on the guest machine to access files that you can conveniently manage on your host machine and vice-versa. For example, many of the scripts in IPython Notebooks may write out data files and you can easily access those data files on your host environment (should you desire to do so) without needing to connect into the virtual machine with an SSH session. On the flip side, you can provide data files to IPython Notebook, which is running on the guest machine by copying them anywhere into your top level GitHub checkout. In effect, the top level directory of your GitHub checkout is automatically synchronized between the guest and host environments so that you have access to everything that is happening and can manage your source code, modified notebooks, and everything else all from your host machine. See Vagrantfile for more details on how synchronized folders can be configured. The following code snippet illustrates how to access files. Keep in mind that the code that you execute in this cell writes data to the guest (virtual machine) environment, and it's Vagrant that automatically synchronizes it back to your guest environment. It's a subtle but important detail. import os # The absolute path to the shared folder on the VM shared_folder="/vagrant" # List the files in the shared folder print os.listdir(shared_folder) print # How to read and display a snippet of the share/README.md file... README = os.path.join(shared_folder, "README.md") txt = open(README).read() print txt[:200] # Write out a file to the guest but notice that it is available on the host # by checking the contents of your GitHub checkout f = open(os.path.join(shared_folder, "Hello.txt"), "w") f.write("Hello. This text is written on the guest but synchronized to the host by Vagrant") f.close() IPython Notebook's server kernels are ordinary Python processes that will use as much memory as they need to perform the computation that you give them. Most of the examples in this book do not entail consuming very large amounts of memory (the only notable exception could be Example 7-12 that builds a fairly large in-memory graph), but it's worth noting that most Vagrant boxes, including the default configuration for this book's virtual machine, have fairly low amounts of memory allocated to them by default. The amount of memory that's available for the "precise64" box that's used for these notebooks, for example, ships with a default of 334MB of memory that's allocated to it. Consequently, if any of your IPython Notebooks ever consume close to 334MB of memory, you'll reach the limit that's allocated to the guest virtual machine and the kernel will kill the offending Python process. Unfortunately, IPython Notebook isn't able to provide a clear indication of what's gone wrong in this case, so your only clue as to what may have happened is that you'll no longer see a "Kernel Busy" message in the upper-right corner of the screen, and your variables in the notebook become undefined because the IPython Notebook kernel that's servicing the notebook has effectively restarted. From within IPython Notebook, you can check the kernel log to see if there is any evidence that it killed your process with the following Bash command that displays the last 100 lines /var/log/kern.log %%bash tail -n 100 /var/log/kern.log You can increase the amount of memory that's available to your Vagrant box (and therefore to IPython Notebook) by including the following code snippet in your Vagrantfile as a provider-specific configuration option that specifies that the box should be allocated 768MB of memory: config.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", "768"] end While a long-running cell is executing, you can also take advantage of IPython Notebook's Bash cell magic to monitor the memory usage of processes by opening up a different notebook and executing the following code in its own cell. In the example below, we are specifying that we'd like to see a list of the top 10 processes and the amount of memory (in KB) that each process is using. %%bash ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS | tail -n 10 Again, the guidance offered here is fairly advanced advice that you may never need to use, but it the event that you suspect that you have a memory problem with a notebook, it'll be helpful You are free to use or adapt this notebook for any purpose you'd like. However, please respect the following Simplified BSD License (also known as "FreeBSD License") that governs its use. Basically, you can do whatever you want with the code so long as you retain the copyright notice. FreeBSD Project.
https://nbviewer.jupyter.org/github/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/v2.0/ipynb/_Appendix%20C%20-%20Python%20%26%20IPython%20Notebook%20Tips.ipynb
CC-MAIN-2018-13
refinedweb
3,280
56.49
The Questions What is Props? Props represents data. Props allow a component to receive data from its parent component. Why do we use Props? We use Props because React is a component-based library. React separates the user interface of an application into individual pieces, known as Components. Those components need to send data to each other and they do so, using props. How can we use Props? To use Props effectively, consider these steps: - Create a parent component that renders some JSX. class Parent extends React.Component{ render(){ return( <h1>Parent</h1> ) } } - Create a child component. const Child = () => { return <h3>I'm a child!</h3> } - Import the child component in the parent component. import Child from './Child' class Parent extends React.Component{ render(){ return( <h1>Parent</h1> ) } } - Pass in Props into the child component as a parameter. const Child = (props) => { return <h3>I'm a child!</h3> } - Render the child component in the parent component. class Parent extends React.Component{ render(){ return( <> <h1>Parent</h1> <Child text={"Child!"}/> </> ) } } - Render the Props in the child component using string interpolation. const Child = (props) => { return <h3>{props.text}</h3> } The Rules - Props can only be sent from parent component to child component (This is called "unidirectional flow"). - Props are immutable, meaning they cannot be changed. - Props is an object. - Props represents data. - Props are being passed down to components as a parameter. Conclusion We use props to pass data between components. The ability to pass data in this manner makes application development more efficient and makes your code more DRY. Props is a special feature to ReactJS and continues to prove the ever-evolving nature of tech. Let's continue to evolve with it! Comment below + let's start a conversation. Thanks for reading! Top comments (0)
https://dev.to/am20dipi/the-questions-and-the-rules-to-props-3ahn
CC-MAIN-2022-40
refinedweb
295
54.9
Filter::Simple - Simplified source filtering # in MyFilter.pm: package MyFilter; use Filter::Simple; FILTER { ... }; # or just: # # use Filter::Simple sub { ... }; # in user's code: use MyFilter; # this code is filtered no MyFilter; # this code is not Source filtering is an immensely powerful feature of recent versions of Perl. It allows one to extend the language itself (e.g. the Switch module), to simplify the language (e.g. Language::Pythonesque), or to completely recast the language (e.g. Lingua::Romana::Perligata). Effectively, it allows one to use the full power of Perl as its own, recursively applied, macro language. The excellent Filter::Util::Call module (by Paul Marquess) provides a usable Perl interface to source filtering, but it is often too powerful no BANG; statement, if any): package BANG; use Filter::Util::Call ; sub import { filter_add( sub { my $caller = caller; my ($status, $no_seen, $data); while ($status = filter_read()) { if (/^\s*no\s+$caller\s*;\s*?$/) { $no_seen=1; last; } $data .= $_; $_ = ""; } $_ = $data; s/BANG\s+BANG/die 'BANG' if \$BANG/g unless $status < 0; $_ .= "no $class;\n" if $no_seen; return 1; }) } sub unimport { filter_del(); } 1 ; This level of sophistication puts filtering out of the reach of many programmers.__. "executable" Filters only those sections of the source code that are not POD. For example, here's a simple macro-preprocessor that is only applied within regexes, with a final debugging pass that prints the resulting source code: use Regexp::Common; FILTER_ONLY regex => sub { s/!\[/[^/g }, regex => sub { s/%d/$RE{num}{int}/g }, regex => sub { s/%f/$RE{num}{real}/g }, all => sub { print if $::DEBUG }; Most source code ceases to be grammatically correct when it is broken up into the pieces between string literals and regexes. So the 'code' component filter behaves slightly differently from the other partial filters described in the previous section. Rather than calling the specified processor on each individual piece of code (i.e. on the bits between quotelikes), the 'code' partial filter operates on the entire source code, but with the quotelike bits . Placeholders can be moved and re-ordered within the source code as needed. Once the filtering has been applied, the original strings, regexes, POD, etc. are re-inserted into the code, by replacing each placeholder with the corresponding original component. For example, the following filter detects concatent import subroutine passes its own argument list to the filtering subroutine, so the BANG.pm filter could easily be made parametric: package BANG; use Filter::Simple; FILTER { my ($die_msg, $var_name) = @_; s/BANG\s+BANG/die '$die_msg' if \${$var_name}/g; }; # and in some user code: use BANG "BOOM", "BAM"; # "BANG BANG" becomes: die 'BOOM' if $BAM The specified filtering subroutine is called every time a (damian@conway.org) Copyright (c) 2000-2001, Damian Conway. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
http://search.cpan.org/~jhi/perl-5.8.0/lib/Filter/Simple.pm
CC-MAIN-2016-26
refinedweb
483
55.44
With Fauna’s document streaming feature, you can get real-time updates about changes made to your database. In this tutorial, you will learn how to use Fauna’s document streaming feature in a Python application. Here for the code alone? Head over to the implementation section of this article. Introduction What is Streaming? Streaming refers to when a program continuously reads and fetches data from a given source in real-time. For example, while watching a YouTube video or downloading a file from the internet, you stream the data from the origin and process it on your client’s device instantaneously. Streaming, in some ways, can arguably be a better alternative to polling. Polling refers to when a client periodically makes queries to a data source to get updates. It is more expensive than streaming as the client sends many requests only to get a single update or none at all. Polling is only aware of changes when the query results return. What is Fauna? Fauna is a flexible database delivered as a secure data API providing two interfaces: GraphQL and the Fauna Query Language (FQL). It offers functionality to store collections, indexes, and other databases. To learn more about Fauna, visit the official documentation. NOTE: The rest of this article assumes you have a fair understanding of Fauna and Python. Check out my introductory tutorial first if you don't. Setting up our Fauna database Creating the Fauna database We need to first create the database to use in Fauna’s dashboard. If you have not created an account on Fauna before now, do so here. In the dashboard, click on the NEW DATABASE button, provide a name for the database, then press SAVE. We will also be ticking the Pre-populate option to get demo data that will be used in this article: Generate the database security key Then, we need to create a security key to connect the database to the application. Go to the Security tab on the Fauna sidebar (located on the left side of the screen), click the NEW KEY button, provide the necessary information, and press SAVE: Fauna will then present you with your Secret Key. Copy the key immediately and store it somewhere easily retrievable because it will only be displayed once. Implementing document streaming with Python Fauna features built-in support for document streaming. Whenever changes in a particular document are streamed, all the clients subscribed to it will be notified in real-time. Initializing our Fauna client Let’s write some code to implement this functionality!. First, we will install the Fauna Python driver, importing the required libraries, and creating a database client. In the terminal, type: pip install faunadb After that, create a Python script and save the code below in it: from faunadb import query as q from faunadb.objects import Ref from faunadb.client import FaunaClient client = FaunaClient(secret="FAUNA_SECRET_KEY") Selecting a document to stream Next, we will fetch the document from the Fauna database collections that we want to stream: doc = client.query( q.get( q.ref(q.collection("customers"), "101") ) ) Creating an OnStart function We will start by defining an on_start function, which will be triggered when a document stream starts: def on_start(event): print(f"started stream at {event.txn}") data = { "firstName": "John", "lastName": "Smith", "telephone": "719-872-4470" } client.query(q.update(doc["ref"], {"data": data})) In our on_start function, we printed out the current timestamp of the transaction emitting the event (in microseconds) provided by event.txn. Then, the streamed document, so Fauna notifies our application in real-time. Creating an OnVersion function Next, we will define an on_version function. It will be triggered when there is a change in the streamed document and Fauna has sent a notification to the subscribing application: def on_version(event): print(f"on_version event at {event.txn}") print(f"Event action: {event.event['action']}") print(f"Changes made: {event.event['diff'].get('data')}") In our on_version function, we printed out the current timestamp again (in microseconds), then printed out the event action provided by event.event['action']. We then printed out the changes made to the document. Creating an OnError function After that, we will define an on_error function. It will be triggered when an error occurs while processing the data in the on_version: def on_error(event): print(f"Received error event {event}") In our on_error function, we printed out the event that triggered the issue along with its error message. Starting the document streaming We will now begin document streaming: options = {"fields": ["document", "diff", "action"]} stream = client.stream(doc["ref"], options, on_start, on_error, on_version) stream.start() In the code above, we defined the fields we want in every event update. Then, we passed the on_start, on_error, and on_version functions to the stream object and triggered it with the start method. You should get an image like the one below when the entire script executes: NOTE: You can stop active streams using the stream.close()method. A few things to note At the time of writing, Fauna’s document streaming is still an Early Access feature. Hence there are some limitations to using it, such as: - You cannot have more than 100 active stream connections to Fauna from a single client device. - Document streaming is currently not supported in Node.js clients due to an HTTP/2 implementation issue. - You can only stream Fauna documents. It is not possible to stream collections or any schema document. - Streams can only report events to the fields and values within a document’s datafield. - There is currently no support for GraphQL subscriptions. Conclusion In this article, we learned about Fauna’s document streaming capabilities and how easy it is to integrate Fauna’s document streaming into a Python application. You can learn more about Fauna document streaming from the official documentation. If you have any questions, don't hesitate to contact me on Twitter: @LordGhostX. Top comments (0)
https://dev.to/lordghostx/streaming-fauna-documents-with-python-18c3
CC-MAIN-2022-40
refinedweb
990
55.54
Basics of NumPy Arrays Part – 1 Hello Enthusiastic Learners! Its time to learn Basics of NumPy Arrays. Arrays are the base of everything, since everything in our computer are numbers, all of them are being processed via an Array. When it comes to effective data processing and data manipulation, NumPy is one of the key libraries to get results in most efficient way. Even library “Pandas” is built around NumPy. So, it is good to have good knowledge of basics of NumPy arrays. For more basics of NumPy arrays & good introduction to it, visit our article Introduction to NumPy Some of the things that we will cover in this article are: - Array Attributes – Shape, size, data types & more. - Slicing of Arrays – Accessing sub-arrays from larger arrays - Array Indexing – Accessing array elements NumPy Array Attributes Attributes of an array corresponds to – its sieze, dimensions, size of each dimension & data type of values stroed in array. We will learn all this with help of few examples. Before we jump on to creating arrays with random number, a little about random number genrator “seed”. SEED – while genrating random numbers if we want eveytime same sequence of random numbers must be generated then we provide a value called “SEED” which when kept same for every run will make sure that same sequence is generated. Now, we will create few Arrays. Importing libraries import numpy as np # seed for reproducing same random number sequence np.random.seed(10) # 1 dimensional Array a1 = np.random.randint(5, size=10) # it will create a 1 dimensional array having 10 values and all below 5 a1 array([1, 4, 0, 1, 3, 4, 1, 0, 1, 2]) # @ dimensional Array a2 = np.random.randint(5, size=(2,10)) # it will create a 2 dimensional array having 10 values in each row and all below 5 a2 array([[0, 1, 0, 2, 0, 4, 3, 0, 4, 3], [0, 3, 2, 1, 0, 4, 1, 3, 3, 1]]) # @ dimensional Array a3 = np.random.randint(5, size=(3, 2, 10)) # it will create a 3 dimensional array having 10 values in each row all below 5 # In each dimension there will be 2 rows a3 array([[[4, 1, 4, 1, 1, 4, 3, 2, 0, 3], [4, 2, 0, 1, 2, 0, 0, 3, 1, 3]], [[4, 1, 4, 2, 0, 0, 4, 4, 0, 0], [2, 4, 2, 0, 0, 2, 3, 0, 4, 4]], [[0, 1, 1, 4, 0, 2, 1, 3, 1, 2], [0, 1, 1, 0, 2, 3, 0, 4, 2, 0]]]) Fetching attributes of arrays Let’s fetch attributes for above arrays: - ndim – number of dimensions in each array - shape – dimensions - size – total number of elements in array - dtype – data type of array elemets (in current case it will be int64 only, as we used randint which genrated int type values only) print("a1.ndim \t= '" + str(a1.ndim) + "' dimension(s) in array") print("a1.shape \t= '" + str(a1.shape) + "' -- single row with 10 elements each") print("a1.size \t= '" + str(a1.size) + "' -- total elements in array") print("a1.dtype \t= '" + str(a1.dtype) + "' type data in array") a1.ndim = '1' dimension(s) in array a1.shape = '(10,)' -- single row with 10 elements each a1.size = '10' -- total elements in array a1.dtype = 'int64' type data in array print("a2.ndim \t= '" + str(a2.ndim) + "' dimension(s) in array") print("a2.shape \t= '" + str(a2.shape) + "' 2 rows with 10 elements each") print("a2.size \t= '" + str(a2.size) + "' -- total elements in array") print("a2.dtype \t= '" + str(a2.dtype) + "' type data in array") a2.ndim = '2' dimension(s) in array a2.shape = '(2, 10)' 2 rows with 10 elements each a2.size = '20' -- total elements in array a2.dtype = 'int64' type data in array print("a3.ndim \t= '" + str(a3.ndim) + "' dimension(s) in array") print("a3.shape \t= '" + str(a3.shape) + "' 3 dimensions, 2 rows in each dimension with 10 elements each") print("a3.size \t= '" + str(a3.size) + "' -- total elements in array") print("a3.dtype \t= '" + str(a3.dtype) + "' type data in array") a3.ndim = '3' dimension(s) in array a3.shape = '(3, 2, 10)' 3 dimensions, 2 rows in each dimension with 10 elements each a3.size = '60' -- total elements in array a3.dtype = 'int64' type data in array Fetching size of array If you want to get size of array & its element in bytes you can use following functions: - itemsize – size of each element of array in bytes - nbytes – size of complete array in bytes print("Size of each item in bytes \t= " + str(a3.itemsize)) print("Size of array in bytes \t = " + str(a3.nbytes)) Size of each item in bytes = 8 Size of array in bytes = 480 You can also check-out same tutorial in Video Format below Accessing array elements (Array Indexing) Here is our 1 dimensional array: a1 array([1, 4, 0, 1, 3, 4, 1, 0, 1, 2]) Fetching first element of array use following command: a1[0] 1 Get 5th element by using the code below: a1[4] 3 Due to what we read so far, we can say to access nth element we use array[n-1] One can use negative values for indexing (or traversing) array from end. In order to access last element of array we can use following: a1[-1] 2 For fetching 5th element from behind: a1[-5] 4 Certainly, for multi-dimension array, we can access values by adding a comma (,). Here is our 2 dimensional array: a2 array([[0, 1, 0, 2, 0, 4, 3, 0, 4, 3], [0, 3, 2, 1, 0, 4, 1, 3, 3, 1]]) Below code fetches 1st element: a2[0,0] 0 Accessing 3rd element from 2nd row of array: a2[1,2] 2 Similarly, you can traverse 2 dimensional array as well from behind. For getting 2nd last element from 2nd row of array: a2[-1, -2] 3 To access 2nd last element from 1st row of array: a2[-2, -2] 4 Slicing of Arrays We will be accessing sub arrays from larger arrays. Hence, it is very important to learn that how we can access sub elements from an array because in many situations like while sampling data we need to fetch smaller data or sample from given data. Above all, the syntax for slicing arrays is as follows: x[ start : stop : step ] - start – Starting position, from which we will start accessing values from larger array. Default value start = 0. - stop – Last position in array till which you want to get values from larger array. Default value stop = size of dimension. - step – as discussed in our article “Introduction to NumPy“, step is the value by which we are skipping values. Default value step = 1. Slicing on 1-Dimensional Array Let’s proceed with creating an array. x = np.arange(11) x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Access first 4 elements x[ : 4] array([0, 1, 2, 3]) Note: Element at “stop” position is not included Further, One can access elements after 4th element x[ 4 : ] array([ 4, 5, 6, 7, 8, 9, 10]) Fetch elements 4th to 8th element x[ 4 : 8 ] array([4, 5, 6, 7]) All elements skipping 2 values, like 0, 3, 6, 9. For this we will step = 3 x[ : : 3 ] array([0, 3, 6, 9]) All elements skipping 1 value and values starting from 4th element. x[ 3 : : 2 ] array([3, 5, 7, 9]) Using negative steps Yes, negative STEP values are also allowed. In this case default values of start & stop value are swapped. Therefore, we will receive an array in reverse order. All elements skipping 1 value and values starting from 8th element from end. x[ 8 : : -2 ] array([8, 6, 4, 2, 0]) You can also use this technique to reverse an array. x[ : : -1] array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) Slicing on Multi-Dimensional Array Let’s proceed with creating an array. x = np.arange(20).reshape(4,5) x array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) reshape(rows, elements) reshape is used to reshape our larger array as per rows & elements provided in reshape() function. First of all, let’s fetch first 2 rows and 4 columns x[ : 2, : 4 ] array([[0, 1, 2, 3], [5, 6, 7, 8]]) Also, we can fetch first 2 rows and 4 columns with STEP=2 on column values. x[ : 2, : 4 : 2] array([[0, 2], [5, 7]]) Reversing multi-dimensional array x[: : -1, : : -1] array([[19, 18, 17, 16, 15], [14, 13, 12, 11, 10], [ 9, 8, 7, 6, 5], [ 4, 3, 2, 1, 0]]) So far, we have covered many powerful functionalities of NumPy Arrays. Practice them and also play around with steps and multi-dimensional array. Further, we will be providing more in-depth knowledge in our next article “Basics of Numpy Array Part-2” Stay tuned. Keep Learning! Also, for video tutorials check our YouTube channel ML for Analytics 5 thoughts on “Basics of NumPy Arrays Part – 1”
https://mlforanalytics.com/2020/03/28/basics-of-numpy-arrays-part-1/
CC-MAIN-2021-21
refinedweb
1,525
62.27
Components in JavaScript This series is about how the Kibana team is componentizing the Kibana UI. In the last post in this series, I outlined how we've been applying this process to Kibana's CSS. But components are more than just CSS -- they're JavaScript, too. We went looking for a JS library to help us, and when we came upon React we found it to be a natural fit! React is a library for building user interfaces with JavaScript, open-sourced by Facebook in 2015. In React everything is a component. This is the same fundamental principle which drives our componentization process. According to the React documentation site, React allows you to “build encapsulated components that manage their own state, then compose them to make complex UIs.” Let’s explore these ideas in the context of our UI Framework. Encapsulation lets us hide complexity Engineers should be able to wield a UI Framework component like an artist wields a brush. You should be able to apply it to a medium and, with a little skill, expect a positive result. As a corollary, an engineer who’s using a component shouldn’t have to worry about how the component works underneath the hood. Implementation details should be encapsulated, hidden from view. This includes JavaScripty things like state and performance optimizations, but it also means that entire layers of our stack become invisible. The very markup and CSS that make up our components become implementation details, which are encapsulated by our React components. For example, take a look at how we converted our Button component to React (check out the pull request if you're interested in the details). Here’s what the component looked like originally: <button class="kuiButton kuiButton--basic"> Basic button </button> We just wrapped this markup inside of a React component, like so: const KuiButton = ({ className, type, children, }) => { return ( <button className={getClassName({ className, type, })} > {children} </button> ); }; And now engineers can use this component like this: <KuiButton type="basic" onClick={() => window.alert('Button clicked')} > Basic button </KuiButton> By relegating the actual CSS and markup to mere implementation details, we gain three big advantages: - The code that represents a user interface becomes more readable and succinct. - Engineers no longer need to remember class names and specific markup. Instead, they can focus on wiring the UI with event handlers and business logic to bring the UI to life. This means greater code consistency, fewer hacks and custom solutions, and a faster development cycle. - Engineers who maintain the UI Framework gain a greater degree of freedom when refactoring components -- we can rename classes and restructure a component’s markup without worrying about disrupting someone else’s workflow. Componentization means composition Good components can be defined by many traits. They should be modular, reusable, and ideally adhere to the single responsibility principle. But great components are also composable. This means that many components can be thought of as simple containers, into which any other component or number of components can be injected. In the previous blog post in this series, I raised the example of a Panel component. This component is just a box with a title. And like any box, it can contain literally anything: text, buttons, a table, or even other Panels. A component is composable when it exhibits this level of flexibility. The process of componentizing our user interfaces largely consists of figuring out how to compose them out of components. When we look at a complex user interface that needs to be broken apart into components, we start by looking for the containers. And typically, these are the UI elements that become we can extract into components in our UI Framework. By following this simple process, we end up with an ecosystem of components which can be reused and composed together to create complex UIs. React emphasizes composition as a first-class concept. It encourages component developers to design components to be stateless and functional. This results in components which accept dependencies, most notably the children dependency. React supports composition by allowing you to provide components as the children dependencies of other components. The React team has written a terrific article on how they designed React with composition in mind, entitled “Composition vs Inheritance”. If you’re getting started with React, I highly recommend you check it out. I should mention that I also love stateless, functional React components because they’re so easy to demonstrate in the UI Framework. In fact, I copied the above KuiButton code snippet from our UI Framework documentation site. Unlike an AngularJS directive, which would require creating an Angular app, registering the directive to it, and creating a template in which to declare an instance of the directive, there’s very little overhead required to instantiate a React component. You just import it and instantiate it with whatever JavaScript dependencies it requires. This also makes React components very easy to unit test. We use AirBnB’s Enzyme to render an HTML string of the component, and then we use Facebook's Jest to save this string as a snapshot, and compare it against subsequent renders. Here’s what a test would look like: import React from 'react'; import { render } from 'enzyme'; import { KuiButton } from './button'; describe('KuiButton is rendered', () => { const $button = render( <KuiButton> Hello </KuiButton> ); expect($button) .toMatchSnapshot(); }); This would render a snapshot which looks like this: exports[`KuiButton Baseline is rendered 1`] = ` <button class="kuiButton" > <span class="kuiButton__inner" > <span> Hello </span> </span> </button> `; This snapshot is committed to the repo. During subsequent executions of our UI Framework test suite, Jest will detect that the snapshot exists and compare Enzyme’s output against it. If the output doesn’t match the snapshot, we’ll see a diff in the terminal with some helpful error messages. When this happens, we can either decide that our changes to the component are ones we want to preserve, in which case we’ll update the snapshot with the latest output, or we’ll realize we made a mistake and fix the component so that the test’s pass. Looking ahead We’re just getting started with the transition to React. If you’d like to follow our progress, drop in on our React-related GitHub Issues and see what’s in the works. We also created an open-source React Design Workshop to help ourselves and others get started with React. Feel free to run through it and make suggestions on ways we can make it better! Next up: Designing systems In the next and final post, I’ll share the thrilling secret of how we’ve applied componentization to our actual design process, so that we end up creating design systems instead of just static mockups. Interested in joining our team? Well, we’re interested in you, too. Come say hi!
https://www.elastic.co/blog/componentizing-the-kibana-ui-writing-javascript-with-react
CC-MAIN-2019-26
refinedweb
1,137
53