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
Hi there, How did you make Dev C++ 4 work in Vista? I tried both 4 and 5 in my Vista, and they don't work out. I will appreciate it greatly! Printable View Hi there, How did you make Dev C++ 4 work in Vista? I tried both 4 and 5 in my Vista, and they don't work out. I will appreciate it greatly! This thread was a post moved from I need C++ Compiler for MS Windows Vista. If you want to use Dev-C++, use version 5 (or rather, 4.9.9.2). If that does not work, try the MinGW port of g++, which is the compiler used by Dev-C++ by default. If that works, you can use it with some other IDE, e.g., Code Blocks, Eclipse or Netbeans. If not, MSVC9 (from Microsoft Visual C++ 2008) is your best bet. Hi, Can you define work in more detail? 1) it will not load? 2) when it is loaded, it will not open enviroment? 3) i cannot compile my code? If it installs fine, make sure when the icon pops up on desktop, right click on it, (um cant remember this bit exactly), but there is a compatable mode, select this and select xp mode. After this step it should run ok. Hope this helps. I had a problem compiling on Vista. Turns out saving the code in MyDocuments caused the error. I don't know if this is the problem, but hope it helps a little. Hi, Ok here is a long shot, i was using my embedded c compiler when vista first came out and i could not update my txt.c file when i ran or compiled my code. The solution was to go to my folder in my documents, right click on the folder and change the security paramerters on it - i think it could only read and not write to this folder. When i had changed this, it worked fine - vista has more security fetures over xp. As i said this is a long shot, but since that happened i have changed the security setting of my code folder and all seems ok with dev-c++ as well as my embedded c compiler. Hope this helps. tuurbo46 I am using the Visual C++ compiler Alternatively, run the app as admin to avoid this crap altogether. You can set run as admin on the compability tab in the properties. Or you should save to a directory you have write permission to - like your documents folder. Or %AppPath%. Hi. I didn't find any post that could help me with my problem, even a simple program like this, i still can't it get to work. I've tried some compilers that can't compile the same code, everyone of them use "their own way of writing c++" i don't understand why that's so, still i tried to compile this one, i got this as a result.i got this as a result.Code: #include <iostream> int main() { std::cout << "Hello world!" << std::endl; return 0; } File Line Message main.cpp 1 iostream: No such file or directory main.cpp 5 error: `cout' is not a member of `std' main.cpp 5 error: `endl' is not a member of `std' Could anyone at least tell me what was wrong? (im using windows wista, Code::Blocks v1.0) and i heard something about libstdc, but dont really get it how to get that to work. I'm not familiar with codeblocks - but you have somewhere to specify the include files location, currently compiler is not able to find a file iostream Thank you, that tells at least something ^_^ When I installed Dev-C++ 4.9.9.something under Vista, it didn't set the PATH, even though I ran the installer as the administrator. If you were getting errors to the effect that gcc/g++ could not be executed, you're likely having the same problem. To do it manually, do something like this: - Click start. - Right-click on Computer, and click properties. - Choose Advanced settings, or something -- it's a hard-to-see link on the left hand side of the screen. It's the last link in the list, I believe. - Choose the Environment Variables tab, or something. - Add ;C:\Dev-C++\Bin to the end of the PATH variable. The path is to Dev-C++, (i got that compiler to) but i used CodeBlocks (If wondering why, i tried to fix the SDL thing, but it doesn't work, can't even compile) Wait -- you're trying to get SDL programs to compile? That's a bit tougher. I suggest you try reading this: However, there is a DevPak for the SDL that makes installing the SDL under Dev-C++ a cinch. Or so I hear. You might want to have a look at it. Well, thanks for that, was on that site, and SDL are working ^_^
http://cboard.cprogramming.com/cplusplus-programming/97875-does-dev-cplusplus-4-even-work-vista-printable-thread.html
CC-MAIN-2016-40
refinedweb
833
82.65
Overview. Hello and welcome! 🎉. Instructors Dave Cheney dave@cheney.net License and Materials This workshop is a collaboration between David Cheney and Francesc Campoy. This presentation is licensed under the Creative Commons Attribution-ShareAlike 4.0 International licence. Prerequisites The are several software downloads you will need today. The workshop repository Download the source to this document and code samples at Go 1.13 The workshop material targets Go 1.13. This is currently available in beta. Graphviz The section on pprof requires the dot program which ships with the graphviz suite of tools. Google Chrome The section on the execution tracer requires Google Chrome. It will not work with Safari, Edge, Firefox, or IE 4.01. Please tell your battery I’m sorry. Your own code to profile and optimise The final section of the day will be an open session where you can experiment with the tools you’ve learnt. One more thing … This isn’t a lecture, it’s a conversation. We’ll have lots of breaks to ask questions. If you don’t understand something, or think what you’re hearing not correct, please ask. 1. The past, present, and future of Microprocessor performance This is a workshop about writing high performance code. In other workshops I talk about decoupled design and maintainability, but we’re here today to talk about performance. I want to start today with a short lecture on how I think about the history of the evolution of computers and why I think writing high performance software is important. The reality is that software runs on hardware, so to talk about writing high performance code, first we need to talk about the hardware that runs our code. 1.1. Mechanical Sympathy There is a term in popular use at the moment, you’ll hear people like Martin Thompson or Bill Kennedy talk about “mechanical sympathy”. The name "Mechanical Sympathy" comes from the three time Formula 1 champion, Jackie Stewart. Stewart believed that the best drivers had to understand the mechanics of their vehicle so they could work in harmony with it. To be a great race car driver, you don’t need to be a great mechanic, but you need to have more than a cursory understanding of how a motor car works. I believe the same is true for us as software engineers. I don’t think any of us in this room will be a professional CPU designer, but that doesn’t mean we can ignore the problems that CPU designers face. 1.2. Six orders of magnitude There’s a common internet meme that goes something like this; Of course this is preposterous, but it underscores just how much has changed in the computing industry. As software authors all of us in this room have benefited from Moore’s Law, the doubling of the number of available transistors on a chip every 18 months, for 40 years. No other industry has experienced a six order of magnitude [1] improvement in their tools in the space of a lifetime. But this is all changing. 1.3. Are computers still getting faster? So the fundamental question is, confronted with statistic like the ones in the image above, should we ask the question are computers still getting faster? If computers are still getting faster then maybe we don’t need to care about the performance of our code, we just wait a bit and the hardware manufacturers will solve our performance problems for us. 1.3.1. Let’s look at the data This is the classic data you’ll find in textbooks like Computer Architecture, A Quantitative Approach by John L. Hennessy and David A. Patterson. This graph was taken from the 5th edition. Hennessey and Patterson argue that there are five distinct eras of computing performance The first was the 1970’s and early 80’s which was the formative years. Microprocessors as we know them today didn’t really exist, computers were built from discrete transistors or small scale integrated circuits. Cost, size, and the limitations in the understanding of material science were the limiting factor. From the mid 80s to 2004 the trend line is clear. Computer integer performance improved on average by 52% each year. Computer power doubled every two years, hence people conflated Moore’s law — the doubling of the number of transistors on a die, with computer performance. Then we come to the third era of computer performance. Things slow down. The aggregate rate of change is 22% per year. The fourth, and fifth continue that trend, dropping to 9.3% and 2.5% per year respectively. Different versions of the Hennessey and Patterson data that you find online stops between 2012 and 2015. Fortunately in 2012 Jeff Preshing wrote a tool to scrape the Spec website and build your own graph. So this is the same graph using Spec data from 1995 til 2017. This graph is over a shorter timespan, but confirms Hennessey and Patterson’s results. The numbers are slightly better for floating point, but for us in the room doing line of business applications, this is probably not that relevant. 1.3.2. Yes, computer are still getting faster, slowly The first thing to remember about the ending of Moore’s law is something Gordon Moore told me. He said "All exponentials come to an end". — John Hennessy This is Hennessy’s quote from Google Next 18 and his Turing Award lecture. His contention is yes, CPU performance is still improving. However, single threaded integer performance is still improving around 2-3% per year. At this rate its going to take 20 years of compounding growth to double integer performance. Compare that to the go-go days of the 90’s where performance was doubling every two years. Why is this happening? 1.4. Clock speeds This graph from 2015 demonstrates this well. The top line shows the number of transistors on a die. This has continued in a roughly linear trend line since the 1970’s. As this is a log/lin graph this linear series represents exponential growth. However, If we look at the middle line, we see clock speeds have not increased in a decade, we see that cpu speeds stalled around 2004 The bottom graph shows thermal dissipation power; that is electrical power that is turned into heat, follows a same pattern—clock speeds and cpu heat dissipation are correlated. 1.5. Heat Why does a CPU produce heat? It’s a solid state device, there are no moving components, so effects like friction are not (directly) relevant here. This digram is taken from a great data sheet produced by TI. In this model the switch in N typed devices is attracted to a positive voltage P type devices are repelled from a positive voltage. The power consumption of a CMOS device, which is what every transistor in this room, on your desk, and in your pocket, is made from, is combination of three factors. Static power. When a transistor is static, that is, not changing its state, there is a small amount of current that leaks through the transistor to ground. The smaller the transistor, the more leakage. Leakage increases with temperature. Even a minute amount of leakage adds up when you have billions of transistors! Dynamic power. When a transistor transitions from one state to another, it must charge or discharge the various capacitances it is connected to the gate. Dynamic power per transistor is the voltage squared times the capacitance and the frequency of change. Lowering the voltage can reduce the power consumed by a transistor, but lower voltages causes the transistor to switch slower. Crowbar, or short circuit current. We like to think of transistors as digital devices occupying one state or another, off or on, atomically. In reality a transistor is an analog device. As a switch a transistor starts out mostly off, and transitions, or switches, to a state of being mostly on. This transition or switching time is very fast, in modern processors it is in the order of pico seconds, but that still represents a period of time when there is a low resistance path from Vcc to ground. The faster the transistor switches, its frequency, the more heat is dissipated. 1.6. The end of Dennard scaling To understand what happened next we need to look to a paper written in 1974 co-authored by Robert H. Dennard. Dennard’s Scaling law states roughly that as transistors get smaller their power density stays constant. Smaller transistors can run at lower voltages, have lower gate capacitance, and switch faster, which helps reduce the amount of dynamic power. So how did that work out? It turns out not so great. As the gate length of the transistor approaches the width of a few silicon atom, the relationship between transistor size, voltage, and importantly leakage broke down. It was postulated at the Micro-32 conference in 1999 that if we followed the trend line of increasing clock speed and shrinking transistor dimensions then within a processor generation the transistor junction would approach the temperature of the core of a nuclear reactor. Obviously this is was lunacy. The Pentium 4 marked the end of the line for single core, high frequency, consumer CPUs. Returning to this graph, we see that the reason clock speeds have stalled is because cpu’s exceeded our ability to cool them. By 2006 reducing the size of the transistor no longer improved its power efficiency. We now know that CPU feature size reductions are primarily aimed at reducing power consumption. Reducing power consumption doesn’t just mean “green”, like recycle, save the planet. The primary goal is to keep power consumption, and thus heat dissipation, below levels that will damage the CPU. But, there is one part of the graph that is continuing to increase, the number of transistors on a die. The march of cpu features size, more transistors in the same given area, has both positive and negative effects. Also, as you can see in the insert, the cost per transistor continued to fall until around 5 years ago, and then the cost per transistor started to go back up again. Not only is it getting more expensive to create smaller transistors, it’s getting harder. This report from 2016 shows the prediction of what the chip makers believed would occur in 2013; two years later they had missed all their predictions, and while I don’t have an updated version of this report, there are no signs that they are going to be able to reverse this trend. It is costing intel, TSMC, AMD, and Samsung billions of dollars because they have to build new fabs, buy all new process tooling. So while the number of transistors per die continues to increase, their unit cost has started to increase. 1.7. More cores With thermal and frequency limits reached it’s no longer possible to make a single core run twice as fast. But, if you add another cores you can provide twice the processing capacity — if the software can support it. In truth, the core count of a CPU is dominated by heat dissipation. The end of Dennard scaling means that the clock speed of a CPU is some arbitrary number between 1 and 4 Ghz depending on how hot it is. We’ll see this shortly when we talk about benchmarking. 1.8. Amdahl’s law CPUs are not getting faster, but they are getting larger with hyper threading and multiple cores. Dual core on mobile parts, quad core on desktop parts, dozens of cores on server parts. Will this be the future of computer performance? Unfortunately not. Amdahl’s law, named after the Gene Amdahl, the cheif architect of the IBM/360 series, is a formula which gives the theoretical speedup in latency of the execution of a task at fixed workload that can be expected of a system whose resources are improved. Amdahl’s law tells us that the maximum speedup of a program is limited by the sequential parts of the program. If you write a program with 95% of its execution able to be run in parallel, even with thousands of processors the maximum speedup in the programs execution is limited to 20x. Think about the programs that you work on every day, how much of their execution is parallelisable? 1.9. Dynamic Optimisations With clock speeds stalled and limited returns from throwing extra cores at the problem, where are the speedups coming from? They are coming from architectural improvements in the chips themselves. These are the big five to seven year projects with names like Nehalem, Sandy Bridge, and Skylake. Much of the improvement in performance in the last two decades has come from architectural improvements: 1.9.1. Out of order execution Out of Order, also known as super scalar, execution is a way of extracting so called Instruction level parallelism from the code the CPU is executing. Modern CPUs effectively do SSA at the hardware level to identify data dependencies between operations, and where possible run independent instructions in parallel. However there is a limit to the amount of parallelism inherent in any piece of code. It’s also tremendously power hungry. Most modern CPUs have settled on six execution units per core as there is an n squared cost of connecting each execution unit to all others at each stage of the pipeline. 1.9.2. Speculative execution Save the smallest micro controllers, all CPUs utilise an instruction pipeline to overlap parts of in the instruction fetch/decode/execute/commit cycle. The problem with an instruction pipeline is branch instructions, which occur every 5-8 instructions on average. When a CPU reaches a branch it cannot look beyond the branch for additional instructions to execute and it cannot start filling its pipeline until it knows where the program counter will branch too. Speculative execution allows the CPU to "guess" which path the branch will take while the branch instruction is still being processed! If the CPU predicts the branch correctly then it can keep its pipeline of instructions full. If the CPU fails to predict the correct branch then when it realises the mistake it must roll back any change that were made to its architectural state. As we’re all learning through Spectre style vulnerabilities, sometimes this rollback isn’t as seamless as hoped. Speculative execution can be very power hungry when branch prediction rates are low. If the branch is misprediction, not only must the CPU backtrace to the point of the misprediction, but the energy expended on the incorrect branch is wasted. All these optimisations lead to the improvements in single threaded performance we’ve seen, at the cost of huge numbers of transistors and power. 1.10. Modern CPUs are optimised for bulk operations Modern processors are a like nitro fuelled funny cars, they excel at the quarter mile. Unfortunately modern programming languages are like Monte Carlo, they are full of twists and turns. — David Ungar This a quote from David Ungar, an influential computer scientist and the developer of the SELF programming language that was referenced in a very old presentation I found online. Thus, modern CPUs are optimised for bulk transfers and bulk operations. At every level, the setup cost of an operation encourages you to work in bulk. Some examples include memory is not loaded per byte, but per multiple of cache lines, this is why alignment is becoming less of an issue than it was in earlier computers. Vector instructions like MMX and SSE allow a single instruction to execute against multiple items of data concurrently providing your program can be expressed in that form. 1.11. Modern processors are limited by memory latency not memory capacity If the situation in CPU land wasn’t bad enough, the news from the memory side of the house doesn’t get much better. Physical memory attached to a server has increased geometrically. My first computer in the 1980’s had kilobytes of memory. When I went through high school I wrote all my essays on a 386 with 1.8 megabytes of ram. Now its commonplace to find servers with tens or hundreds of gigabytes of ram, and the cloud providers are pushing into the terabytes of ram. However, the gap between processor speeds and memory access time continues to grow. But, in terms of processor cycles lost waiting for memory, physical memory is still as far away as ever because memory has not kept pace with the increases in CPU speed. So, most modern processors are limited by memory latency not capacity. Further reading: An interactive graphic of latency figures over time. 1.12. Cache rules everything around me For decades the solution to the processor/memory cap was to add a cache-- a piece of small fast memory located closer, and now directly integrated onto, the CPU. But; L1 has been stuck at 32kb per core for decades L2 has slowly crept up to 512kb on the largest Intel parts L3 is now measured in 4-32mb range, but its access time is variable By caches are limited in size because they are physically large on the CPU die, consume a lot of power. To halve the cache miss rate you must quadruple the cache size. 1.13. The free lunch is over In 2005 Herb Sutter, the C++ committee leader, wrote an article entitled The free lunch is over. In his article Sutter discussed all the points I covered and asserted that future programmers will not longer be able to rely on faster hardware to fix slow programs—or slow programming languages. Now, more than a decade later, there is no doubt that Herb Sutter was right. Memory is slow, caches are too small, CPU clock speeds are going backwards, and the simple world of a single threaded CPU is long gone. Moore’s Law is still in effect, but for all of us in this room, the free lunch is over. 1.14. Conclusion The numbers I would cite would be by 2010: 30GHz, 10billion transistors, and 1 tera-instruction per second. — Pat Gelsinger, Intel CTO, April 2002 It’s clear that without a breakthrough in material science the likelihood of a return to the days of 52% year on year growth in general purpose CPU performance is vanishingly small.[2]. The common consensus is that the fault lies not with the material science itself, but how the transistors are being used. The logical model of sequential instruction flow as expressed in silicon has lead to this expensive endgame. There are many presentations online that rehash this point. They all have the same prediction — computers in the future will not be programmed like they are today. Some argue it’ll look more like graphics cards with hundreds of very dumb, very incoherent processors. Others argue that Very Long Instruction Word (VLIW) computers will become predominant. All agree that our current sequential programming languages will not be compatible with these kinds of processors. My view is that these predictions are correct, the outlook for hardware manufacturers saving us at this point is grim. However, there is enormous scope to optimise the programs today we write for the hardware we have today. Rick Hudson spoke at GopherCon 2015 about reengaging with a "virtuous cycle" of software that works with the hardware we have today, not indiferent of it. Looking at the graphs I showed earlier, from 2015 to 2018 with at best a 5-8% improvement in integer performance and less than that in memory latency, the Go team have decreased the garbage collector pause times by two orders of magnitude. A Go 1.11 program exhibits significantly better GC latency than the same program on the same hardware using Go 1.6. None of this came from hardware. So, for best performance on today’s hardware in today’s world, you need a programming language which: Is compiled, not interpreted, because interpreted programming languages interact poorly with CPU branch predictors and speculative execution. You need a language which permits efficient code to be written, it needs to be able to talk about bits and bytes, and the length of an integer efficiently, rather than pretend every number is an ideal float. You need a language which lets programmers talk about memory effectively, think structs vs java objects, because all that pointer chasing puts pressure on the CPU cache and cache misses burn hundreds of cycles. A programming language that scales to multiple cores as performance of an application is determined by how efficiently it uses its cache and how efficiently it can parallelise work over multiple cores. Obviously we’re here to talk about Go, and I believe that Go inherits many of the traits I just described. 1.14.1. What does that mean for us? There are only three optimizations: Do less. Do it less often. Do it faster. The largest gains come from 1, but we spend all our time on 3. — Michael Fromberger The point of this lecture was to illustrate that when you’re talking about the performance of a program or a system is entirely in the software. Waiting for faster hardware to save the day is a fool’s errand. But there is good news, there is a tonne of improvements we can make in software, and that is what we’re going to talk about today. 2. Benchmarking Measure twice and cut once. — Ancient proverb Before we attempt to improve the performance of a piece of code, first we must know its current performance. This section focuses on how to construct useful benchmarks using the Go testing framework, and gives practical tips for avoiding the pitfalls. 2.1. Benchmarking ground rules Before you benchmark, you must have a stable environment to get repeatable results. The machine must be idle—don’t profile on shared hardware, don’t browse the web while waiting for a long benchmark to run. Watch out for power saving and thermal scaling. These are almost unavoidable on modern laptops. Avoid virtual machines and shared cloud hosting; they can be too noisy for consistent measurements. If you can afford it, buy dedicated performance test hardware. Rack it, disable all the power management and thermal scaling, and never update the software on those machines. The last point is poor advice from a system adminstration point of view, but if a software update changes the way the kernel or library performs—think the Spectre patches—this will invalidate any previous benchmarking results. For the rest of us, have a before and after sample and run them multiple times to get consistent results. 2.2. Using the testing package for benchmarking The testing package has built in support for writing benchmarks. If we have a simple function like this: func Fib(n int) int { switch n { case 0: return 0 case 1: return 1 default: return Fib(n-1) + Fib(n-2) } } The we can use the testing package to write a benchmark for the function using this form. func BenchmarkFib20(b *testing.B) { for n := 0; n < b.N; n++ { Fib(20) // run the Fib function b.N times } } Benchmarks are similar to tests, the only real difference is they take a *testing.B rather than a *testing.T. Both of these types implement the testing.TB interface which provides crowd favorites like Errorf(), Fatalf(), and FailNow(). 2.2.1. Running a package’s benchmarks As benchmarks use the testing package they are executed via the go test subcommand. However, by default when you invoke go test, benchmarks are excluded. To explicitly run benchmarks in a package use the -bench flag. -bench takes a regular expression that matches the names of the benchmarks you want to run, so the most common way to invoke all benchmarks in a package is -bench=.. Here is an example: % go test -bench=. ./examples/fib/ goos: darwin goarch: amd64 pkg: high-performance-go-workshop/examples/fib BenchmarkFib20-8 28947 40617 ns/op PASS ok high-performance-go-workshop/examples/fib 1.602s 2.2.2. How benchmarks work Each benchmark function is called with different value for b.N, this is the number of iterations the benchmark should run for. b.N starts at 1, if the benchmark function completes in under 1 second—the default—then b.N is increased and the benchmark function run again. b.N increases in the approximate sequence, growing by roughly 20% each iteration. The benchmark framework tries to be smart and if it sees small values of b.N are completing relatively quickly, it will increase the iteration count faster. Looking at the example above, BenchmarkFib20-8 found that around 29,000 iterations of the loop took just over a second. From there the benchmark framework computed that the average time per operation was 40617ns. 2.2.3. Go 1.13 benchmarking changes Prior to Go 1.13 the benchmarking iteration numbers we rounded to a 1, 2, 3, 5 sequence. The original goal of this rounding to was to make it easier to eyeball times. However, proper analysis requires tooling anyway, so human readable numbers became less valuble as the tooling improved. The rounding could hide almost an order of magnitude of variation. Fortuntely in Go 1.13 the rounding has been removed, which improves the accuracy of benchmarking operations in the low ns/op range, and reduce the run time of benchmarks overall as the benchmark framework arrives at the correct iteration count faster. 2.2.4. Improving benchmark accuracy The fib function is a slightly contrived example—unless your writing a TechPower web server benchmark—it’s unlikely your business is going to be gated on how quickly you can compute the 20th number in the Fibonaci sequence. But, the benchmark does provide a faithful example of a valid benchmark. Specifically you want your benchmark to run for several tens of thousand iterations so you get a good average per operation. If your benchmark runs for only 100’s or 10’s of iterations, the average of those runs may have a high standard deviation. If your benchmark runs for millions or billions of iterations, the average may be very accurate, but subject to the vaguaries of code layout and alignment. To increase the number of iterations, the benchmark time can be increased with the -benchtime flag. For example: % go test -bench=. -benchtime=10s ./examples/fib/ goos: darwin goarch: amd64 pkg: high-performance-go-workshop/examples/fib BenchmarkFib20-8 313048 41673 ns/op PASS ok high-performance-go-workshop/examples/fib 13.442s Ran the same benchmark until it reached a value of b.N that took longer than 10 seconds to return. As we’re running for 10x longer, the total number of iterations is 10x larger. The result hasn’t changed much, which is what we expected. Why is the total time reporteded to be 13 seconds, not 10? If you have a benchmark which runs for millons or billions of iterations resulting in a time per operation in the micro or nano second range, you may find that your benchmark numbers are unstable because thermal scaling, memory locality, background processing, gc activity, etc. For times measured in 10 or single digit nanoseconds per operation the relativistic effects of instruction reordering and code alignment will have an impact on your benchmark times. To address this run benchmarks multiple times with the -count flag: % go test -bench=Fib20 -count=10 ./examples/fib/ | tee old.txt goos: darwin goarch: amd64 pkg: high-performance-go-workshop/examples/fib BenchmarkFib20-8 30099 38117 ns/op BenchmarkFib20-8 31806 40433 ns/op BenchmarkFib20-8 30052 43412 ns/op BenchmarkFib20-8 28392 39225 ns/op BenchmarkFib20-8 28270 42956 ns/op BenchmarkFib20-8 28276 49493 ns/op BenchmarkFib20-8 26047 45571 ns/op BenchmarkFib20-8 27392 43803 ns/op BenchmarkFib20-8 27507 44896 ns/op BenchmarkFib20-8 25647 43579 ns/op PASS ok high-performance-go-workshop/examples/fib 16.516s A benchmark of Fib(1) takes around 2 nano seconds with a variance of +/- 15%. New in Go 1.12 is the -benchtime flag now takes a number of iterations, eg. -benchtime=20x which will run your code exactly benchtime times. Try running the fib bench above with a -benchtime of 10x, 20x, 50x, 100x, and 300x. What do you see? 2.3. Comparing benchmarks with benchstat In the previous section I suggested running benchmarks more than once to get more data to average. This is good advice for any benchmark because of the effects of power management, background processes, and thermal management that I mentioned at the start of the chapter. % go get golang.org/x/perf/cmd/benchstat Benchstat can take a set of benchmark runs and tell you how stable they are. Here is an example of Fib(20) on battery power. % go test -bench=Fib20 -count=10 ./examples/fib/ | tee old.txt goos: darwin goarch: amd64 pkg: high-performance-go-workshop/examples/fib BenchmarkFib20-8 30721 37893 ns/op BenchmarkFib20-8 31468 38695 ns/op BenchmarkFib20-8 31726 37521 ns/op BenchmarkFib20-8 31686 37583 ns/op BenchmarkFib20-8 31719 38087 ns/op BenchmarkFib20-8 31802 37703 ns/op BenchmarkFib20-8 31754 37471 ns/op BenchmarkFib20-8 31800 37570 ns/op BenchmarkFib20-8 31824 37644 ns/op BenchmarkFib20-8 31165 38354 ns/op PASS ok high-performance-go-workshop/examples/fib 15.808s % benchstat old.txt name time/op Fib20-8 37.9µs ± 2% benchstat tells us the mean is 38.8 microseconds with a +/- 2% variation across the samples. This is because while the benchmark was running I didn’t touch the machine. 2.3.1. Improve Fib Determining the performance delta between two sets of benchmarks can be tedious and error prone. Benchstat can help us with this. The previous Fib fuction had hard coded values for the 0th and 1st numbers in the fibonaci series. After that the code calls itself recursively. We’ll talk about the cost of recursion later today, but for the moment, assume it has a cost, especially as our algorithm uses exponential time. As simple fix to this would be to hard code another number from the fibonacci series, reducing the depth of each recusive call by one. func Fib(n int) int { switch n { case 0: return 0 case 1: return 1 case 2: return 1 default: return Fib(n-1) + Fib(n-2) } } To compare our new version, we compile a new test binary and benchmark both of them and use benchstat to compare the outputs. % go test -c % ./fib.golden -test.bench=. -test.count=10 > old.txt % ./fib.test -test.bench=. -test.count=10 > new.txt % benchstat old.txt new.txt name old time/op new time/op delta Fib20-8 37.9µs ± 2% 24.1µs ± 3% -36.26% (p=0.000 n=10+10) There are three things to check when comparing benchmarks The variance ± in the old and new times. 1-2% is good, 3-5% is ok, greater than 5% and some of your samples will be considered unreliable. Be careful when comparing benchmarks where one side has a high variance, you may not be seeing an improvement. Missing samples. benchstat will report how many of the old and new samples it considered to be valid, sometimes you may find only, say, 9 reported, even though you did -count=10. A 10% or lower rejection rate is ok, higher than 10% may indicate your setup is unstable and you may be comparing too few samples. 2.3.2. Beware the p-value p-values lower than 0.05 likely to be statistiaclly significant. p-values greater than 0.05 imply the benchmark may not be statistically significant. Further reading: P-value (wikipedia). 2.4. Avoiding benchmarking start up costs Sometimes your benchmark has a once per run setup cost. b.ResetTimer() will can be used to ignore the time accrued in setup. func BenchmarkExpensive(b *testing.B) { boringAndExpensiveSetup() b.ResetTimer() (1) for n := 0; n < b.N; n++ { // function under test } } If you have some expensive setup logic per loop iteration, use b.StopTimer() and b.StartTimer() to pause the benchmark timer. func BenchmarkComplicated(b *testing.B) { for n := 0; n < b.N; n++ { b.StopTimer() (1) complicatedSetup() b.StartTimer() (2) // function under test } } 2.5. Benchmarking allocations Allocation count and size is strongly correlated with benchmark time. You can tell the testing framework to record the number of allocations made by code under test. func BenchmarkRead(b *testing.B) { b.ReportAllocs() for n := 0; n < b.N; n++ { // function under test } } Here is an example using the bufio package’s benchmarks. % go test -run=^$ -bench=. bufio goos: darwin goarch: amd64 pkg: bufio BenchmarkReaderCopyOptimal-8 12999212 78.6 ns/op BenchmarkReaderCopyUnoptimal-8 8495018 133 ns/op BenchmarkReaderCopyNoWriteTo-8 360471 2805 ns/op BenchmarkReaderWriteToOptimal-8 3839959 291 ns/op BenchmarkWriterCopyOptimal-8 13878241 82.7 ns/op BenchmarkWriterCopyUnoptimal-8 9932562 117 ns/op BenchmarkWriterCopyNoReadFrom-8 385789 2681 ns/op BenchmarkReaderEmpty-8 1863018 640 ns/op 4224 B/op 3 allocs/op BenchmarkWriterEmpty-8 2040326 579 ns/op 4096 B/op 1 allocs/op BenchmarkWriterFlush-8 88363759 12.7 ns/op 0 B/op 0 allocs/op PASS ok bufio 13.249s 2.6. Watch out for compiler optimisations This example comes from issue 14813. func popcnt(x uint64) uint64 { x -= (x >> 1) & m1 x = (x & m2) + ((x >> 2) & m2) x = (x + (x >> 4)) & m4 return (x * h01) >> 56 } func BenchmarkPopcnt(b *testing.B) { for i := 0; i < b.N; i++ { popcnt(uint64(i)) } } How fast do you think this function will benchmark? Let’s find out. % go test -bench=. ./examples/popcnt/ goos: darwin goarch: amd64 pkg: high-performance-go-workshop/examples/popcnt BenchmarkPopcnt-8 1000000000 0.278 ns/op PASS ok high-performance-go-workshop/examples/popcnt 0.318s 0.278 of a nano second; that’s basically one clock cycle. Even assuming that the CPU may have a few instructions in flight per clock tick, this number seems unreasonably low. What happened? To understand what happened, we have to look at the function under benchmake, popcnt. popcnt is a leaf function — it does not call any other functions — so the compiler can inline it. Because the function is inlined, the compiler now can see it has no side effects. popcnt does not affect the state of any global variable. Thus, the call is eliminated. This is what the compiler sees: func BenchmarkPopcnt(b *testing.B) { for i := 0; i < b.N; i++ { // optimised away } } On all versions of the Go compiler that i’ve tested, the loop is still generated. But Intel CPUs are really good at optimising loops, especially empty ones. 2.6.1. Exercise, look at the assembly Before we go on, lets look at the assembly to confirm what we saw % go test -gcflags=-S Use `gcflags="-l -S" to disable inlining, how does that affect the assembly output 2.6.2. Fixing the benchmark Disabling inlining to make the benchmark work is unrealistic; we want to build our code with optimisations on. To fix this benchmark we must ensure that the compiler cannot prove that the body of BenchmarkPopcnt does not cause global state to change. var Result uint64 func BenchmarkPopcnt(b *testing.B) { var r uint64 for i := 0; i < b.N; i++ { r = popcnt(uint64(i)) } Result = r } This is the recommended way to ensure the compiler cannot optimise away body of the loop. First we use the result of calling popcnt by storing it in r. Second, because r is declared locally inside the scope of BenchmarkPopcnt once the benchmark is over, the result of r is never visible to another part of the program, so as the final act we assign the value of r to the package public variable Result. Because Result is public the compiler cannot prove that another package importing this one will not be able to see the value of Result changing over time, hence it cannot optimise away any of the operations leading to its assignment. What happens if we assign to Result directly? Does this affect the benchmark time? What about if we assign the result of popcnt to _? 2.7. Benchmark mistakes The for loop is crucial to the operation of the benchmark. Here are two incorrect benchmarks, can you explain what is wrong with them? func BenchmarkFibWrong(b *testing.B) { Fib(b.N) } func BenchmarkFibWrong2(b *testing.B) { for n := 0; n < b.N; n++ { Fib(n) } } Run these benchmarks, what do you see? 2.8. Benchmarking math/rand Thanks to Spectre and Meltdown we all know that computers are very good a caching predictable operations. Perhaps our Popcnt benchmark, even the correct version, is returning us a cached value—data that varies unpredictably might be slower than we’re expecting. Let’s test this. var Result uint64 func BenchmarkPopcnt(b *testing.B) { var r uint64 for i := 0; i < b.N; i++ { r = popcnt(rand.Uint64()) } Result = r } Is this result reliable? If not, what went wrong? 2.9. Profiling benchmarks The testing package has built in support for generating CPU, memory, and block profiles. -cpuprofile=$FILEwrites a CPU profile to $FILE. -memprofile=$FILE, writes a memory profile to $FILE, -memprofilerate=Nadjusts the profile rate to 1/N. -blockprofile=$FILE, writes a block profile to $FILE. Using any of these flags also preserves the binary. % go test -run=XXX -bench=. -cpuprofile=c.p bytes % go tool pprof c.p 2.10. Discussion Are there any questions? Perhaps it is time for a break. 3. Performance measurement and profiling In the previous section we looked at benchmarking individual functions which is useful when you know ahead of time where the bottlekneck is. However, often you will find yourself in the position of asking Why is this program taking so long to run? Profiling whole programs which is useful for answering high level questions like. In this section we’ll use profiling tools built into Go to investigate the operation of the program from the inside. 3.1. pprof The first tool we’re going to be talking about today is pprof. pprof descends from the Google Perf Tools suite of tools and has been integrated into the Go runtime since the earliest public releases. pprof consists of two parts: runtime/pprofpackage built into every Go program go tool pproffor investigating profiles. 3.2. Types of profiles pprof supports several types of profiling, we’ll discuss three of these today: CPU profiling. Memory profiling. Block (or blocking) profiling. Mutex contention profiling. 3.2.1. CPU profiling CPU profiling is the most common type of profile, and the most obvious. When CPU profiling is enabled the runtime will interrupt itself every 10ms and record the stack trace of the currently running goroutines. Once the profile is complete we can analyse it to determine the hottest code paths. The more times a function appears in the profile, the more time that code path is taking as a percentage of the total runtime. 3.2.2. Memory profiling Memory profiling records the stack trace when a heap allocation is made. Stack allocations are assumed to be free and are not_tracked in the memory profile. Memory profiling, like CPU profiling is sample based, by default memory profiling samples 1 in every 1000 allocations. This rate can be changed. Because of memory profiling is sample based and because it tracks allocations not use, using memory profiling to determine your application’s overall memory usage is difficult. Personal Opinion: I do not find memory profiling useful for finding memory leaks. There are better ways to determine how much memory your application is using. We will discuss these later in the presentation. 3.2.3. Block profiling Block profiling is quite unique to Go. A block profile is similar to a CPU profile, but it records the amount of time a goroutine spent waiting for a shared resource. This can be useful for determining concurrency bottlenecks in your application. Block profiling can show you when a large number of goroutines could make progress, but were blocked. Blocking includes: Sending or receiving on a unbuffered channel. Sending to a full channel, receiving from an empty one. Trying to Locka sync.Mutexthat is locked by another goroutine. Block profiling is a very specialised tool, it should not be used until you believe you have eliminated all your CPU and memory usage bottlenecks. 3.2.4. Mutex profiling Mutex profiling is simlar to Block profiling, but is focused exclusively on operations that lead to delays caused by mutex contention. The mutex profile does not show you how long the program ran for, or even what took the most time. Instead it reports how much time was spent waiting for locks. Just like blocking profile, it says how much time was spent waiting for a resource. Said another way, the mutex profile reports how much time could be saved if the lock contention was removed. 3.3. One profile at at time Profiling is not free. Profiling has a moderate, but measurable impact on program performance—especially if you increase the memory profile sample rate. Most tools will not stop you from enabling multiple profiles at once. 3.4. Collecting a profile The Go runtime’s profiling interface lives in the runtime/pprof package. runtime/pprof is a very low level tool, and for historic reasons the interfaces to the different kinds of profile are not uniform. As we saw in the previous section, pprof profiling is built into the testing package, but sometimes its inconvenient, or difficult, to place the code you want to profile in the context of at testing.B benchmark and must use the runtime/pprof API directly. A few years ago I wrote a [small package][0], to make it easier to profile an existing application. import "github.com/pkg/profile" func main() { defer profile.Start().Stop() // ... } We’ll use the profile package throughout this section. Later in the day we’ll touch on using the runtime/pprof interface directly. 3.5. Analysing a profile with pprof Now that we’ve talked about what pprof can measure, and how to generate a profile, let’s talk about how to use pprof to analyse a profile. The analysis is driven by the go pprof subcommand go tool pprof /path/to/your/profile This tool provides several different representations of the profiling data; textual, graphical, even flame graphs. 3.5.2. CPU profiling (exercise) Let’s write a program to count words: package main import ( "fmt" "io" "log" "os" "unicode" ) func readbyte(r io.Reader) (rune, error) { var buf [1]byte _, err := r.Read(buf[:]) return rune(buf[0]), err } func main() { f, err := os.Open(os.Args[1]) if err != nil { log.Fatalf("could not open file %q: %v", os.Args[1], err) } words := 0 inword := false for { r, err := readbyte) } Let’s see how many words there are in Herman Melville’s classic Moby Dick (sourced from Project Gutenberg) % go build && time ./words moby.txt "moby.txt": 181275 words real 0m2.110s user 0m1.264s sys 0m0.944s Let’s compare that to unix’s wc -w % time wc -w moby.txt 215829 moby.txt real 0m0.012s user 0m0.009s sys 0m0.002s So the numbers aren’t the same. wc is about 19% higher because what it considers a word is different to what my simple program does. That’s not important—both programs take the whole file as input and in a single pass count the number of transitions from word to non word. Let’s investigate why these programs have different run times using pprof. 3.5.3. Add CPU profiling First, edit main.go and enable profiling import ( "github.com/pkg/profile" ) func main() { defer profile.Start().Stop() // ... Now when we run the program a cpu.pprof file is created. % go run main.go moby.txt 2018/08/25 14:09:01 profile: cpu profiling enabled, /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile239941020/cpu.pprof "moby.txt": 181275 words 2018/08/25 14:09:03 profile: cpu profiling disabled, /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile239941020/cpu.pprof Now we have the profile we can analyse it with go tool pprof % go tool pprof /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile239941020/cpu.pprof Type: cpu Time: Aug 25, 2018 at 2:09pm (AEST) Duration: 2.05s, Total samples = 1.36s (66.29%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top Showing nodes accounting for 1.42s, 100% of 1.42s total flat flat% sum% cum cum% 1.41s 99.30% 99.30% 1.41s 99.30% syscall.Syscall 0.01s 0.7% 100% 1.42s 100% main.readbyte 0 0% 100% 1.41s 99.30% internal/poll.(*FD).Read 0 0% 100% 1.42s 100% main.main 0 0% 100% 1.41s 99.30% os.(*File).Read 0 0% 100% 1.41s 99.30% os.(*File).read 0 0% 100% 1.42s 100% runtime.main 0 0% 100% 1.41s 99.30% syscall.Read 0 0% 100% 1.41s 99.30% syscall.read The top command is one you’ll use the most. We can see that 99% of the time this program spends in syscall.Syscall, and a small part in main.readbyte. We can also visualise this call the with the web command. This will generate a directed graph from the profile data. Under the hood this uses the dot command from Graphviz. However, in Go 1.10 (possibly 1.11) Go ships with a version of pprof that natively supports a http sever % go tool pprof -http=:8080 /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile239941020/cpu.pprof Will open a web browser; Graph mode Flame graph mode On the graph the box that consumes the most CPU time is the largest — we see sys call.Syscall at 99.3% of the total time spent in the program. The string of boxes leading to syscall.Syscall represent the immediate callers — there can be more than one if multiple code paths converge on the same function. The size of the arrow represents how much time was spent in children of a box, we see that from main.readbyte onwards they account for near 0 of the 1.41 second spent in this arm of the graph. Question: Can anyone guess why our version is so much slower than wc? 3.5.4. Improving our version The reason our program is slow is not because Go’s syscall.Syscall is slow. It is because syscalls in general are expensive operations (and getting more expensive as more Spectre family vulnerabilities are discovered). Each call to readbyte results in a syscall.Read with a buffer size of 1. So the number of syscalls executed by our program is equal to the size of the input. We can see that in the pprof graph that reading the input dominates everything else. func main() { defer profile.Start(profile.MemProfile, profile.MemProfileRate(1)).Stop() // defer profile.Start(profile.MemProfile).Stop() f, err := os.Open(os.Args[1]) if err != nil { log.Fatalf("could not open file %q: %v", os.Args[1], err) } b := bufio.NewReader(f) words := 0 inword := false) } By inserting a bufio.Reader between the input file and readbyte will Compare the times of this revised program to wc. How close is it? Take a profile and see what remains. 3.5.5. Memory profiling The new words profile suggests that something is allocating inside the readbyte function. We can use pprof to investigate. defer profile.Start(profile.MemProfile).Stop() Then run the program as usual % go run main2.go moby.txt 2018/08/25 14:41:15 profile: memory profiling enabled (rate 4096), /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile312088211/mem.pprof "moby.txt": 181275 words 2018/08/25 14:41:15 profile: memory profiling disabled, /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile312088211/mem.pprof As we suspected the allocation was coming from readbyte — this wasn’t that complicated, readbyte is three lines long: Use pprof to determine where the allocation is coming from. func readbyte(r io.Reader) (rune, error) { var buf [1]byte (1) _, err := r.Read(buf[:]) return rune(buf[0]), err } We’ll talk about why this is happening in more detail in the next section, but for the moment what we see is every call to readbyte is allocating a new one byte long array and that array is being allocated on the heap. What are some ways we can avoid this? Try them and use CPU and memory profiling to prove it. Alloc objects vs. inuse objects Memory profiles come in two varieties, named after their go tool pprof flags -alloc_objectsreports the call site where each allocation was made. -inuse_objectsreports the call site where an allocation was made iff it was reachable at the end of the profile. To demonstrate this, here is a contrived program which will allocate a bunch of memory in a controlled manner. const count = 100000 var y []byte func main() { defer profile.Start(profile.MemProfile, profile.MemProfileRate(1)).Stop() y = allocate() runtime.GC() } // allocate allocates count byte slices and returns the first slice allocated. func allocate() []byte { var x [][]byte for i := 0; i < count; i++ { x = append(x, makeByteSlice()) } return x[0] } // makeByteSlice returns a byte slice of a random length in the range [0, 16384). func makeByteSlice() []byte { return make([]byte, rand.Intn(2^14)) } The program is annotation with the profile package, and we set the memory profile rate to 1--that is, record a stack trace for every allocation. This is slows down the program a lot, but you’ll see why in a minute. % go run main.go 2018/08/25 15:22:05 profile: memory profiling enabled (rate 1), /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile730812803/mem.pprof 2018/08/25 15:22:05 profile: memory profiling disabled, /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile730812803/mem.pprof Lets look at the graph of allocated objects, this is the default, and shows the call graphs that lead to the allocation of every object during the profile. % go tool pprof -http=:8080 /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile891268605/mem.pprof Not surprisingly more than 99% of the allocations were inside makeByteSlice. Now lets look at the same profile using -inuse_objects % go tool pprof -http=:8080 /var/folders/by/3gf34_z95zg05cyj744_vhx40000gn/T/profile891268605/mem.pprof What we see is not the objects that were allocated during the profile, but the objects that remain in use, at the time the profile was taken — this ignores the stack trace for objects which have been reclaimed by the garbage collector. 3.5.6. Block profiling The last profile type we’ll look at is block profiling. We’ll use the ClientServer benchmark from the net/http package % go test -run=XXX -bench=ClientServer$ -blockprofile=/tmp/block.p net/http % go tool pprof -http=:8080 /tmp/block.p 3.5.7. Mutex profiling Mutex contention increases with the number of goroutines. type AtomicVariable struct { mu sync.Mutex val uint64 } func (av *AtomicVariable) Inc() { av.mu.Lock() av.val++ av.mu.Unlock() } func BenchmarkInc(b *testing.B) { var av AtomicVariable b.RunParallel(func(pb *testing.PB) { for pb.Next() { av.Inc() } }) } Try running this on your machine. % go test -bench=. -cpu=1,2,4,8,16 ./examples/mutex 3.5.8. Framepointers Go 1.7 has been released and along with a new compiler for amd64, the compiler now enables frame pointers by default. The frame pointer is a register that always points to the top of the current stack frame. Framepointers enable tools like gdb(1), and perf(1) to understand the Go call stack. We won’t cover these tools in this workshop, but you can read and watch a presentation I gave on seven different ways to profile Go programs. Seven ways to profile a Go program (slides) Seven ways to profile a Go program (video, 30 mins) Seven ways to profile a Go program (webcast, 60 mins) 3.5.9. Exercise Generate a profile from a piece of code you know well. If you don’t have a code sample, try profiling godoc. % go get golang.org/x/tools/cmd/godoc % cd $GOPATH/src/golang.org/x/tools/cmd/godoc % vim main.go If you were to generate a profile on one machine and inspect it on another, how would you do it? 4. Compiler optimisations This section covers some of the optimisations that the Go compiler performs. For example: Escape analysis Inlining are handled in the front end of the compiler, while the code is still in its AST form; then the code is passed to the SSA compiler for further optimisation like: Dead code elimination Bounds check elimination Nil check elimination 4.1. History of the Go compiler The Go compiler started as a fork of the Plan9 compiler tool chain circa 2007. The compiler at that time bore a strong resemblance to Aho and Ullman’s Dragon Book. A year later, Go 1.7 introduced a new compiler backend based on SSA techniques replaced the previous Plan 9 style code generation. This new backend introduced many opportunities for generic and architecture specific optimistions. 4.2. Escape analysis The first optimisation we’re doing to discuss is escape analysis. To illustrate what escape analysis does recall that the Go spec does not mention the heap or the stack. It only mentions that the language is garbage collected in the introduction, and gives no hints as to how this is to be achieved. A compliant Go implementation of the Go spec could store every allocation on the heap. That would put a lot of pressure on the the garbage collector, but it is in no way incorrect; for several years, gccgo had very limited support for escape analysis so could effectively be considered to be operating in this mode. However, a goroutine’s stack exists as a cheap place to store local variables; there is no need to garbage collect things on the stack as they are effectively collected when the function returns. Therefore, where it is safe to do so, an allocation placed on the stack will be more efficient. In some languages, for example C and C++, the choice of allocating on the stack or on the heap is a manual exercise for the programmer—heap allocations are made with malloc and free, stack allocation is via alloca. Mistakes using these mechanisms are a common cause of memory corruption bugs. In Go, the compiler automatically moves a value to the heap if it lives beyond the lifetime of the function call. It is said that the value escapes to the heap. type Foo struct { a, b, c, d int } func NewFoo() *Foo { return &Foo{a: 3, b: 1, c: 4, d: 7} } In this example the Foo allocated in NewFoo will be moved to the heap so its contents remain valid after NewFoo has returned. This has been present since the earliest days of Go. It isn’t so much an optimisation as an automatic correctness feature. Accidentally returning the address of a stack allocated variable is not possible in Go. But the compiler can also do the opposite; it can find things which would be assumed to be allocated on the heap, and move them to stack. Let’s have a look at an example func Sum() int { numbers := make([]int, 100) for i := range numbers { numbers[i] = i + 1 } var sum int for _, i := range numbers { sum += i } return sum } func main() { answer := Sum() fmt.Println(answer) } Sum adds the `int`s between 1 and 100 and returns the result. Because the numbers slice is only referenced inside Sum, the compiler will arrange to store the 100 integers for that slice on the stack, rather than the heap. There is no need to garbage collect numbers, it is automatically freed when Sum returns. 4.2.1. Prove it! To print the compilers escape analysis decisions, use the -m flag. % go build -gcflags=-m examples/esc/sum.go # command-line-arguments examples/esc/sum.go:21:13: inlining call to fmt.Println examples/esc/sum.go:7:17: Sum make([]int, 100) does not escape examples/esc/sum.go:21:13: answer escapes to heap examples/esc/sum.go:21:13: main []interface {} literal does not escape examples/esc/sum.go:21:13: io.Writer(os.Stdout) escapes to heap <autogenerated>:1: (*File).close .this does not escape Line 7 shows the compiler has correctly deduced that the result of make([]int, 100) does not escape to the heap. The reason it did no The reason line 21 reports that answer escapes to the heap is fmt.Println is a variadic function. The parameters to a variadic function are boxed into a slice, in this case a []interface{}, so answer is placed into a interface value because it is referenced by the call to fmt.Println. Since Go 1.6 the garbage collector requires all values passed via an interface to be pointers, what the compiler sees is approximately: var answer = Sum() fmt.Println([]interface{&answer}...) We can confirm this using the -gcflags="-m -m" flag. Which returns % go build -gcflags='-m -m' examples/esc/sum.go 2>&1 | grep sum.go:21 examples/esc/sum.go:21:13: inlining call to fmt.Println func(...interface {}) (int, error) { var fmt..autotmp_3 int; fmt..autotmp_3 = <N>; var fmt..autotmp_4 error; fmt..autotmp_4 = <N>; fmt..autotmp_3, fmt..autotmp_4 = fmt.Fprintln(io.Writer(os.Stdout), fmt.a...); return fmt..autotmp_3, fmt..autotmp_4 } examples/esc/sum.go:21:13: answer escapes to heap examples/esc/sum.go:21:13: main []interface {} literal does not escape examples/esc/sum.go:21:13: io.Writer(os.Stdout) escapes to heap In short, don’t worry about line 21, its not important to this discussion. 4.2.2. Exercises Does this optimisation hold true for all values of count? Does this optimisation hold true if countis a variable, not a constant? Does this optimisation hold true if countis a parameter to Sum? 4.2.3. Escape analysis (continued) This example is a little contrived. It is not intended to be real code, just an example. type Point struct{ X, Y int } const Width = 640 const Height = 480 func Center(p *Point) { p.X = Width / 2 p.Y = Height / 2 } func NewPoint() { p := new(Point) Center(p) fmt.Println(p.X, p.Y) } NewPoint creates a new *Point value, p. We pass p to the Center function which moves the point to a position in the center of the screen. Finally we print the values of p.X and p.Y. % go build -gcflags=-m examples/esc/center.go # command-line-arguments examples/esc/center.go:11:6: can inline Center examples/esc/center.go:18:8: inlining call to Center examples/esc/center.go:19:13: inlining call to fmt.Println examples/esc/center.go:11:13: Center p does not escape examples/esc/center.go:17:10: NewPoint new(Point) does not escape examples/esc/center.go:19:15: p.X escapes to heap examples/esc/center.go:19:20: p.Y escapes to heap examples/esc/center.go:19:13: NewPoint []interface {} literal does not escape examples/esc/center.go:19:13: io.Writer(os.Stdout) escapes to heap <autogenerated>:1: (*File).close .this does not escape Even though p was allocated with the new function, it will not be stored on the heap, because no reference p escapes the Center function. Question: What about line 19, if p doesn’t escape, what is escaping to the heap? Write a benchmark to provide that Sum does not allocate. 4.3. Inlining In Go function calls in have a fixed overhead; stack and preemption checks. Some of this is ameliorated by hardware branch predictors, but it’s still a cost in terms of function size and clock cycles. Inlining is the classical optimisation that avoids these costs. Until Go 1.11 inlining only worked on leaf functions, a function that does not call another. The justification for this is: If your function does a lot of work, then the preamble overhead will be negligible. That’s why functions over a certain size (currently some count of instructions, plus a few operations which prevent inlining all together, eg. switch before Go 1.7) Small functions on the other hand pay a fixed overhead for a relatively small amount of useful work performed. These are the functions that inlining targets as they benefit the most. The other reason is that heavy inlining makes stack traces harder to follow. 4.3.1. Inlining (example) func Max(a, b int) int { if a > b { return a } return b } func F() { const a, b = 100, 20 if Max(a, b) == b { panic(b) } } Again we use the -gcflags=-m flag to view the compilers optimisation decision. % go build -gcflags=-m examples/inl/max.go # command-line-arguments examples/inl/max.go:4:6: can inline Max examples/inl/max.go:11:6: can inline F examples/inl/max.go:13:8: inlining call to Max examples/inl/max.go:20:6: can inline main examples/inl/max.go:21:3: inlining call to F examples/inl/max.go:21:3: inlining call to Max The compiler printed two lines. The first at line 3, the declaration of Max, telling us that it can be inlined. The second is reporting that the body of Maxhas been inlined into the caller at line 12. 4.3.2. What does inlining look like? Compile max.go and see what the optimised version of F() became. % go build -gcflags=-S examples/inl/max.go 2>&1 | grep -A5 '"".F STEXT' "".F STEXT nosplit size=2 args=0x0 locals=0x0 0x0000 00000 (/Users/dfc/devel/high-performance-go-workshop/examples/inl/max.go:11) TEXT "".F(SB), NOSPLIT|ABIInternal, $0-0 0x0000 00000 (/Users/dfc/devel/high-performance-go-workshop/examples/inl/max.go:11) FUNCDATA $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x0000 00000 (/Users/dfc/devel/high-performance-go-workshop/examples/inl/max.go:11) FUNCDATA $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x0000 00000 (/Users/dfc/devel/high-performance-go-workshop/examples/inl/max.go:11) FUNCDATA $3, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x0000 00000 (/Users/dfc/devel/high-performance-go-workshop/examples/inl/max.go:13) PCDATA $2, $0 This is the body of F once Max has been inlined into it — there’s nothing happening in this function. I know there’s a lot of text on the screen for nothing, but take my word for it, the only thing happening is the RET. In effect F became: func F() { return } Without using the //go:noinline comment, rewrite Max such that it still returns the right answer, but is no longer considered inlineable by the compiler. Here’s one way to do it include::../examples/inl/max_noinline.go Let’s see what the compiler thinks of it % go build -gcflags=-m max_noinline.go # command-line-arguments ./max_noinline.go:16:6: can inline F (1) ./max_noinline.go:25:6: can inline main ./max_noinline.go:26:3: inlining call to F We can double check this with two -m flags % go build -gcflags=-m=2 max_noinline.go # command-line-arguments ./max_noinline.go:6:6: cannot inline Max: unhandled op SELECT (1) ./max_noinline.go:16:6: can inline F as: func() { <node DCLCONST>; <node DCLCONST>; if Max(a, b) == b { panic(b) } } (2) ./max_noinline.go:25:6: can inline main as: func() { F() } ./max_noinline.go:26:3: inlining call to F func() { <node DCLCONST>; <node DCLCONST>; if Max(a, b) == b { panic(b) } } 4.3.3. Discussion Why did I declare a and b in F() to be constants? Experiment with the output of What happens if a and b are declared as are variables? What happens if a and b are passing into F() as parameters? In the example at the start of the day, no care was taken to prevent the optimisation that broke the popcnt benchmark from affecting Fib20. Why was that? 4.3.4. Adjusting the level of inlining Adjusting the inlining level is performed with the -gcflags=-l flag. Somewhat confusingly passing a single -l will disable inlining, and two or more will enable inlining at more aggressive settings. -gcflags=-l, inlining disabled. nothing, regular inlining. -gcflags='-l -l'inlining level 2, more aggressive, might be faster, may make bigger binaries. -gcflags='-l -l -l'inlining level 3, more aggressive again, binaries definitely bigger, maybe faster again, but might also be buggy. -gcflags=-l=4(four `-l`s) in Go 1.11 will enable the experimental mid stack inlining optimisation. I believe as of Go 1.12 it has no effect. 4.3.5. Mid Stack inlining Since Go 1.12 so called mid stack inlining has been enabled (it was previously available in preview in Go 1.11 with the -gcflags='-l -l -l -l' flag). We can see an example of mid stack inlining in the previous example. In Go 1.11 and earlier F would not have been a leaf function — it called max. However because of inlining improvements F is now inlined into its caller. This is for two reasons; . When max is inlined into F, F contains no other function calls thus it becomes a potential leaf function, assuming its complexity budget has not been exceeded. . Because F is a simple function—inlining and dead code elimination has eliminated much of its complexity budget—it is eligable for mid stack inlining irrispective of calling max. 4.4. Dead code elimination Why is it important that a and b are constants? To understand what happened lets look at what the compiler sees once its inlined Max into F. We can’t get this from the compiler easily, but it’s straight forward to do it by hand. Before: func Max(a, b int) int { if a > b { return a } return b } func F() { const a, b = 100, 20 if Max(a, b) == b { panic(b) } } After: func F() { const a, b = 100, 20 var result int if a > b { result = a } else { result = b } if result == b { panic(b) } } Because a and b are constants the compiler can prove at compile time that the branch will never be false; 100 is always greater than 20. So the compiler can further optimise F to func F() { const a, b = 100, 20 var result int if true { result = a } else { result = b } if result == b { panic(b) } } Now that the result of the branch is know then then the contents of result are also known. This is call branch elimination. func F() { const a, b = 100, 20 const result = a if result == b { panic(b) } } Now the branch is eliminated we know that result is always equal to a, and because a was a constant, we know that result is a constant. The compiler applies this proof to the second branch func F() { const a, b = 100, 20 const result = a if false { panic(b) } } And using branch elimination again the final form of F is reduced to. func F() { const a, b = 100, 20 const result = a } And finally just func F() { } 4.4.1. Dead code elimination (cont.) Branch elimination is one of a category of optimisations known as dead code elimination. In effect, using static proofs to show that a piece of code is never reachable, colloquially known as dead, therefore it need not be compiled, optimised, or emitted in the final binary. We saw how dead code elimination works together with inlining to reduce the amount of code generated by removing loops and branches that are proven unreachable. You can take advantage of this to implement expensive debugging, and hide it behind const debug = false Combined with build tags this can be very useful. 4.5. Prove pass A few releases ago the SSA backend gained a, so called, prove pass. Prove, the verb form of Proof, establishes the relationship between variables. Let’s look at an example to explain what prove is doing. package main func foo(x int) bool { if x > 5 { (1) if x > 3 { (2) return true } panic("x less than 3") } return false } func main() { foo(-1) } 4.5.1. Prove it (ha!) Just as with inining and escape analysis we can ask the compiler to show us the working of the prove pass. We do this with the -d flag passed to go tool compile via -gcflags % go build -gcflags=-d=ssa/prove/debug=on examples/prove/foo.go # command-line-arguments examples/prove/foo.go:5:10: Proved Greater64 Line 5 is if x > 3. The compiler is saying that is has proven that the branch will always be true. Experiment with the output of What happens if a and b are declared as are variables? What happens if a and b are passing into F() as parameters? 4.6. Compiler intrinsics Go allows you to write functions in assembly if required. The technique involves a forwarding declared function—a function without a body—and a corresponding assembly function. package asm // Add returns the sum of a and b. func Add(a int64, b int64) int64 Here we’re declaring an Add function which takes two int64’s and returns a third. Note the `Add function has no body. If we were to compile it we would see something like this % go build # high-performance-go-workshop/examples/asm [high-performance-go-workshop/examples/asm.test] ./decl.go:4:6: missing function body To satisfy the compiler we must supply the assembly for this function, which we can do via a .s file in the same package. TEXT ·Add(SB),$0 MOVQ a+0(FP), AX ADDQ b+8(FP), AX MOVQ AX, ret+16(FP) RET Now we can build, test, and use our asm.Add function just like normal Go code. But there’s a problem, assembly functions cannot be inlined. This has long been a complaint by Go developers who need to use assembly either for performance, or for operations which are not exposed in the language; vector instructions, atomic primatives and so on, which when written as assembly functions pay a high overhead cost because they cannot be inlined. There have been various proposals for an inline assembly syntax for Go, similar to GCC’s asm(…) directive, but they have not been accepted by the Go developers. Instead, Go has added intrinsic functions. An intrinsic function is regular Go code written in regular Go, however the compiler contains specific drop in replacements for the functions. The two packages that make use of this this are math/bits sync/atomic These replacements are implemented in the compiler backend; if your architecture supports a faster way of doing an operation it will be transparently replaced with the comparable instruction during compilation. As well as generating more efficient code, because intrinsic functions are just normal Go code, the rules of inlining, and mid stack inlining apply to them. 4.6.1. Popcnt example Let’s return to the pop count example from earlier. Population count is an important crypto operation so modern CPUs have a native instruction to perform it. The math/bits package provides a set of functions, OnesCount… which are recognised by the compiler and replaced with their native equivalent. func BenchmarkMathBitsPopcnt(b *testing.B) { var r int for i := 0; i < b.N; i++ { r = bits.OnesCount64(uint64(i)) } Result = uint64(r) } Run the benchmark and compare the performance of the hand rolled shift implementation and math/bits.OnesCount64. % go test -bench=. ./examples/popcnt-intrinsic/ 4.6.2. Atomic counter example Here’s an example of an atomic counter type. We’ve got methods on types, method calls several levels deep, multiple packages, etc. You’d be forgiven for thinking this might have a lot of overhead. package main() } func main() { f() } But, because of the interation between inlining and compiler intrinsics, this code collapses down to efficient native code on most platforms. "".f STEXT nosplit size=36 args=0x8 locals=0x0 0x0000 00000 (/tmp/counter.go:21) TEXT "".f(SB), NOSPLIT|ABIInternal, $0-8 0x0000 00000 (<unknown line number>) NOP 0x0000 00000 (/tmp/counter.go:22) MOVL $1, AX 0x0005 00005 (/tmp/counter.go:13) LEAQ "".c(SB), CX 0x000c 00012 (/tmp/counter.go:13) LOCK 0x000d 00013 (/tmp/counter.go:13) XADDQ AX, (CX) (1) 0x0011 00017 (/tmp/counter.go:23) XCHGL AX, AX 0x0012 00018 (/tmp/counter.go:10) MOVQ "".c(SB), AX (2) 0x0019 00025 (<unknown line number>) NOP 0x0019 00025 (/tmp/counter.go:16) XORL AX, AX 0x001b 00027 (/tmp/counter.go:16) XCHGQ AX, (CX) (3) 0x001e 00030 (/tmp/counter.go:24) MOVQ AX, "".~r0+8(SP) 0x0023 00035 (/tmp/counter.go:24) RET 0x0000 b8 01 00 00 00 48 8d 0d 00 00 00 00 f0 48 0f c1 .....H.......H.. 0x0010 01 90 48 8b 05 00 00 00 00 31 c0 48 87 01 48 89 ..H......1.H..H. 0x0020 44 24 08 c3 D$.. rel 8+4 t=15 "".c+0 rel 21+4 t=15 "".c+0 4.7. Bounds check elimination Go is a bounds checked language. This means array and slice subscript operations are checked to ensure they are within the bounds of the respective types. For arrays, this can be done at compile time. For slices, this must be done at run time. var v = make([]int, 9) var A, B, C, D, E, F, G, H, I int func BenchmarkBoundsCheckInOrder(b *testing.B) { var a, _b, c, d, e, f, g, h, i int for n := 0; n < b.N; n++ { a = v[0] _b = v[1] c = v[2] d = v[3] e = v[4] f = v[5] g = v[6] h = v[7] i = v[8] } A, B, C, D, E, F, G, H, I = a, _b, c, d, e, f, g, h, i } Use -gcflags=-S to disassemble BenchmarkBoundsCheckInOrder. How many bounds check operations are performed per loop? func BenchmarkBoundsCheckOutOfOrder(b *testing.B) { var a, _b, c, d, e, f, g, h, i int for n := 0; n < b.N; n++ { i = v[8] a = v[0] _b = v[1] c = v[2] d = v[3] e = v[4] f = v[5] g = v[6] h = v[7] } A, B, C, D, E, F, G, H, I = a, _b, c, d, e, f, g, h, i } Does rearranging the order in which we assign the A through I affect the assembly. Disassemble BenchmarkBoundsCheckOutOfOrder and find out. 4.7.1. Exercises Does rearranging the order of subscript operations affect the size of the function? Does it affect the speed of the function? What happens if vis moved inside the Benchmarkfunction? What happens if vwas declared as an array, var v [9]int? 4.8. Compiler flags exercises Compiler flags are provided with: go build -gcflags=$FLAGS Investigate the operation of the following compiler functions: -Sprints the (Go flavoured) assembly of the package being compiled. -lcontrols the behaviour of the inliner; -ldisables inlining, -l -lincreases it (more -l's increases the compiler’s appetite for inlining code). Experiment with the difference in compile time, program size, and run time. -mcontrols printing of optimisation decision like inlining, escape analysis. -m-m` prints more details about what the compiler was thinking. -l -Ndisables all optimisations. -d=ssa/prove/debug=on, this also takes values of 2 and above, see what prints The -dflag takes other values, you can find out what they are with the command go tool compile -d help. Experiment and see what you can discovrer. 5. Execution Tracer The execution tracer was developed by Dmitry Vyukov for Go 1.5 and remained under documented, and under utilised, for several years. Unlike sample based profiling, the execution tracer is integrated into the Go runtime, so it does just know what a Go program is doing at a particular point in time, but why. 5.1. What is the execution tracer, why do we need it? I think its easiest to explain what the execution tracer does, and why it’s important by looking at a piece of code where the pprof, go tool pprof performs poorly. The examples/mandelbrot directory contains a simple mandelbrot generator. This code is derived from Francesc Campoy’s mandelbrot package. cd examples/mandelbrot go build && ./mandelbrot If we build it, then run it, it generates something like this 5.1.1. How long does it take? So, how long does this program take to generate a 1024 x 1024 pixel image? The simplest way I know how to do this is to use something like time(1). % time ./mandelbrot real 0m1.654s user 0m1.630s sys 0m0.015s 5.1.2. What is the program doing? So, in this example the program took 1.6 seconds to generate the mandelbrot and write to to a png. Is that good? Could we make it faster? One way to answer that question would be to use Go’s built in pprof support to profile the program. Let’s try that. 5.2. Generating the profile To turn generate a profile we need to either Use the runtime/pprofpackage directly. Use a wrapper like github.com/pkg/profileto automate this. 5.3. Generating a profile with runtime/pprof To show you that there’s no magic, let’s modify the program to write a CPU profile to os.Stdout. import "runtime/pprof" func main() { pprof.StartCPUProfile(os.Stdout) defer pprof.StopCPUProfile() By adding this code to the top of the main function, this program will write a profile to os.Stdout. cd examples/mandelbrot-runtime-pprof go run mandelbrot.go > cpu.pprof 5.3.1. Generating a profile with github.com/pkg/profile The previous slide showed a super cheap way to generate a profile, but it has a few problems. If you forget to redirect the output to a file then you’ll blow up that terminal session. 😞 (hint: reset(1)is your friend) If you write anything else to os.Stdout, for example, fmt.Printlnyou’ll corrupt the trace. The recommended way to use runtime/pprof is to write the trace to a file. But, then you have to make sure the trace is stopped, and file is closed before your program stops, including if someone `^C’s it. import "github.com/pkg/profile" func main() { defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop() If we run this version, we get a profile written to the current working directory % go run mandelbrot.go 2017/09/17 12:22:06 profile: cpu profiling enabled, cpu.pprof 2017/09/17 12:22:08 profile: cpu profiling disabled, cpu.pprof 5.3.2. Analysing the profile Now we have a profile, we can use go tool pprof to analyse it. % go tool pprof -http=:8080 cpu.pprof In this run we see that the program ran for 1.81s seconds (profiling adds a small overhead). We can also see that pprof only captured data for 1.53 seconds, as pprof is sample based, relying on the operating system’s SIGPROF timer. We can use the top pprof function to sort functions recorded by the trace % go tool pprof cpu.pprof Type: cpu Time: Mar 24, 2019 at 5:18pm (CET) Duration: 2.16s, Total samples = 1.91s (88.51%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top Showing nodes accounting for 1.90s, 99.48% of 1.91s total Showing top 10 nodes out of 35 flat flat% sum% cum cum% 0.82s 42.93% 42.93% 1.63s 85.34% main.fillPixel 0.81s 42.41% 85.34% 0.81s 42.41% main.paint 0.11s 5.76% 91.10% 0.12s 6.28% runtime.mallocgc 0.04s 2.09% 93.19% 0.04s 2.09% runtime.memmove 0.04s 2.09% 95.29% 0.04s 2.09% runtime.nanotime 0.03s 1.57% 96.86% 0.03s 1.57% runtime.pthread_cond_signal 0.02s 1.05% 97.91% 0.04s 2.09% compress/flate.(*compressor).deflate 0.01s 0.52% 98.43% 0.01s 0.52% compress/flate.(*compressor).findMatch 0.01s 0.52% 98.95% 0.01s 0.52% compress/flate.hash4 0.01s 0.52% 99.48% 0.01s 0.52% image/png.filter We see that the main.fillPixel function was on the CPU the most when pprof captured the stack. Finding main.paint on the stack isn’t a surprise, this is what the program does; it paints pixels. But what is causing paint to spend so much time? We can check that with the cummulative flag to top. (pprof) top --cum Showing nodes accounting for 1630ms, 85.34% of 1910ms total Showing top 10 nodes out of 35 flat flat% sum% cum cum% 0 0% 0% 1840ms 96.34% main.main 0 0% 0% 1840ms 96.34% runtime.main 820ms 42.93% 42.93% 1630ms 85.34% main.fillPixel 0 0% 42.93% 1630ms 85.34% main.seqFillImg 810ms 42.41% 85.34% 810ms 42.41% main.paint 0 0% 85.34% 210ms 10.99% image/png.(*Encoder).Encode 0 0% 85.34% 210ms 10.99% image/png.Encode 0 0% 85.34% 160ms 8.38% main.(*img).At 0 0% 85.34% 160ms 8.38% runtime.convT2Inoptr 0 0% 85.34% 150ms 7.85% image/png.(*encoder).writeIDATs This is sort of suggesting that main.fillPixed is actually doing most of the work. 5.4. Tracing vs Profiling Hopefully this example shows the limitations of profiling. Profiling told us what the profiler saw; fillPixel was doing all the work. There didn’t look like there was much that could be done about that. So now it’s a good time to introduce the execution tracer which gives a different view of the same program. 5.4.1. Using the execution tracer Using the tracer is as simple as asking for a profile.TraceProfile, nothing else changes. import "github.com/pkg/profile" func main() { defer profile.Start(profile.TraceProfile, profile.ProfilePath(".")).Stop() When we run the program, we get a trace.out file in the current working directory. % go build mandelbrot.go % % time ./mandelbrot 2017/09/17 13:19:10 profile: trace enabled, trace.out 2017/09/17 13:19:12 profile: trace disabled, trace.out real 0m1.740s user 0m1.707s sys 0m0.020s Just like pprof, there is a tool in the go command to analyse the trace. % go tool trace trace.out 2017/09/17 12:41:39 Parsing trace... 2017/09/17 12:41:40 Serializing trace... 2017/09/17 12:41:40 Splitting trace... 2017/09/17 12:41:40 Opening browser. Trace viewer s listening on This tool is a little bit different to go tool pprof. The execution tracer is reusing a lot of the profile visualisation infrastructure built into Chrome, so go tool trace acts as a server to translate the raw execution trace into data which Chome can display natively. 5.4.2. Analysing the trace We can see from the trace that the program is only using one cpu. func seqFillImg(m *img) { for i, row := range m.m { for j := range row { fillPixel(m, i, j) } } } This isn’t a surprise, by default mandelbrot.go calls fillPixel for each pixel in each row in sequence. Once the image is painted, see the execution switches to writing the .png file. This generates garbage on the heap, and so the trace changes at that point, we can see the classic saw tooth pattern of a garbage collected heap. The trace profile offers timing resolution down to the microsecond level. This is something you just can’t get with external profiling. 5.5. Using more than one CPU We saw from the previous trace that the program is running sequentially and not taking advantage of the other CPUs on this machine. Mandelbrot generation is known as embarassingly_parallel. Each pixel is independant So the runtime was basically the same. There was more user time, which makes sense, we were using all the CPUs, but the real (wall clock) time was about the same. Let’s look a the trace. As you can see this trace generated much more data. It looks like lots of work is being done, but if you zoom right in, there are gaps. This is believed to be the scheduler. While we’re using all four cores, because each fillPixelis a relatively small amount of work, we’re spending a lot of time in scheduling overhead. 5.6. Batching up work Using one goroutine per pixel was too fine grained. There wasn. As you can see the trace is now smaller and easier to work with. We get to see the whole trace in span, which is a nice bonus. At the start of the program we see the number of goroutines ramp up to around 1,000. This is an improvement over the 1 << 20 that we saw in the previous trace. Zooming in we see onePerRowFillImgruns for longer, and as the goroutine producing work is done early, the scheduler efficiently works through the remaining runnable goroutines. 5.7. Using workers mandelbrot.go supports one other mode, let’s try it. % go build mandelbrot.go % time ./mandelbrot -mode workers 2017/09/17 13:49:46 profile: trace enabled, trace.out 2017/09/17 13:49:50 profile: trace disabled, trace.out real 0m4.207s user 0m4.459s sys 0m1.284s So, the runtime was much worse than any previous. Let’s look at the trace and see if we can figure out what happened. Looking at the trace you can see that with only one worker process the producer and consumer tend to alternate because there is only one worker and one consumer. Let’s increase the number of workers % go build mandelbrot.go % time ./mandelbrot -mode workers -workers 4 2017/09/17 13:52:51 profile: trace enabled, trace.out 2017/09/17 13:52:57 profile: trace disabled, trace.out real 0m5.528s user 0m7.307s sys 0m4.311s So that made it worse! More real time, more CPU time. Let’s look at the trace to see what happened. That trace is a mess. There were more workers available, but the seemed to spend all their time fighting over the work to do. This is because the channel is unbuffered. An unbuffered channel cannot send until there is someone ready to receive. The producer cannot send work until there is a worker ready to receive it. Workers cannot receive work until there is someone ready to send, so they compete with each other when they are waiting. The sender is not privileged, it cannot take priority over a worker that is already running. What we see here is a lot of latency introduced by the unbuffered channel. There are lots of stops and starts inside the scheduler, and potentially locks and mutexes while waiting for work, this is why we see the sys time higher. 5.8. Using buffered channels import "github.com/pkg/profile" func main() { defer profile.Start(profile.TraceProfile, profile.ProfilePath(".")).Stop() % go build mandelbrot.go % time ./mandelbrot -mode workers -workers 4 2017/09/17 14:23:56 profile: trace enabled, trace.out 2017/09/17 14:23:57 profile: trace disabled, trace.out real 0m0.905s user 0m2.150s sys 0m0.121s Which is pretty close to the per row mode above. Using a buffered channel the trace showed us that: The producer doesn’t have to wait for a worker to arrive, it can fill up the channel quickly. The worker can quickly take the next item from the channel without having to sleep waiting on work to be produced. Using this method we got nearly the same speed using a channel to hand off work per pixel than we did previously scheduling on goroutine per row. Modify nWorkersFillImg to work per row. Time the result and analyse the trace. 5.9. Mandelbrot microservice It’s 2019, generating Mandelbrots is pointless unless you can offer them on the internet as a serverless microservice. Thus, I present to you, Mandelweb % go run examples/mandelweb/mandelweb.go 2017/09/17 15:29:21 listening on 5.9.1. Tracing running applications In the previous example we ran the trace over the whole program. As you saw, traces can be very large, even for small amounts of time, so collecting trace data continually would generate far too much data. Also, tracing can have an impact on the speed of your program, especially if there is a lot of activity. What we want is a way to collect a short trace from a running program. Fortuntately, the net/http/pprof package has just such a facility. 5.9.2. Collecting traces via http Hopefully everyone knows about the net/http/pprof package. import _ "net/http/pprof" When imported, the net/http/pprof will register tracing and profiling routes with http.DefaultServeMux. Since Go 1.5 this includes the trace profiler. We can grab a five second trace from mandelweb with curl (or wget) % curl -o trace.out 5.9.3. Generating some load The previous example was interesting, but an idle webserver has, by definition, no performance issues. We need to generate some load. For this I’m using hey by JBD. % go get -u github.com/rakyll/hey Let’s start with one request per second. % hey -c 1 -n 1000 -q 1.4. Simulating overload Let’s increase the rate to 5 requests per second. % hey -c 5 -n 1000 -q 5.5. Extra credit, the Sieve of Eratosthenes The concurrent prime sieve is one of the first Go programs written. Ivan Daniluk wrote a great post on visualising it. Let’s take a look at its operation using the execution tracer. 5.9.6. More resources Rhys Hiltner, Go’s execution tracer (dotGo 2016) Rhys Hiltner, An Introduction to "go tool trace" (GopherCon 2017) Dave Cheney, Seven ways to profile Go programs (GolangUK 2016) Dave Cheney, High performance Go workshop Ivan Daniluk, Visualizing Concurrency in Go (GopherCon 2016) Kavya Joshi, Understanding Channels (GopherCon 2017) Francesc Campoy, Using the Go execution tracer 6. Memory and Garbage Collector Go is a garbage collected language. This is a design principle, it will not change. As a garbage collected language, the performance of Go programs is often determined by their interaction with the garbage collector. Next to your choice of algorithms, memory consumption is the most important factor that determines the performance and scalability of your application. This section discusses the operation of the garbage collector, how to measure the memory usage of your program and strategies for lowering memory usage if garbage collector performance is a bottleneck. 6.1. Garbage collector world view The purpose of any garbage collector is to present the illusion that there is an infinite amount of memory available to the program. You may disagree with this statement, but this is the base assumption of how garbage collector designers work. A stop the world, mark sweep GC is the most efficient in terms of total run time; good for batch processing, simulation, etc. However, over time the Go GC has moved from a pure stop the world collector to a concurrent, non compacting, collector. This is because the Go GC is designed for low latency servers and interactive applications. The design of the Go GC favors lower_latency over maximum_throughput; it moves some of the allocation cost to the mutator to reduce the cost of cleanup later. 6.2. Garbage collector design The design of the Go GC has changed over the years Go 1.0, stop the world mark sweep collector based heavily on tcmalloc. Go 1.3, fully precise collector, wouldn’t mistake big numbers on the heap for pointers, thus leaking memory. Go 1.5, new GC design, focusing on latency over throughput. Go 1.6, GC improvements, handling larger heaps with lower latency. Go 1.7, small GC improvements, mainly refactoring. Go 1.8, further work to reduce STW times, now down to the 100 microsecond range. Go 1.10+, move away from pure cooprerative goroutine scheduling to lower the latency when triggering a full GC cycle. Go 1.13 Scavenger rewritten 6.2.1. Garbage collector tuning The Go runtime provides one environment variable to tune the GC, GOGC. The formula for GOGC is \$goal = reachabl\e * (1 + (GOGC)/100)\$ For example, if we currently have a 256MB heap, and GOGC=100 (the default), when the heap fills up it will grow to \$512MB = 256MB * (1 + 100/100)\$ Values of GOGCgreater than 100 causes the heap to grow faster, reducing the pressure on the GC. Values of GOGCless than 100 cause the heap to grow slowly, increasing the pressure on the GC. The default value of 100 is just_a_guide. you should choose your own value after profiling your application with production loads. 6.2.2. VSS and the scavenger Many applications operate through distict phases; setup, steady-state, and (optionally) shutdown. The phases have different memory profiles. Setup may process or summarise a large amounts of data. Steady-state may consume memory proportional to connected clients or request rate. Shutdown may consume memory proportional to the amount of data process during steady state to summarise or pasivate data to disk. In practical terms your application may use more memory on startup than during the rest of it’s life, then its heap will be larger than necessary, but mostly unused. It would be useful if the Go runtime could tell the operating system which parts of the, mostly unoccupied, heap are not needed. 6.2.3. Garbage collector monitoring A simple way to obtain a general idea of how hard the garbage collector is working is to enable the output of GC logging. These stats are always collected, but normally suppressed, you can enable their display by setting the GODEBUG environment variable. % env GODEBUG=gctrace=1 godoc -http=:8080 gc 1 @0.012s 2%: 0.026+0.39+0.10 ms clock, 0.21+0.88/0.52/0+0.84 ms cpu, 4->4->0 MB, 5 MB goal, 8 P gc 2 @0.016s 3%: 0.038+0.41+0.042 ms clock, 0.30+1.2/0.59/0+0.33 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 3 @0.020s 4%: 0.054+0.56+0.054 ms clock, 0.43+1.0/0.59/0+0.43 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 4 @0.025s 4%: 0.043+0.52+0.058 ms clock, 0.34+1.3/0.64/0+0.46 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 5 @0.029s 5%: 0.058+0.64+0.053 ms clock, 0.46+1.3/0.89/0+0.42 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 6 @0.034s 5%: 0.062+0.42+0.050 ms clock, 0.50+1.2/0.63/0+0.40 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 7 @0.038s 6%: 0.057+0.47+0.046 ms clock, 0.46+1.2/0.67/0+0.37 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 8 @0.041s 6%: 0.049+0.42+0.057 ms clock, 0.39+1.1/0.57/0+0.46 ms cpu, 4->4->1 MB, 5 MB goal, 8 P gc 9 @0.045s 6%: 0.047+0.38+0.042 ms clock, 0.37+0.94/0.61/0+0.33 ms cpu, 4->4->1 MB, 5 MB goal, 8 P The trace output gives a general measure of GC activity. The output format of gctrace=1 is described in the runtime package documentation. DEMO: Show godoc with GODEBUG=gctrace=1 enabled Using GODEBUG=gctrace=1 is good when you know there is a problem, but for general telemetry on your Go application I recommend the net/http/pprof interface. import _ "net/http/pprof" Importing the net/http/pprof package will register a handler at /debug/pprof with various runtime metrics, including: A list of all the running goroutines, /debug/pprof/heap?debug=1. A report on the memory allocation statistics, /debug/pprof/heap?debug=1. DEMO: godoc -http=:8080, show /debug/pprof. 6.3. Minimise allocations Memory allocation is not free, this is true reguardless of if your language is garbage collected or not. Memory allocation can be an overhead spread throughout your codebase; each represents a tiny fraction of the total runtime, but collectively they represent a sizeable cost. Because that cost is spread across many places, identifying the biggest offenders can be complicated and often requires reworking APIs. Each allocation should pay its way. Analogy: if you move to a larger house because you’re planning on having a family, that’s a good use of your capital. If you move to a larger house because someone asked you to mind their child for an afternoon, that’s a poor use of your capital. 6.3.1. strings vs []bytes In Go string values are immutable, []byte are mutable. Most programs prefer to work string, but most IO is done with []byte. Avoid []byte to string conversions wherever possible, this normally means picking one representation, either a string or a []byte for a value. Often this will be []byte if you read the data from the network or disk. The bytes package contains many of the same operations — Split, Compare, HasPrefix, Trim, etc — as the strings package. Under the hood strings uses same assembly primitives as the bytes package. 6.3.2. Using []byte as a map key It is very common to use a string as a map key, but often you have a []byte. Alterntative you may have a key in []byte form, but slices do not have a defined equality operator so cannot be used as map keys. The compiler implements a specific optimisation for this case var m map[string]string v, ok := m[string(bytes)] This will avoid the conversion of the byte slice to a string for the map lookup. This is very specific, it won’t work if you do something like key := string(bytes) val, ok := m[key] Let’s see if this is still true. Write a benchmark comparing these two methods of using a []byte as a string map key. 6.3.3. []byte to string conversions Just like []byte to string conversions are necessary for map keys, comparing two []byte slices for equality either requires a conversion — potentially a copy — to a string, or the use of the bytes.Equal function. The good news is in 1.13 the compiler has improved to the point that []byte to string conversions for the purpose of equality testing avoids the allocation. func BenchmarkBytesEqualInline(b *testing.B) { x := bytes.Repeat([]byte{'a'}, 1<<20) y := bytes.Repeat([]byte{'a'}, 1<<20) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { if string(x) != string(y) { b.Fatal("x != y") } } } func BenchmarkBytesEqualExplicit(b *testing.B) { x := bytes.Repeat([]byte{'a'}, 1<<20) y := bytes.Repeat([]byte{'a'}, 1<<20) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { q := string(x) r := string(y) if q != r { b.Fatal("x != y") } } } However, just like the map example above, the copy is only elided in simple cases. Further reading: 6.3.4. Avoid string concatenation Go strings are immutable. Concatenating two strings generates a third. Which of the following is fastest? s := request.ID s += " " + client.Addr().String() s += " " + time.Now().String() r = s var b bytes.Buffer fmt.Fprintf(&b, "%s %v %v", request.ID, client.Addr(), time.Now()) r = b.String() r = fmt.Sprintf("%s %v %v", request.ID, client.Addr(), time.Now()) b := make([]byte, 0, 40) b = append(b, request.ID...) b = append(b, ' ') b = append(b, client.Addr().String()...) b = append(b, ' ') b = time.Now().AppendFormat(b, "2006-01-02 15:04:05.999999999 -0700 MST") r = string(b) var b strings.Builder b.WriteString(request.ID) b.WriteString(" ") b.WriteString(client.Addr().String()) b.WriteString(" ") b.WriteString(time.Now().String()) r = b.String() DEMO: go test -bench=. ./examples/concat 6.3.5. Don’t force allocations on the callers of your API Make sure your APIs allow the caller to reduce the amount of garbage generated. Consider these two Read methods func (r *Reader) Read() ([]byte, error) func (r *Reader) Read(buf []byte) (int, error) The first Read method takes no arguments and returns some data as a []byte. The second takes a []byte buffer and returns the amount of bytes read. The first Read method will always allocate a buffer, putting pressure on the GC. The second fills the buffer it was given. Can you name examples in the std lib which follow this pattern? 6.3.6. Preallocate slices if the length is known Append is convenient, but wasteful. Slices grow by doubling up to 1024 elements, then by approximately 25% after that. What is the capacity of b after we append one more item to it? func main() { b := make([]int, 1024) b = append(b, 99) fmt.Println("len:", len(b), "cap:", cap(b)) } If you use the append pattern you could be copying a lot of data and creating a lot of garbage. If know know the length of the slice beforehand, then pre-allocate the target to avoid copying and to make sure the target is exactly the right size. var s []string for _, v := range fn() { s = append(s, v) } return s vals := fn() s := make([]string, len(vals)) for i, v := range vals { s[i] = v } return s 6.4. Using sync.Pool The sync package comes with a sync.Pool type which is used to reuse common objects. sync.Pool has no fixed size or maximum capacity. You add to it and take from it until a GC happens, then it is emptied unconditionally. This is by design: If before garbage collection is too early and after garbage collection too late, then the right time to drain the pool must be during garbage collection. That is, the semantics of the Pool type must be that it drains at each garbage collection. — Russ Cox var pool = sync.Pool{New: func() interface{} { return make([]byte, 4096) }} func fn() { buf := pool.Get().([]byte) // takes from pool or calls New // do work pool.Put(buf) // returns buf to the pool } 6.5. Exercises Using godoc(or another program) observe the results of changing GOGCusing GODEBUG=gctrace=1. Benchmark byte’s string(byte) map keys Benchmark allocs from different concat strategies. 7. Tips and trips A random grab back of tips and suggestions This final section contains a number of tips to micro optimise Go code. 7.1. Goroutines The key feature of Go that makes it a great fit for modern hardware are goroutines. Goroutines are so easy to use, and so cheap to create, you could think of them as almost free. The Go runtime has been written for programs with tens of thousands of goroutines as the norm, hundreds of thousands are not unexpected. However, each goroutine does consume a minimum amount of memory for the goroutine’s stack which is currently at least 2k. 2048 * 1,000,000 goroutines == 2GB of memory, and they haven’t done anything yet. Maybe this is a lot, maybe it isn’t given the other usages of your application. 7.1.1. Know when to stop a goroutine Goroutines are cheap to start and cheap to run, but they do have a finite cost in terms of memory footprint; you cannot create an infinite number of them. Every time you use the go keyword in your program to launch a goroutine, you must know how, and when, that goroutine will exit. In your design, some goroutines may run until the program exits. These goroutines are rare enough to not become an exception to the rule. If you don’t know the answer, that’s a potential memory leak as the goroutine will pin its stack’s memory on the heap, as well as any heap allocated variables reachable from the stack. 7.1.2. Further reading Concurrency Made Easy (video) Concurrency Made Easy (slides) Never start a goroutine without knowning when it will stop (Practical Go, QCon Shanghai 2018) 7.2. Go uses efficient network polling for some requests The Go runtime handles network IO using an efficient operating system polling mechanism (kqueue, epoll, windows IOCP, etc). Many waiting goroutines will be serviced by a single operating system thread. However, for local file IO, Go does not implement any IO polling. Each operation on a *os.File consumes one operating system thread while in progress. Heavy use of local file IO can cause your program to spawn hundreds or thousands of threads; possibly more than your operating system allows. Your disk subsystem does not expect to be able to handle hundreds or thousands of concurrent IO requests. 7.3. Watch out for IO multipliers in your application If you’re writing a server process, its primary job is to multiplex clients connected over the network, and data stored in your application. Most server programs take a request, do some processing, then return a result. This sounds simple, but depending on the result it can let the client consume a large (possibly unbounded) amount of resources on your server. Here are some things to pay attention to: The amount of IO requests per incoming request; how many IO events does a single client request generate? It might be on average 1, or possibly less than one if many requests are served out of a cache. The amount of reads required to service a query; is it fixed, N+1, or linear (reading the whole table to generate the last page of results). If memory is slow, relatively speaking, then IO is so slow that you should avoid doing it at all costs. Most importantly avoid doing IO in the context of a request—don’t make the user wait for your disk subsystem to write to disk, or even read. 7.4. Use streaming IO interfaces Where-ever possible avoid reading data into a []byte and passing it around. Depending on the request you may end up reading megabytes (or more!) of data into memory. This places huge pressure on the GC, which will increase the average latency of your application. Instead use io.Reader and io.Writer to construct processing pipelines to cap the amount of memory in use per request. For efficiency, consider implementing io.ReaderFrom / io.WriterTo if you use a lot of io.Copy. These interface are more efficient and avoid copying memory into a temporary buffer. 7.5. Timeouts, timeouts, timeouts Never start an IO operating without knowing the maximum time it will take. You need to set a timeout on every network request you make with SetDeadline, SetReadDeadline, SetWriteDeadline. 7.6. Defer is expensive, or is it? Historically defer is expensive because it has to record a closure for defer’s arguments. defer mu.Unlock() is equivalent to defer func() { mu.Unlock() }() defer is expensive if the work being done is small, the classic example is defer ing a mutex unlock around a struct variable or map lookup. Exercise: experiment with the example/mutex example, defering mu.Unlock and observing the cost. If you have Go 1.12 installed, compare the performance of defer. This is a case where readability and maintenance is sacrificed for a performance win. You may choose to avoid defer in those situations. Always revisit these decisions. 7.7. Make the fast path inlinable The size of a function, it’s complexity, affects the ability of the compiler to inline it. Mid stack inlining can be used to exploit this to make the fast path of a function inlinable. 7.8. Avoid Finalisers Finalisation is a technique to attach behaviour to an object which is just about to be garbage collected. Thus, finalisation is non deterministic. For a finaliser to run, the object must not be reachable by anything. If you accidentally keep a reference to the object in the map, it won’t be finalised. Finalisers run as part of the gc cycle, which means it is unpredictable when they will run and puts them at odds with the goal of reducing gc operation. A finaliser may not run for a long time if you have a large heap and have tuned your appliation to create minimal garbage. 7.9. Minimise cgo cgo allows Go programs to call into C libraries. C code and Go code live in two different universes, cgo traverses the boundary between them. This transition is not free and depending on where it exists in your code, the cost could be substantial. cgo calls are similar to blocking IO, they consume a thread during operation. Do not call out to C code in the middle of a tight loop. 7.9.1. Actually, maybe avoid cgo cgo has a high overhead. For best performance I recommend avoiding cgo in your applications. If the C code takes a long time, cgo overhead is not as important. If you’re using cgo to call a very short C function, where the overhead is the most noticeable, rewrite that code in Go — by definition it’s short. If you’re using a large piece of expensive C code is called in a tight loop, why are you using Go? Is there anyone who’s using cgo to call expensive C code frequently? 7.10. Always use the latest released version of Go Old versions of Go will never get better. They will never get bug fixes or optimisations. Go 1.4 should not be used. Go 1.5 and 1.6 had a slower compiler, but it produces faster code, and has a faster GC. Go 1.7 delivered roughly a 30% improvement in compilation speed over 1.6, a 2x improvement in linking speed (better than any previous version of Go). Go 1.8 will deliver a smaller improvement in compilation speed (at this point), but a significant improvement in code quality for non Intel architectures. Go 1.9-1.12 continue to improve the performance of generated code, fix bugs, and improve inlining and improve debuging. 7.10.2. Move hot fields to the top of the struct TODO: fill in or drop 7.11. Discussion Any questions? Final Questions and Conclusion Don’t do it. Do it, but don’t do it again. Do it less. Do it later. Do it when they’re not looking. Do it concurrently. Do it cheaper. Is it better to write clear code, or high performance code? I’ve given this workshop in many countries and without exception the first question I get is? What is more important, readable code or high performance code? My retort is; What is more important, love or money? I need to dissuade you of the necessity for writing the highest performance code, certainly if that comes at a cost to clarity, readability, or maintainablity. Readable means reliable. Start with the simplest possible code. Measure. Profile your code to identify the bottlenecks, do not guess. If performance is good, stop. You don’t need to optimise everything, only the hottest parts of your code. The fastest algorithm can frequently be replaced by one that is almost as fast and much easier to understand. As your application grows, or your traffic pattern evolves, the performance hot spots will change. Don’t leave complex code that is not performance critical, rewrite it with simpler operations if the bottleneck moves elsewhere. Always write the simplest code you can, the compiler is optimised for normal code. Shorter code is faster code; Go is not C++, do not expect the compiler to unravel complicated abstractions. Shorter code is smaller code; which is important for the CPU’s cache. Pay very close attention to allocations, avoid unnecessary allocation where possible. I can make things very fast if they don’t have to be correct. Performance and reliability are equally important. I see little value in making a very fast server that panics, deadlocks or OOMs on a regular basis. Don’t trade performance for reliability.
https://dave.cheney.net/high-performance-go-workshop/sydney-2019.html
CC-MAIN-2020-34
refinedweb
18,788
66.23
The DIS 29500 ballot resolution meeting (BRM) finished up in Geneva today and was an unqualified success by any measure. A few things need to be kept top of mind as national bodies solidify their position within the next 30 days: A BRM is about technical work on the remaining open issues most important to participating national standards bodies Extensive steps were taken within the last year to improve Open XML through work with national standards bodies (and their participants) within the inclusive framework of ISO/IEC processes. A BRM is successful if it produces technical improvements to the specification to address comments raised during the ballot phase. ISO/IEC standards are not only technically sound, but they should also be relevant to the marketplace.. If you would like to receive an email when updates are made to this post, please register here RSS PingBack from please, could you explain in non PR words what happened exactly in this BRM for example, would you tell us . which comments were voted? . what was the result of each comment vote . and which country NB voted what ? thanks Carlos - at this point, this isn't public information. ISO has rules concerning the confidentiality of their proceedings, so that will be up to them as to how they do that. Obviously the project editor will be working furiously to update the specification as per the BRM conclusions, but that is a separate matter. I'm not sure how each delegation will deal with the flow of information. I'm sure more specific information will be coming out shortly. THx Jason The Ballot Resolution Meeting for DIS 29500 (Open XML) has concluded on a very positive note. I hear "Carlos - at this point, this isn't public information. ISO has rules concerning the confidentiality of their proceedings, so that will be up to them as to how they do that." so, basically ISO is discussing an "Office Open" format in a "Door Close" way we are in 2008, we have the internet, we have mail, wikis, blogs, mailing lists, google documents, twitter, etc, etc, etc and we are discussing the digital formats for the next digital age during five days with any bit of information disclosed why on hell this kind of process is so closed? are you discussing a new military weapon or something like that? i --Carlos Carlos - how about a little balance here? ISO is a treaty-based organization. It is an international standards body that has years, and years, and years of proceedures. It is an inclusive process....for national standards bodies. It is open....to national standards bodies. Microsoft does not get a vote in ISO. IBM does not get a vote in ISO. It is one country, one vote. The ballot resolution meeting is part of a highly formalized process which has been designed to enable national standards bodies to participate in the process in a predictable, respectful fashion.. Thanks, ." please, *you* compose ISO ( i'm a poor final user [ and sometimes victim ] of standards ) , so please explain to "the leadership of JTC1" the following words: "transparency" "openness" "quality" "consensus" "technical merits of fast-tracked standards" ( i'm assuming that you and your employer *know* its true meaning ) To begin with, you can point the "JTC1 leadership" an example of balance between standardization work and transparent process: The closed dark ages ( monastery work ) are gone. Welcome to the open age. What are your fears[1]? Carlos [1] "that is why such overwhelmingly positive consensus was achieved during the BRM." "tI'll say it again - by any rational measure of ISO/IEC JTC 1 ballot resolution meetings, this one was a complete success." Jason, I cannot believe that you wrote such words after having read news from at least 5 other bloggers (some having spend the 5 days within the BRM room) who have exactly opposed conclusions. See for example Tim Bray's: "The process was complete, utter, unadulterated bullshit." "This was horrible, egregious, process abuse and ISO should hang their heads in shame for allowing it to happen." So, 6 countries out of 32 (according to Andy Updegrove) are an "overwhelmingly positive consensus" ? Did you calculated this using the OOXML defective formulas ? Shame on you and on Microsoft. Ok, I seem to have found the grumpy crew for comments on this one. 1) Carlos. Take a moment to consider that any specification going through the BRM process is subject to the same rules. The delegations from countries would be subject to the same rules. It has nothing to do with Open XML. We are members and participants in OASIS. We have more than 6,000 open source projects hosted on codeplex. Our product teams arguably produce more materials for developers to be successful than any other company. Yet, no matter how much we believe in, or build, technologies that enable greater transparency and openness - all particpants are subject to the same rules in ISO. Personally, I think it was very unhelpful, given the public discourse, during the months leading up to the BRM to have the comments password secured. But, my feelings in the matter are irrelevant. If you want a specification to move through the JTC 1 process, then it is a good idea to be respectful of the process. Luc - I absolutely knew what I was saying, and yes, read what was being said. Andy's tortured logic to get the vote count he is reporting is really quite something.. The folks I have been speaking with who were both in the meetings (as delegates) and who were on site said that there were many ups and downs, and drama throughout the week. But, in the end, real technical work was accomplished and the specification was improved. The comments from national bodies were all respected and throughout the 5 month process and the week in Geneva have resulted in some very sold standard work. The words I hear people using are "consensus" and "respectful" and "productive." I expect that those most opposed to the adoption of DIS 29500 will say the exact opposite of me. Thanks guys - keep smiling. This is a document format we're talking about here. I wrote a blog posting on perspective the other day following a health crisis with my father. I haven't lost that perspective - it might do everyone some good to get a dose of the same. :-) "Carlos. Take a moment to consider that any specification going through the BRM process is subject to the same rules" Jason, you seem to don't understand what i'm saying. I'm saying that you, members of ISO, start changing this closed nature of the standardization process, for the benefit of final users. If, for example, nine O-members who never participated in document and descripcion languages activities suddenly ask ISO/JTC1 to be upgraded to P-member status, prior to an important ballot voting, I, as a final user who will be affected by ISO deliverables, want to *know* that, so i can judge how "fear" was the process that put an ISO stamp on *that* standard. What do you want, that i should send a letter to JTC1 leadership to ask this? you , the corporations, are who have the power to change this things, if you really want to make it. Or may be is like the European Commission said recently: "Talk is cheap" Carlos - it is a fair point that those organizations who are participants in the national bodies have the responsibility to improve the system. Point taken, and one that I can assure you we are looking at. I think everyone agrees that international standards are likely to be come more important rather than less over the coming years. Although our competitors are decrying the process today, those same organizations were of the opinion that because their technology was first to ISO standardization it should become mandated by legislation for government procurement. My point is not to dredge up other arguments. It is simply that as eGov continues to be a more and more important factor, there will be increased pressure to have what used to be fine as consortia-based standards move to carry international standards labels. I am quite sure that our oposition on the Open XML spec will be pushing for changes in the JTC 1 rules. In the end, even that process is slow and deliberate in nature to make sure that no rash decisions are made. I hear you on the responsibility Microsoft carries - it is in fact a focal point of my job for the forseeable future. I understand that the BRM only had a mandate to consider responses to the previous ballot, so the lack of new comments during the meeting was simply a result of the process in action. If my understanding is correct, then I believe that pointing to a lack of "surprises" or "new comments" as an indication that the meeting was a success isn't a strong argument. I found your enthusiastic and emotional terminology that you used in the posting a little off-putting, including some cases where you were writing an opinion but the entry sounded like you were speaking on behalf of all: "unqualified success", "valuable input", "overwhelmingly positive consensus", "without question", "changes ... based on consensus ... is exactly how BRMs are meant to function", "by any rational measure... this one was a complete success", "rigorous review", "rich ecosystem", "diligent feedback". A couple more impressions: 1. You seem to point to the significant effort that has been expended on improving this specification as a strong indicator that the result is very worthy. I am not comfortable that this impression is justified -- I believe that this speaks more about the specification's past than it does speak about its current state. 2. My belief is that a standard should be seen as a contract brokered between parties, whereas I get the sense that you view this standard more as a gift for the wider community to consider accepting. I'm having some trouble in explaining my low-level disquiet at the very positive tone of your posting which is at odds with some of the other post-meeting comments I've seen; the nearest I can get to describing it is to point to the cliche that "a good negotiated agreement is often one where nobody comes out happy". I apologise that I can't describe my position any more clearly. Hi Jason, is that really your writing style? Sorry but this entry (like many others) reads like a press release, and I think that is part of the reason why you get such harsh reactions in the comments. People know press releases are pure spin. Let's take this entry as example: According to it, the BRM was the best thing since sliced bread. Very productive, all issues were addressed, couldn't have gone better (obviously, since you didn't mention a single, tiny negative thing about it). Tim Bray, who you caracterize as "very bright and capable", paints a different picture. Yes, people were genuinely trying to improve the spec. Good technical discussions. But the process was completely inadequate for a spec of this size with this many problems, and there were *no deliberations whatsoever* on the vast majority of issues. See Now I understand that it can be hard to write an even-handed blog entry, especially if your employer is the one responsible for fast-tracking OOXML. But this is no excuse for publishing PR propaganda on a blog supposedly written by a "normal" person. It's degrading to your audience. Just look at ex-Softie Robert Scoble on how to do it right. There is a reason he is respected in certain circles where other Microsofties (wink, wink) aren't. Cheers, Stephan Jason, Dismissing Andy Updegrove's report with a single-line insult doesn't really wash. Is it, or is it not, true that there was a ballot to accept, reject, or abstain from voting on, the majority of ECMA dispositions because there just wasn't time to discuss them? Andy and Tim provided substance to their descriptions of the proceedings. You're giving sweeping statements about it being "an unqualified success" while saying the other guys are just anti-OOXML. I know who I'm inclined to believe at this point. Certainly I wouldn't be calling a meeting a "complete success" when several of its participants say the exact opposite. An update: I've just read the OpenMalaysia blog, and while they are certainly pro-ODF, I believe them when they say they worked honestly and diligently to improve OOXML to the best of their abilities. Read their "Geneva, Day Five" post - - it's a description of a process so broken and corrupt that it can't possibly be taken seriously. The statement "We eventually found out that if any changes affected current implementations it would certainly be rejected" left me aghast ("current implementations", in this context, certainly meaning MS Office 2007, and no other). Jason, if you want to refute this, please provide something substantive rather than the hallelujah hand-waving that the rest of your replies to this thread have been. In plain English: The result of the BRM was a 70% defeat for your side and now you will try to lobby the national bodies to approve it anyway. Hey Carlos - Why didn't you, IBM, the FSF, Google and Updegrove not have any issues with the ISO process when ODF went through ISO? Just curious? Hey Jason - Tim Bray has gone out of his way to recuse himself from outside influences and to act fairly. He has previously distanced himself from extremism and has been willing to be critical of ODF. He spent the last week at your BRM without blogging and without discussing the BRM with his colleagues. Your dismissal of his opinion is hugely unfair, especially given his long experience of the standards process (longer, I suspect, than yours). You say "by any measure". I gather the vast majority of the open issues were voted "en masse" without being considered due to lack of time. Is that part of the success you're claiming? Jason Matusow said "The DIS 29500 ballot resolution meeting (BRM) finished up in Geneva today and was an unqualified success by any measure." Jason, do you believe that the following numbers ( abstention + no vote + refusal to vote totals ) represent an "unqualified success by any measure" ? Please explain, thank you ( to the casual reader: if you don't believe this numbers, demand ISO to disclose this numbers and check yourself )% Denmark% NO (MS HOD) 0 0.00% (*) "This is a document format we're talking about here..." It is a LITTLE bit more than that don't you think? If was just that, why have M$ been bribing NGO's in India to write to their Government to support OOXML? Why have M$ totally screwed the ISO process in SC34 by flooding it with P members who had little or no interest in document processing before or afterwards? Why has M$ spent SO MUCH money trying to steamroller a badly written, badly edited, inconsistent, proprietary specification through ISO/IEC as a FAST TRACK standard? It clearly should never have been put through as a fast track. over 1100 comments to be discussed and reviewed in 5 days. Honestly. Microshaft have really tripped up here. I hope this is start of a long decline into oblivion as your company truly deserves. Jason, could you please confirm the figures of Andy Updegrove, in summary : - 20 dispositions discussed in details - 200-ish editorial dispositions accepted without discussions - 900-ish dispositions decided without any discussion in 1 single bulk vote on Friday, by 6 votes for (4 P- and 2 O-countries), 4 votes againt (4 P-countries), 4 refusal to vote and 18 abstentions) (i.e. 6 positive votes out of 32). If you agree with these figures, what is your math to conclude that there was an "overwhelmingly positive consensus" ? My understanding is that this represent rather an "overwhelmingly negative consensus". If you don't agree with Andy's figures, what are your own figures ? Jason- Were you at the same BRM where they discussed that file format? The one in Geneva ... ... Switzerland? Guys - it is Saturday morning and I have a bunch of family things to do with my kids. I will get back to do comments later in the day. For a few of you who are taking Andy's numbers as gosple. I would point out the following comment that was left by the BRM convener. As for all the other numbers posted here - I simply can't say until I see the numbers from ISO. That would be the whole respecting of the confidentiality rules thing... On Andy's blog () Showdown in Geneva: OOXML Fails to Achieve Majority Approval at BRM. Jason, about Andy's numbers : - it is not a matter of gospel, but they are currently the only ones available. I would be delighted to read your figures, so we would have two "gospels" to think about. - please note that Alex Brown comments on the subject and rules for the vote, but doesn't comment about the resulting numbers. - "I simply can't say until I see the numbers from ISO": does that mean that you have see no figures yet ? If this is the case, how can you announce that the BRM was a complete success ? Jason I wouldn't spend too much time responding to this nonsense - spend some time with your kids, at least their childishness is due to their age! When a group defines itself by what it stands against rather than by what it stands for, a victim cultute frequently follows. When the focus of their opposition makes progress there's always the spontaneous outpouring of mock-outrage, and allegations of wrongdoing. Some of the commentators on this thread seem to believe the whole world is corrupt - an attitude that says more about them than the world they live in. So, sadly, it was entirely predictable that a small but very loud group would attack the BRM. This was obvious from the moment the "anti-BRM" event was announced. However the extent of the attack, and the chosen focus on undermining both Ecma and ISO during sessions when neither were in the room to defend themselves, was both cheap and unprecedented. Now it seems there's an equally orchestrated cry of "Penalty! Ref!" followed by a loud chorus of complaint about the referee being blind, and the game being fixed. The facts remain however 1. that there's significant acknowledgment that Ecma did a great job with the repsonses to National Bodies' comments even from within the ODF "camp". 2. The whole point of the BRM was always to accept or reject the proposed dispositions that would then modify the DIS text so that National Bodies that had given conditional approval can decide whether their feedback has been addressed. 3. The BRM itself decided a process to do this. 4. Given the BRM's objectives, and Alex's responsibilities to run a meeting that tried to improve the specification and drive consensus, both were successful. 5. The clique that equates being pro-ODF with being anti-OpenXML are seeking to bring the process, Ecma and ISO into disrepute - on that score both Tim Bray and Andy Updegrove have reason to feel ashamed. from what I read, there was hardly time at the meeting to deal with any of the proposed resolutions. It sounds very much like 'fast track' is inappropriate for a standard of such size with so many issues raised by the national bodies. I can't see how in the world one can conclude that consensus was reached. Nor can I see how objective observers can trust anybody who says it was. - Dan "When a group defines itself by what it stands against rather than by what it stands for .." Actually, it's Microsoft that stands agains broad ODF adoption (an ISO starndard). Like MS tryed to kill other open standards before. You know that exactly. So when you call the move of MS to kill yet another starndard to establish it's own ".. An Unqualified Success", the question remains who's success it is? Certainly not for the public. (Or in other words: Shame on you! Shame on Microsoft!) Dan nails it. To Tim Bray's credit, he's added a post that calls out the blatant spin and disregard for the truth:- "I." I think Tim's post poured fuel on the fire, but I am pleased to see him call out the nonsense. I wonder if Andy will do the same? If I read marc reaction correct than 19 countries present accepted more than 90% of ALL comments. That would suggest a big difference of interpretation with Andy UpdeGroves numbers. Probably caused by countries that voted approvals on most dispositions individually not being recognised by Andy (who as anti-ooxml blogger of course not not want to recognize approvals). However I find marc figures above also very strange as the czech repulic for instance show only 7 approvals whilst before the BRM already they had about 95% of their own 80 comments granted. Why would they not even vote on positive dispositions on their own comments ? p you write "Actually, it's Microsoft that stands agains broad ODF adoption (an ISO standard)" What gives you that impression? Microsoft stands against one sided procurement preferences - of course we do, but doesn't oppose ODF per se. In fact Microsoft supported ODF's adoption as a national standard by the US. Okay folks - where to begin? Many points made, much to be discussed. FYI - I will be bubbling up some thoughts to a top-level post as this comment thread is already very long. 1) Simon Phipps - I'll start here because I like Simon and because it touches on a few other comments. I said nothing derogatory about Tim Bray. What I did is point out that as a Sun employee he carries a bias as to what his desired outcome of the BRM was. Does he have more standards experience than me? You bet. As do many, many people. But I can assure you, my colleagues in Microsoft whom I work with closely on things that influence my blog are extremely experienced standards professionals. My role is somewhat similar to yours in being an ombudsman who works in the gray areas between product groups, business groups, legal teams, our field, and in constant contact with our customers and partners. But this is not on point for this discussion. Recherche (clever name) - You are right about the mandate to consider existing comments. I made that clear in my posting on purose due to mistatements I have seen about what takes place in the BRM. As for my choice of words - they are my opinion. Not sure why I wouldn't use those words, especially when I believe them to be true. I think the second part of your comment is well stated. You are correct that the specification was improved through the process. I know the arguments about what a FastTrack should, or should not be. At the end of the day, the Ecma specification is of high enough quality to be seeing hundreds of independent implementation projects of varying degrees. So the past is strong - the future is stronger. Does that help? Finally, I would not categorize my feeling about this spec in the context of a "gift" as you put it. Like thousands of other standards specs, Open XML is a contributed specification. In those scenarios a producer of a technology has taken their hard work and moved it into a standards body. That action is beneficial to the community as a whole, but also places responsibility on those participating in the process as well as the orginal contributor. PDF being a pretty good example of this. Governments and customers asked us to standardize our document format for Office. We have, and it is a good thing on balance for the entire ecosystem around MS Office and for any other software producers looking to utilize the specification. Thx - Jason hAl...how can you view the news that China didn't vote to approve any of the propositions to mean that it approved more than 90%? Japan, that is number 19 on the list did approve 9.06% and abst+no+refusal on 90.94% of them. Me again...I'm breaking my response to comments into smaller sections: Stephen Jaensch - You are correct that this particular post was with more formalized use of language. The media often quotes me from this blog as if they have interviewed me in person. Guess what, they do the same to Andy, Bob, Rex, Brian, and many others as well. You can't tell me that Andy Updegrove fairly sprinted to put out such a blog posting the moment the BRM ended, using the inflamatory language he did, because that is "just how he talks." He was looking to spin the situation and drive coverage with his work. Please - let's take a little bit more realistic view of things. No matter what, I stand by the text above and the points I made. And, if you are curious - I drafted the post. Rob Brown - you are right, I need to be more specific with my concerns regarding Andy's posting. I will write a top-level post to address that as I think it is worth doing. Andre - You are getting that number from Andy's post. The convener to the BRM commented on his post and suggested that he be more careful with his facts. According to the generally accepted practices of ballot resolution meetings for JTC 1, this was a very successful meeting. NO MATTER WHAT THE OUTCOME OF THE VOTE IS. I will address the point Andy makes in a top-level post. Marc - a few things. I'm quite sure it will be best for everyone to wait to see numbers from...oh, I don't know....how about ISO rather than you. I'm not sure what their schedule is, but I'm sure they will make an announcement about the BRM. If you did take these numbers from them, I would assume you are violating their policies in posting. That is on your head, but for now it is best for all of us to review and debate the actual results. The Open Sourcerer (also, clever name) - no, no...I'm pretty sure this is about document formats. The FAR, FAR, FAR more important thing is the functionality and value from the applications used to produce the data stored in the document formats. I have said repeatedly over the past 2 years that the app is significantly more important that the format. I also believe that if you limit the world to a single document format you are creating an innovation dead-zone that is unhealthy for everyone (producers and consumers alike). There is absolutely no basis for your claims about SC34 - and more over, as an adovcate of openness and participation (which is at least what the OSI says they are about) why would you disparage the inclusion of ANY participants to this process? The choice of a country to elevate themselves to P-member status is their choice. I welcome all of them to the process. More participatin is better in my opinion sir. thx I see now I misread the numbers in marcs post as I was fooled by the high numbers However that is also misleading to as we al already aware that about 98-99% of the items were approved. So making a list of approved+abstained would have even higher numbers. More from Jason: Luc Bollen - Andy's numbers will be addressed when the official results are released by ISO. I am going to respect the process even if he is choosing not to. As I said in other comments, I will make a top-level post to talk to Andy's assertions. Deep down here in the comments to this post is simply the wrong place to do that. As for your questions about my ability to make assertions - they are based upon the conversations I have had with people who were both in the room and working with the project editor, and TC 45. My willingness to comment or not on the ISO numbers specifically comes back to the same point about the process and respecting the confidentiality issues. Dan Kegel - check out what I wrote in the posting that you are commenting on. I explicitly speak about the fact that the BRM week has been one part of 5 months of work on the disposition of comments. The BRM was never going to be an item-by-item discussion. The national bodies had MONTHS to review the materials and were well aware of what issues were most important to them going into the week in Geneva. Please - reread the post. I think it will help you understand what I'm saying a bit more clearly. "p" - We have never stood against ODF. We have voted in favor of it on a few different occasions. If you believe in consumer choice as the best option, then you would vote in favor of your competitors specification. That is what Microsoft has done. Wow - I don't get your logic. The contribution of Open XML to the standards process benefits consumers, software providers, etc. There is nothing about our work on Open XML that in ANY WAY damages ODF. In fact, we have put significant resources into building translators. That does not mean that we won't compete with our products. That does not mean that we won't continue to seek the international standardization of Open XML. No shame in any of that. thx - Jason Fiery and hAL - I still think that you should be very careful with marc's numbers above. Are those the right numbers? Marc - would you be willing to tell us where you go those? I'll wait for the official ISO results, thanks. I looked at those number again with less beer in me They are definitly not the correct numbers unless Denmark has just been split up in two countries. Hello, Jason. I'm just an observer in all this, without any technical background. I don't consider myself anti-OOXML; if the standard is truly open and not unduly influenced by any single entity, I see in principle no reason to object. That being said, I have a couple of questions. I understand that you're invoking ISO confidentiality to put off talking about, e.g., Andy's numbers. But surely general comments, without mentioning specifics of who voted for what, wouldn't touch upon confidentialities. Do you think Andy's numbers bear any resemblance to reality? It would seem that any answer less than an unqualified "No!" is tantemount to an admission that there is significant opposition to approving OOXML in its current state. To "p" you said: "There is nothing about our work on Open XML that in ANY WAY damages ODF. ... That does not mean that we won't compete with our products." Since the ISO already has an open document standard, what is MS' rationale for expending huge resources in pushing for a second? If MS has technical objections to ODF, certainly it would be easier to fix a broken standard than try to develop a new one from scratch. Since it's difficult to believe that Microsoft has suddenly got open standards religion after decades of holding its .DOC standard so close to it's chest, what is MS' business rationale for seeking a separate-but-equal standard? As to "damaging ODF", I think your reply is a bit disingenuous. Given MS' near-monopoly in the office space, if OOXML is approved and MS Office continues to withhold support for ODF, ODF's ability to compete *is* significantly damaged. Redmond is well aware of this. Finally, what is your objective assessment of OOXML's chances for approval this year? CJ Mr. Jason, I was at the BRM and you are completely misleading everyone. You are a marketing guy with ZERO technical credibility to post this blog. marc's numbers are meaningless (or at least, if they reflect anything significant about the vote I can't fathom what it is!) - A." Why doesn't Microsoft offer its customers to chose which format meets their needs best? The only purpose of the OOXML ISO process is to get the public sector to adopt OOXML as to secure the income stream from Ms Office licensing. But as a tax payer I want my government to negotiate harder with Microsoft. I want it to be strong and put your company under pressure to reduce license fees of its overpriced products and support a file format that puts competitors on equal footing. Who guarantees the user that Microsoft will ever implement the ISO format? It is very likely that it will just use the ISO stamp for marketing. You know very well that the format of Word2007 is not the same as the ECMA standard 376. As we already have the ECMA 376 format that will hopefully get fixed with the ISO BRM input etc. I see no need to approve OOXML as an immature ISO standard because ISO standards require a higher quality than you were able to offer to us. It is time to step back for your company. forgetting all the numbers, how come your perspective of "unqualified success" is diametrically opposed to the view of everyone not employed by Microsoft? "We have never stood against ODF. " Do you really beliefe that people are so stupid not to see why MS tries so desperately to have its "own" document standard? "If you believe in consumer choice as the best option" *LOL* MS believes in consumers choice as long as everybody buy's their software. So where's the format choice with MS Office? Standards are useless if everbody is cooking his own. You know that exactly. If you believe in competition: let's see what happends when MS Office uses ODF as it's primary format and kills OOXML. Then, you'll have consumer choice. But MS would not like such a future, would it? The MS Office cash cow gone all of a sudden .. "I also believe that if you limit the world to a single document format you are creating an innovation dead-zone that is unhealthy for everyone" That's absurd. Why on earth do you believe having more than one standard for a data exchange format bring any competition to the table? A standard is fixed. Being fixed is it's primary value. There is not only no need for competition, it's harmful. I wouldn't call the internet an "innovation dead-zone" just because there are single HTTP/HTML/etc. standards. Quite the opposite: Innovation was possible because there was a fixed data exchange format / protocol that was not going to change year after year. So everybody could build innovation on that basis and be sure that his investment was protected. What is really annyoing is the hypocrisis of Microsoft; All the talks about standards, openness and competition when they really only try to bind customers to their own software and services by cooking their own format soup. Sad.: So what if, by some miracle, OOXML gets ratified as an ISO standard. Then what? What does that do for your customers who CAN'T MIGRATE TO OFFICE 2007 BECAUSE IT IS TOO FULL OF COMPATIBILITY PROBLEMS???? Won't that leave Microsoft with a shiny new ISO standard that very few people can even use, because your own software designed to use it is TOO INCOMPATIBLE TO MIGRATE TO???. I wasn't going to leave a comment here, but since someone else left one here under the name "Andy" I wanted to clarify that it wasn't one left by me. Since I'm here, though, here are a few out of the many comments that I might leave: 1. Like you, I've received lots of information since I wrote the post you refer to (in fact, I wrote it between 4:30 and 5:30 in the afternoon on Friday while the information was coming in, not in advance). Unlike your post, I've continued to update it to conform it to further facts as they come in. Anyone who hasn't read it in a day or two should look at it again, as there is a lot of new information. I've also posted excerpts and links from 8 delegates who were in the room. There are also some interesting exchanges between Alex Brown and I, where we trade views on whether it was better to have done the 900 block vote or not. 2. My figures come from the SC 34 Web site and were given to me by a delegate. We will have to wait and see whether ISO/IEC JTC1 releases the exact numbers and countries or not (I had, but did not release the countries). I totally reject that an organization that purports to set "de jure global standards" for preferential adoption by governments has any business keeping the facts about how their "open" standards are determined secret from those that are affected by them. Fortunately, many delegates agree, and are therefore sharing their stories. 3. I have not tried to verify the by-country numbers that someone has posted at your blog and mine seeking to show the disposition voting by country. I also find it difficult to figure out exactly how they are presented, and therefore hard to draw any conclusions from, even if the original numbers used as a source are accurate. 4. I've modified my view of the proceedings somewhat. Abstentions shouldn't be viewed as rejections, but neither should they be viewed as approvals. Each NB that abstained voted on as many of the individual dispositions as it wished, from a few to many. It abstained as to the rest, and therefore no conclusions can be drawn relating to those dispositions as to which it did not check off a specific vote . I've received email from several delegations indicating that they couldn't even try to vote on most of the 900 dispositions, since the ballot was distributed one afternoon and due the next morning. Recall that the dispositions document was some 2,300 pages long, and 900 is c. 80% of the dispositions. That's a long and impossible night's work, especially for those delegations that hadn't completed the process in the weeks (not "MONTHS") since the complete dispositions were made available. Note also that some delegations had only two people. 5. Neither ISO nor IEC are treaty organizations, although the ITU is. 6. My reaction to your blog post was also that it sounded like the talking points that would be delivered all over the world. I expect that they will be. 7. Your conclusions cannot in any way be squared with any of the accounts that I have read (8 now), representing pro-ooxml folks, anti-ooxml folks and neutrals. Voting on the 900 dispositions was a last available compromise adopted as a way to attempt some sort of statement on all of the dispositions. The result is far, far, far less than would be accomplished in a normal BRM. To pretend otherwise is to be either incredibly naive, or deliberately deceptive. 8. The BRM displayed once again how woefully inappropriate a Fast Track process is for a specification of this length. The attempts to still keep within that process simply became even more desparate and less able to deliver the necessary quality of result expected from the standards process. 9. I find it incredible how often you, Doug Mahugh and others rave about "how much better OOXML is now!" as if this was some great thing. ODF sailed through with _no_ significant comments, and did not need a BRM at all. To have submitted a 6,000 page specification under Fast Track at all was regrettable. To submit somethig in this poor shape was unconscionable. To subject the BRM delegates to this miserable process and then take advantage of their efforts by calling it a huge success is pathetic. In conclustion: It would have likely taken Microsoft fewer engineer-years of effort to implement ODF in Office 2007 than it took engineering years for all these delegates to prepare for and attend the BRM,and certainly been far more beneficial. And your customers would have been better off and happier if they did. Speaking of which: I'll close with a story from Geneva last week. You mentioned above, i think, that Microsoft did not attend the simultaneous OpenForum Europe event. In fact, there were one or more Microsoft representatives in attendance all the time. In one panel presentation, Nick Tsilas from your legal department, and someone I've known for years, tried once more to say how Microsoft's customers haven't yet asked for Microsoft to implement ODF. Unfortunately, he picked the wrong panel to make that claim, because one of the panelists on stage just then was Dr. Rolf Theodor Schuster, the CIO of the German Federal Foreign Office. Rolf lit into Nick in no uncertain terms, saying that his office had demanded that Microsoft implement ODF and not OOXML. After "listening to its customer," Microsoft responded by going over his head to his superiors and getting these bureaucrats to tell them not to worry about it. Nick tried to make the same claim again, and Rolf really ripped him a new one. Jason, people generally think you're a good guy. But this blog entry is so far out in left field that I don't think that I'll be hearing that as often as I used to. Go give a read to the first hand accounts I've compiled at my blog, and then let us know whether your blog entry requires modification, will you? A final thought: I heard many, many first hand horror stories from National Body delegates while I was in Geneva. Here's a sample: inone NB, the vote was 8 to 1 against OOXML last summer. The 1 vote to approve? The Microsoft employee. The result? An entire country had to abstain in the vote, because one conflicted (new) committee member took advantage of the unanimous voting rules of that country. Of course, I also heard from many delegates that each European country has received a formal request letter from the European Commission calling for the disclosure of all bad acts that Microsoft had performed in the process so far as part of the EC's new antitrust investigations. This blog entry will, I expect, make them be even more attentive to what they hear in response. In over twenty years of repsresenting standards bodies, I have never seen anything like this before, and I certainly hope that I never do again. - Andy (Was previously "recherche" (thanks for the compliment), but this name change seems appropriate.) Interesting that you mention PDF. I note that Microsoft is in the process of getting XPS (XML Paper Specification) through the ECMA treatment in order to propose it as an ISO standard. If XPS is to PDF as OOXML is to ODF (and I acknowledge that both the direct comparison between XPS and PDF may be misleading to some extent, and also that mapping this pair across to OOXML/ODF may be misleading to some extent), then a look at how "open" XPS is is not entirely comforting: * As of 1 July 2007, devices advertising "Certified for Windows Vista" are required to have XPS drivers: * The XPS Print Schema License is not compatible with the GPL, so the freedoms granted to users are limited and downstream parties may need to deal with Microsoft directly to access Microsoft Intellectual Property: * XPS handles fonts differently from PDF, mainly as a result of its requiring that fonts be embedded, or else the text must be rasterised. This seems to make PDF less attractive than XPS in some situations: * As an aside on fonts, I note that all fonts used in Vista are owned by Microsoft, and "individuals, graphic designers and businesses" may purchase licenses to use them from Ascender Corporation: . * Also on the font front, I note that the EU ruled that the font Segoe registered by Microsoft as Design Patent US D496,392 S as a forgery of a Linotype GmbH font. "A registered design is protected for a maximum period of 25 years, in 5-year chunks...". How "open" is a user's font choices under Vista and Office 2007? If a user has preferences or requirements in font selections for various documents, how do the applications deal with this desired freedom of expression? I notice that Microsoft is "committed to delivering [XPS] viewers for Windows Vista and downlevel versions of Windows [...] and directly or through partners, for a range of other platforms." I note that Windows Vista comes with XPS Viewer installed by default, and that Windows XP users can download a Pack to enable Internet Explorer to serve as an XPS viewer. Are there XPS Viewers available for any other operating system? Is there any commitment, preferably including a delivery schedule, for the provision of XPS viewers for any currently-unsupported OS? Looking as a non-member of the Microsoft product ecosystem, I believe that choosing XPS over PDF would compromise my flexibility in downstream choices, and so evaluating the costs and benefits of any such choice would be a non-trivial exercise. Given these concerns regarding XPS versus PDF, I believe that there is some similarity between this situation and the Microsoft-ecosystem concerns that some parties have expressed when evaluating the risks and benefits of OOXML versus ODF. This has been a rather long and rambling comment, and I accept that you may not agree with some or all of my premises or conclusions, and I respect your opinions. recidivist/recherche (and already starting to search the dictionary for the next compatible moniker in the namespace-o-sphere...) Mr. Bray - Hello sir. I'm sorry you feel that way. I have been deeply involved with my company's work on this topic for the past 2 years. After more than 15 years in the software industry, I have opinions on many things and I write about them - I hope with some level of erudition. If you don't like what I'm saying...ok, please let me know why. (Comments sections on blogs are very good for this sort of discourse.) Those reading the blogs will make up their minds hopefully after the careful consideration of multiple points of view. Alan - maybe you missed the fact that is not the case even in the comments on this list? Also, that one of the commenters who has expressed concern with the way those opposed to the DIS are portraying things is the convener of the BRM himself? P - WOW, we disagree on so many levels. That is what makes all of this conversation so great. Okay - to be brief. 1) I have ALWAYS stated my belief that all of the flap over document formats comes down to product competition. Microsoft wants to build and sell Office...yep, for profit. Guess what, IBM and Sun want to build software for money too. And yes, the doc formats are a lever for that activity. No high horse there for any of us. But, I do not agree that the profit motive kills any ability to have rational conversation about choice. When I talk to customers, they say they want choice. I agree that is best. What it really means is that our products have to have the best value and capability if we want people to choose it over their other optinos. 2) The idea of having competiting standards is another thing you and I disagree about. Just because one technology is standardized, does not negate the value of another technology that achieves similar goals. Should TCP/IP have not happened because ISO approved OSI? Come on...really. Market forces apply, and that is a far better environment for this choice than through mandates that we should always only have 1 option because someone was first to standardize it. 3) A standard is decidedly NOT fixed. They are modified over time to adjust to work with new technologies and innovations. What's more, as new innovations take shape, they may supercede the functionality in the standard and that is where competition will really come into play. 3) Your memory of HTML is a bit flawed. There was huge change over time around that technology both within the technology itself and in all of the associated capabilities around it. Next, I think the area of protocols presents different factors where commonality will play a stronger role than at the higher-level functions of a document format. I think you are getting at some very fundamental questions underpinning standardization in the software industry - but I think your conclusions are wrong. Thx Luc, "- 900-ish dispositions decided without any discussion in 1 single bulk vote on Friday" It was not a bulk-vote in the traditional sense. I have explained in more detail on my blog at From this: [... know the discussion here is over by now, but I wanted to respond anyway (I was away for the weekend). Jason, I agree that Mr. Updegrove's blog entries are often as full of spin as are yours (sorry). I don't consider them "better" just because he happens to be pro-ODF. On the other hand, I highly value Rob Weir's blog. I'm a software developer, and what he writes just makes sense. He wins about every technical argument, and when people like Brian Jones try to answer/rebut him they just don't do as good a job as him. He clearly has the technical facts on his side. But I do realize that is very hard to judge for a non-technical person. His latest entry is an eye-opener. It seems to be an accurate report from the BRM, and the best one I have read so far. It echoes what Tim Bray has written. Two first-hand accounts from people with indisputable technical knowledge and experience. And unlike what you and Brian wrote, their reports make sense. How can you work on more than 1,000 comments in one week? Of course you cannot. Every report that says otherwise has to be spin, has to be propaganda. They were able to work on about 200 comments in one week, and that sounds like a reasonable number. The other 800 were never discussed. The process has failed. "Alan - maybe you missed the fact that is not the case even in the comments on this list? Also, that one of the commenters who has expressed concern with the way those opposed to the DIS are portraying things is the convener of the BRM himself?" Jason, please see the comment left by the same "Alex Brown" ( if he really is THE Alex Brown anyway) on Tim Bray's blog. Tell you what I'll show it to you here just in case you miss it: Regarding Tim's "Toxic Leech" blog post, Alex Brown writes: ." Well, having just read blogs by Tim Bray, Andy Updegrove, Jason Matusow and Brian Jones, along with a lot of interesting comment, I am now much better informed about the BRM process than I was, and am astonished at the chutzpa of the Microsoft people, who claim joy and consensus in what appears to be direct contravention of the reality. I'm with Dan Kegel on this one, and also find it incredibly hard to believe that Jason actually believes what he is writing: assuming Jason's response to P above is not pure bullshit, then he really does have a view of the world that I simply cannot understand. And particular thanks to those who have posted actual numbers rather than simply say 'it's a secret'. Whilst this is technically 'only document formats', the result is going to have a significant long-term effect on the world. I await the final vote with interest - it looks like things could still go either way. Stephen said "Microsoft stands against one sided procurement preferences." You mean except when those preferences mean that MSFT gets all of the business? lol Seriously Stephen. Your company's practices which serve to disrupt a fair procurement process are well documented. Ecma International released its comments on the BRM. The Ballot Resolution Meeting was a very productive Another Rashomon epic of a standards meeting. Who knew so many cared so passionately about document formats? 1. Transparency doesn't always work. See post-French Revolution and Jean Paul-Marat. When the polarities are this strong, the chances of easy consensus are effectively zero. Polarities are not resolved; they are managed. That is what ISO guarantees: management. The rest is up to the members. That's how we avoid the blade in the bath and the guillotine. 2. Having read most of the blogs, the one message that seems consensual is the current BRM meeting term of one week is inadequate for a specification of this complexity. The convenor/chair/whoever should have the flexibility to schedule a second week with the work items set to follow-on. ISO can be more adaptible. The web evolved towards the ascendancy of the trolls. Then it went subterranean. It may be time to start work on a system to replace it. The Elves "those same organizations were of the opinion that because their technology was first to ISO standardization it should become mandated by legislation for government procurement." Perhaps they were motivated to try get it mandated not because it was first, but because it makes sense to mandate a single open standard format for public information content. Having any more than one standard just causes problems. Everyone is free to use (and help improve) the single standard (ODF) format. Including Microsoft. I think a rational use of the United State's economic resources was also a motivation here - there is a community made of members from many companies that helped create and support ODF. The proposal was to require the government to use one standard open document format, so that public data is not held captive by a single software company and that use of public documents does not have to be done by using a specific company's software. It makes no sense having two standards because nobody is excluded from using the first. And having two dilutes the benefits of having a standard at all. Microsoft was a member in the ODF standards group - it's not like this format came out of the blue at you! Why ODF and not MOOXML? Several good reasons: timing (only one is ISO standard right now), technical merit, and current multi-vendor support of ODF (which proves it is a good standard). "If you believe in consumer choice as the best option, then you would vote in favor of your competitors specification. That is what Microsoft has done." First of all, why does Microsoft look at ODF as the 'competitors' format? Why not just consider it the open format, support it, help it grow and mature, like many other companies are doing, and do something positive for the world? Secondly, you are hurting the customer by proposing a second standard format because implementors of software will have to choose between the two (or spend a lot more money doing the same thing two different ways). Either option hurts the customer: more incompatibilities (two types of documents in the enterprise/government/home files), and higher prices (more development/testing effort because of the redundant work of supporting two formats. If you asked them, you would find that customers would prefer to have one format, and a choice of many applications from many competing companies. That is the choice that you are denying them by 'giving' them the choice of formats. Why don't you ask them if they would prefer two formats, and the incompatibilities that will result in,or one format, which is already supported by a number of top-notch word processing and other applications supported by a number of companies? Thirdly, despite what you say, Microsoft is voting with its feet (and software support) against ODF. The MOOXML format is, according to many technical reviews, much more complicated compared to ODF. That would probably not even make it a good candidate as the open document standard even if there was not one already. And by not making ODF the default save format in your apps, you are voting against it. And finally, based on your response to P, it does not seem like consumer choice is your primary concern, revenue generation is. Well, thanks for being honest about it, but not all companies have the same guiding principle as Microsoft (I mean greed here, not honesty). So looking at this with vendor lock-in profit margins as your base motive......I guess it is time to bring up the M word. Monopolies that do what Microsoft continues to do have been broken up in the past. You are just in a field that not many people (or judges) understand, and so as an expert you can lie and get away with it. And software is difficult to get right even when you are trying, so when making things incompatible is a goal you don't have to do too much to achieve it. That might benefit your shareholders in the short term, but the past history of monopolies proves it is not the right model for the long-term stock holders, or any of the customers at any time. So how about this: stop the FUD machine and do the right thing - drop MOOXML and join the team, the rest of the world, on ODF. If you can produce the best software that uses the format then you have nothing to worry about. You will get paid. But if you don't, take notice: the consumer is tired of incompatibilities, and the consumer is getting smarter. Incompatibilities are like tolls on the roads. They waste resources, energy and time that would be better spent simply moving forward. Having two formats just sends us again down the toll road of incompatibilities. You could get away with using incompatibilities between versions in the past. Those days are over. We all now know that it is possible to standardize a format to allow many different applications to share data. So there is no need to break compatibility simply because you are upgrading to a new version of the same software. Everybody knows it is easy to do if you are guided by the right principles. @John G: very wise and well thought post. I'm sure the Microsoft managers, who are clever guys, know this, but they are too busy maximising short term profit to act accordingly... (sigh). As Stephan Jaensch said above, this discussion appears to be over. However, I would strongly urge anyone interested in alternative viewpoints to read Andy Updegrove's blog. He links to, summarizes and quotes from, the blogs of a number of delegates, and they all seem to paint a picture diametrically opposed to Jason's "unqualified success" -- a picture US delegate Rob Weir called "The Art of Begin Mugged", and Australian delegate Rick Jelliffe styled "The Hell of Geneva". Pictures of national delegations refusing to vote in protest, tempers flaring when all discussion of technical issues was summarily cut off, and ire directed straight at Microsoft and ECMA for putting the delegates in this predicament by trying to ramrod through a standard that is nowhere near ready, and by no means qualified for fast-tracking. As Andy Updegrove called it, "process abuse" indeed. How to square Jason's "unqualified success" with the views of so many delegates actually in attendance is left as an exercise for the reader. One can only hope the national delegations remember the experience at Geneva when the time comes for a final up/down vote on March 29. NCJE Culver I work as a freelance translator and I have been suffering from Microsoft incompatibility for years, its not just interoperability but actually incompatibility between different versions of the monopolist's own office package! This must be either to force consumers to upgrade, or plain incompetence on the part of MS.. Since I've been using OpenOffice, this has actually improved, as the OpenOffice conversion tool produces better formatting for the various MS Word versions than MS Word itself.. I can't wait for the day when the ISO-approved ODF becomes dominant, there shall be NO looking back.. Unqualified success - with qualifications: [...] the process was complete, utter, unadulterated bullshit” - To those that argue that ODF should just have been improved with Microsoft's assistance - what do Microsoft's customers do in the meantime? Should Microsoft rip out a bunch of functionality in their products to then just allow the sparse functionality that ODF contains, until the unlikely event, (10 years down the road, given ODFs pace of progression) that ODF has caught up with maybe representing Office functionality as of 2007. What would an Excel user do if they had to downsample all their existing files to ODF, for example. Who is going to pay for their time to try and solve all the problems, even if they can be solved, for the thousands of existing files they use on a daily basis. What I don't see here is any real world scenarios from the "all files will be ODF" crowd. Scenario 1 - Conversion of depreciation analysis spreadsheet using simple financial formulas. -Sorry, no formula support (in a ISO format designed for spreadsheets !!!!!!!!), cannot be described by ODF. It may just be me, but if I had come up with a spec with that kind of hole, my a55 would have been canned. You might have assumed with the rigorous, multi-year process for ODF that some bright spark might have said "wait a minute, don't we need formulas for spreadsheets". Obviously not, since no comments were raised, no BRM, just sailed through as is. Everyone else involved in the process must have been 'leading experts' on office documents to have let that one through. Excel is my area, but I wonder what happened in the other pieces of ODF - no page breaks? no right justification? no columns? no headers or footers? To me they are as glaring as no formulas. If Microsoft were ever going to go "open", they had to do it sometime and the specs were going to be complex. Don't try and tell me that anyone **CAPABLE** of creating a top class competing Office suite is going to find it too hard because of the size of OpenXML spec. It will take a lot of time and a lot of testing, but that's life. So does trying to implement position-perfect PDF text parsing. The making ODF better idea is easy to say, but impossible to do. It's just StarOffice/OpenOffice's file format, just as Open XML is Office's format. The difference is, that after the BRM, at least it is less like Office's format and a bunch of folks outside the vendor got to pitch in with good ideas. It's like gasoline and diesel, they are certainly incompatible, but they both have their place. If you want to power an 18-wheeler with a petrol engine, be my guest, but I'd rather have the tool for the job. I'm sure I would be happy with Google Docs or OpenOffice with a full rigorous ODT implementation for my record collection spreadsheet, but if I'm doing a complex reconciliation, risk analysis using Monte Carlo or using UDFs developed internally by highly paid derivatives pricing experts, then it will be Excel until the competition has grown up and realised there is a bit more to spreadsheets than they currently know about. Gareth The reason ODF got through, is that the bar was too low, the reason Open XML is having a hard time is that the bar is very high. That's a good thing, but claiming ODF is the answer means that you have to go backwards in functionality terms. Try selling that to an existing user and I doubt they will be interested in upgrading. If you think that is OK and all software should be free etc, then fine, but that is a different forum. I dont understand why the adoption of another standard would 'kill' another existing standard. Are you guys so stupid that having an option kills your 'freedom to choose'? If China submits UOF to the same process.. in which the Market size alone could be bigger than all of your ODF 'downloads'.. would you stop that too? Cmon Guys.. get a LIFE! You still have your FREE WILL! If you dont like the other standard then just DONT USE IT! You are nothing but ABMs (Anything but Microsoft) - Take a break and fire up Windows XP and play World of Warcraft. Let off some steam. Even better.. just sing the OOXML 'Document from Hell' theme song. Global Warming, Wars and Famine - much more important. Jason, MS *could* be a good corporate citizen. Instead, we see absolutely obvious corruption of the ISO process. I understand that you are paid to put a face on a faceless entity. So, you sold your soul for how much again? Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.
http://blogs.msdn.com/jasonmatusow/archive/2008/02/29/the-open-xml-ballot-resolution-meeting-brm-was-an-unqualified-success.aspx
crawl-002
refinedweb
11,046
70.53
0.01 Wed Jul 3 19:19:46 2002 - original version; created by h2xs 1.21 with options -n Data::Type -X 0.01.01 Migrated from 'Data::Verify' to 'Data::Type' namespace Removed the pre-alpha disclaimer from README This now is alpha software added IType::W3C Interface where types from are implemented changed 'Function' namespace to 'Facet' conforming w3c added HEX, BINARY types 0.01.02 * Introduced various changes, thanks to posted by Henrik Tougaard via RT - 'DATE' type now accepts parameters DATE( [ 'MYSQL','DATEPARSE' ] ) where MYSQL (default) is the mysql builtin data type behaviour and DATAPARSE leads to Data::Parse's str2time function use. - Introduced locale support (added empty package Data::Type::Locale) - separated localizable type parameters to methods, so they are overridable through inheriting localized types: Example Type::dk_yesno vs Type::yesno (snipped sourcecode): { package Type::yesno; our @ISA = qw(IType::String); sub info { my $this = shift; return sprintf q{a simple answer (%s)}, join( ', ', $this->choice ) ; } sub choice { qw(yes no) } package Type::dk_yesno; our @ISA = qw(Type::yesno); sub export { qw(DK::YESNO) }; sub choice { qw(mand kvinde) } } * Export names for types are now accessible via 'export' method ( dk_yesno => DK::YESNO for instance ). * Types now have their own $VERSION * Some minor changes - rename IType:: info() to desc() for better distinguishing in toc(), because of a bug during @ISA traversal and IType:: identification (added _unique_ordered for using only unique desc's). - toc() now lists also export alias's - regex's are now centralized and accessible via Regex::list( 'key' ); 0.01.03 * Changed the Data::Type::Guard attribute 'types' to 'allow', because was ambiguous with types per se. * New group IType::Business (see toc). * Some minor changes - toc() now sorts types alphanumeretically - IType:: Groups also get version - added type version number to catalog() output 0.01.04 * added dverify( ) which is die'ing instead of throwing exceptions to the people: dverify( $email, EMAIL ) or die $!; * renamed 'choice' method for Type:: types to 'param'. * Some minor changes - Type::* package now supports new method C< sub depends {qw(CPAN::aModule)} > for retrieval of a dependency tree, which type made Data::Type require what. - added Data::Verify::depends() which returns a dependency list for types requiring other modules. 0.1.5 * Introduced: - %Data::Type::alias holds alias names for types (these listed by export method) ie. package Type::something; sub export { qw( a1 a2 ) } results $Data::Type::alias{a1} returning 'something' etc. - New version numbering with cvs revision number ( <main version>.<cvs revision> ) * Bugfixes: - forgot dverify() to export. 0.1.6 * Added complains(), an alias to testplan() (which is planned to become deprecated). 0.1.12 * Facet:: now could have C<usage()> method * Facet::match now has new syntax match( REGEX, DESC ) while DESC is a clear textual describtion of the REGEX function. This is used for complain(). 0.01.15 * verify now uses $_ per default, if only one argument is given. * matches() introduced as an alias for dverify(). It exported per default. * renamed matches() to is() * Added Locale::Maketext localization. - Accessible via $Data::Type::lh->maketext( ) - Served through Data::Type::L18N packages. [Note] In first line, this is for international error reports. This should help promptig ie. Webusers in front of an cgi-form. * Renamed everything from Type:: to Data::Type:: Filter:: to Data::Type::Filter:: Facet:: to Data::Type::Facet [Note] Now we don't pollute anyones namespace. Everything is beneath C<Data::Type>. * C<Data::Type::IType::UNIVERSAL> got C<alias()> method which returns the exported name of that type. * 'summary()' is the new name of 'testplan()' (which was 'complains()'). 'testplan' is removed from the export symbols and 'summary() was added instead * C<pass> and C<fail> renamed to C<ok> and C<nok> (more intuitive). * Renamed type "OS::PATH" export name to "PATH" * Removed 'alias()' method from IType::UNIVERSAL because export() does the same. * Renamed Data::Type::IType::UNIVERSAL to Data::Type::IType. * C<summary()> - now returns Data::Type::Entry objects instead of simple aref. - new usage: ( VALUE, ENTRY || [ ENTRY, ... ] ) * t/describe.t renamed to t/summary.t * removed C<nok()> - C<ok> now takes a bool argument if awaiting success/fail * Usage changed: C<verify( $value, $test )> C<dverify( $value, $test )> * Data::Type::Exception now has public C<catched> which holds the array of preceding exceptions which induced it. * @Data::Type::err holds the list of negative exceptions when C<dverify> alias C<is> fails. Syntactic sugar: unless( shift and is BIO::DNA ) { print Dumper \@Data::Type::err; } LOCALE - Types suffix the l18n language code: TYPE::DE for "de" (german). [Note] You would need an implicit Data::Type::L18N::de package. Only C<type export> names with a correspondent ::L18N::xx package should be allowed. This may not make sense when no localization is needed, but it will prevent consufion. - Data::Type::l18n_list() returns the implemented localized packages FACETS - move C<Data::Type::Facet::Proxy> to C<Data::Type::Facet> - now every Facet isa C<Data::Type::IFacet> (empty) API - renamed C<verify> to C<valid> - Data::Type::Facet::match has new usage - Data::Type->filter now wants list of [ 'filtername', @args ] - Data::Type::Object::*->test and Data::Type::Filter::*->test now doesnt take any args. Instead Data::Type::value is consequently used. - added C<isnt> as an alias for C<no is( TYPE )> - Relaced 'IType' with 'Interface', so we got 'Data::Type::Interface' instead of 'Data::Type::IType' Replaced 'IFacet' with 'Facet::Interface', so we now have 'Data::Type::Facet::Interface' REGEXPS - Every regex now lives in $Data::Type::Regex::registry - Dynamic regex generation via coderef support (with arguments). - Access via C<Data::Type::Regex->request( )>. This is a step further to facadeless gateway to Regexp::Common (Hopefully will save a lot maintainance time). moved Data::Type::Exception related objects to Data/Type/Exception.pm added the HTML type (thanks to HMTM::Lint) Rename/prefixed the Data::Type::Object:: packages with std_ for Collection - STD::, W3C::, BIO::, CHEM:: and DB:: 0.02.01 [Major] Data::Type::Regex moved to a independant module "Regexp::Box". See CPAN.
https://metacpan.org/changes/distribution/Data-Type
CC-MAIN-2016-07
refinedweb
1,005
55.74
FAQs FAQs This page details common problems - FAQs - Platform - Compilation/Runtime Errors - Data Errors Platform What platforms does dotNetRDF run on? dotNetRDF runs on .Net 3.5 Framework and higher, builds are provided for various framework profiles on the different versions of the framework. Exact supported features depend on the build used, see Getting Started for more details on the builds. dotNetRDF will also run under Mono 2.8 and higher, generally we recommend using the newest Mono release possible for best results. Compilation/Runtime Errors How do I compile dotNetRDF myself? Firstly check out the source from this BitBucket repository. Once downloaded you can either open the solution in Visual Studio 2010 or build via the NAnt scripts. Building via the NAnt scripts is more powerful and only relies on the relevant .Net Framework SDKs having been installed on your system and so doesn't require a full Visual Studio install. See documentation under Build/ in our svn trunk for more information. My code won't compile because a namespace or class from dotNetRDF was not found? There are a number of possible causes of this type of error, please check you have done all of the following. Have you added dotNetRDF as a reference to your project? See Getting Started for help with this Is the version of dotNetRDF referenced the correct version for the target framework version of your project? dotNetRDF comes in builds for a variety of different versions of the .Net framework, using the wrong build will lead to compile errors - see Getting Started Are you using the latest version of the library? Check the Project Status page and compare the build and version number with that shown in your editor Have you added the appropriate using declarations to your code? Check the Intellisense API to see what namespace different classes are in Are you trying to use deprecated/removed code? We have a clear Deprecation Policy and we actively obsolete and deprecate old APIs over time. If you upgrade your version over time you will see warnings ahead of time but if you jump several versions in one go you may encounter problems with missing APIs. See the ChangeLog.txt file in the release or consult the Project Roadmap page to see what may have changed. The front page of the Intellisense API also details breaking API changes between major releases. I get a "No overload for method X takes Y arguments" error or similar Some features are not available across all builds of the library because they cannot be supported on the platform (e.g. anything using synchronous HTTP is not supported under Silverlight or Windows Phone) This means that some methods shown in the documentation and listed on the Formal API will not be available. Use your editors auto-complete functions to see alternative overloads for the method which are supported with the chosen build of dotNetRDF. I get a "The Namespace URI for the given Prefix 'http' is not known by the in-scope NamespaceMapper" This error occurs because you have tried to use the version of CreateUriNode() that expects a Prefixed Name e.g. rdf:type instead of the method that expects a Uri Ensure you call the version of the method that takes a Uri instance instead. Data Errors The data returned from a remote service is not in the format I expected? When you use any class that talks to some remote service to retrieve data whether it be the UriLoader or some triple store connector like the FusekiConnector the data returned will be dictated by the service you are accessing. All dotNetRDF is responsible for is sending the request to the remote service and parsing the data returned into the relevant .Net objects for you to work with. If some piece of data comes back as a ILiteralNode and you expected a IUriNode then that is nothing to with dotNetRDF - it is the remote service that returned the data in that format. My query returned no results? Depending on how you make a query it is either being evaluated by dotNetRDF itself or passed off to some external service to do the query processing. There can be a number of reasons why a query did not return, check the following. Is there a typo in your query? Are you sure the query you wrote is actually correct, minor mistakes in namespace declarations can make your query syntactically correct but fail to match anything. Did you misspell a namespace or Prefixed Name? Are you using literals in triple patterns in your query? Literals in triple patterns are matched strictly in SPARQL so things that look very similar are not considered equal e.g. "1"xsd:integer != "1"xsd:decimal . If you are using Literals you may be better using a variable combined with a FILTER clause because the equality in filter expressions is value based equality so would match something like the above where triple pattern matching would not. Are there named graphs involved? If so does your query actually query the appropriate named graphs? Please see SPARQL Datasets for help with this. Does the data being queried actually contain the triples you are trying to match? You can try debugging your query by following the instructions on Debugging SPARQL Queries If you still have problems then you may wish to ask for Support - bear in mind that for many query able data sources such as 3rd party triple stores you are likely better off asking the people behind the store for help rather than us because we may just be sending a query and receiving a result in which case the lack of results is outside of our control. Updated
https://bitbucket.org/dotnetrdf/dotnetrdf/wiki/FAQs
CC-MAIN-2014-15
refinedweb
953
60.55
From LQWiki The C programming language is certainly the most influential in the world of programming. Created at first by Brian Kernighan and Dennis Ritchie in 1972, this language is characterized by its closeness to the hardware without being architecture dependent. Not that it is complicated (like Assembly), but you can move generally as you want in the memory for example, but may crash if you are not permitted to read or write to that memory. The C language is often associated with UNIX, maybe because it has been developed on and written with it. But it is not linked with any system nor architecture. You can use C in many applications with this language. It, however, has come under criticism for being insecure, when it is not used correctly (for example, bounds overflow checking is not done by default - allowing the chance for buffer overflow attacks in poorly written software). See Overrun screw. Note that even if it is still the most used, the C language has gradually become an old language. Having been written in 1972 means it was created before many modern studies on programming language theory. These studies provide huge advances in the creation of a language, especially in the precision and speed with which it's compiled. For example, you don't have a real range of lines and columns when there is an error or a warning in C; recent languages do. However, Kernighan and Ritchie wrote 'The C Programming Language' in 1978, which served as the de facto standard until it was modified as ANSI C in 1988 and formal standards were promulgated in 1990 and 1999 ISO standards. So C has continued to evolve over time. One unusual, and perhaps vital feature of the C standardization process is that only designs which have proven themselves useful by achieving widespread use and support are accepted into the standards. Any C developer can introduce a new feature into a C compiler, and if other developers like the feature, they may start to use your compiler, or adopt the design into their own compilers. If the new design gains popularity, it may be adopted as a standard. In contrast, most other languages receive new features primarily from a central organization that is responsible for the language. For example, Borland controls Delphi and thus largely influences modern Pascal standards; and TrollTech controls Qt, thus dictating Qt standards. (Qt is an API, but it still has standards!) Most language innovations come from a central place, whereas innovations in C can come from various developers around the world, and are adopted by the community before becoming standards. Language Features Types The size here are only hints. There years have seen very funny breads of computers, e.g. with 9 bit char and 36 bit integer. The actual values depend on the processor you are working on. To find the real values you need <limits.h> and <float.h>. To find out about the real sizes on your system try this program: #include <stdio.h> #include <limits.h> #include <values.h> int main() { printf("Every Char has %d bits.\n",CHARBITS); printf("Every short has %d bits.\n",SHORTBITS); printf("Every int has %d bits.\n",INTBITS); printf("Every long has %d bits.\n",LONGBITS); printf("Every pointer has %d bits.\n",PTRBITS); printf("Every double has %d bits.\n",DOUBLEBITS); printf("Every float has %d bits.\n",FLOATBITS); return 0; } To compile: $ gcc example.c -o example $ ./example this test run on a Intel(R) Pentium(R) 4 CPU 2.80GHz Every Char has 8 bits. Every short has 16 bits. Every int has 32 bits. Every long has 32 bits. Every pointer has 32 bits. Every double has 64 bits. Every float has 32 bits. $ ./example this test run on a Intel(R) Pentium(R) 4 CPU 3.20GHz Every Char has 8 bits. Every short has 16 bits. Every int has 32 bits. Every long has 64 bits. Every pointer has 64 bits. Every double has 64 bits. Every float has 32 bits. note Even when it seems that only the speed is different, internaly we can see that the type long and the pointersize is different. Basic Types char: character 1 byte -128 to 127 int: integer 2 byte -32768 to 32767 float: float 4 byte -3.4E38 to 3.4E38 double: double float 8 byte -1.8E308 to 1.8E308 short: shorter type 2 byte -32768 to 32767 long: longer type 4 byte -2147483648 to 2147483647 signed: signed type (the data is split in half, half for positive values, half for negative values) unsigned: unsigned type (no negative values) Array C knows only about memory, where it is (memory addresses) and its content (data). Actually that is true for every programming language but not all allow user access to this level. That means an array in C is nothing more that a reserved block of memory. It is defined like this: int array[5]; in plain English that translates into: reserve a block of int five times. proof: #include <stdio.h> int main() { int arr[5]; printf("size of this array is %d bytes.\n",sizeof(arr)); return 0; } To compile this type: $gcc example.c -o example $./example size of this array is 20 bytes. That can also be used to find out how many elements an array holds. Add the following lines to find out: printf("We have %d members\n",sizeof(arr)/sizeof(arr[0])); You can access the individual members of this array using an index. The index is written right after the array name. arr[0] means that the first array member is requested. Since arrays are just memory chunks, there is no array start or array end-marker for the compiler. That means careless use can lead to access beyond the reserved memory block. Normaly this will cause a crash. Expressions An expression is a series of operators and quantities to be operated on (operands) that returns a result. This result can be used as the operand of a larger expression or assigned into a variable. Expressions are used throughout the language - in if statements, loops, function calls - and they can even be statements by themselves. This last use is interesting. Just 1; is a valid C statement. Of course, a statement is only interesting if it has side-effects. Saying a=1; has the side-effect of assigning the value 1 to the variable a. Side-effects are especially important with the logical operations and the tertiary if-then operator. Operators There are tons of operators in C. Mathematical, bitwise logical, logical, comparison, and a few others. Operators have precedence, meaning that some take effect before others. Parentheses can be used to do things in the order you want. Mathematical The most familiar operators for most people are +, -, * (multiplication) and ÷. Division uses a slash /, and there's also the modulus operator % for remainder after integer division. I think of the unary operators + and - (negative) as mathematical as well. Assignment Assignment operators have the side-effect of setting a variable's value. In addition to the typical =, there are several operators like += which means, "Add this to the variable." The assignment operators are =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, and >>=. a += b; // equivalent to a = a + b a -= b; // equivalent to a = a - b Comparison These operators compare two values, returning 1 for true or 0 for false. The test to see if two values are equal is (a == b) with a double equals sign (since a single '=' is used for assignment). The comparison operators are ==, != (not equal), <, >, <=, and >=. A common mistake is the use of something like if (a = b) { // WRONG! when it should have been if (a == b) { The former will redefine a equal to b, and use the new value of a as the condition for the IF statement; so for any non-zero value of b, this will succeed (and mess up a in the meantime). Watch out for this trap! It's one = for telling, two == for asking. Logical Logical operators combine values that are true or false. The key concept is that is not 0 is true, and 0 is false. Each of these operators returns 1 for true. a && b // test if a AND b are true a || b // test if a OR b are true !a // test if the negation of a is true a ^ b // exclusive-OR; (a || b) && !(a && b) It is important to realise that C stops processing an expression as soon as the answer is known for sure -- not every sub-expression in a compound expression will necessarily be evaluated. The expressions a and b can have side-effects like assigning the values of variables. Because of the difficulty in debugging such expressions, the use of function calls and operators with side-effects within logical expressions is discouraged. It is common in shell scripts to use logical operators as quick-and-dirty if statements. As an example, if we have an expression such as if ((a && b) || c) { if a is false, b will not be evaluated (because a && b cannot possibly be true if a is false). But c will have to be evaluated, because we do not know the result in advance. If a is true, b will be evaluated; and if b is also true, then c will not be evaluated, since we know that the result of the OR operation will be true. Tertiary if-then operator This operator is unique in that it takes three operands. The form is (a)?(b):(c). (Parentheses are recommended because this operator has low precedence.) The operator evaluates a, and if it is true, then it returns b. Otherwise it returns c. If there are side-effects, a regular if statement is recommended. Being an operator, ?: does return a value. So d = ((a) ? (b) : (c)); sets d = b (and does not evaluate c) if a is true (i.e. anything but zero), or d = c (and does not evaluate b) if a is false (zero). Bitwise Operators Bitwise operators, as the name suggests, operate on binary numbers on a bit-by-bit basis. a & b = bitwise AND a | b = bitwise OR a ^ c = bitwise XOR (exclusive OR) Each bit of a is ANDed, ORed or XORed with the corresponding bit of b and the answer is inserted in the corresponding bit position in the result. For example, (I'm using hexadecimal numbers here to make it a little more obvious -- but this obviously works with any numeric values) 0xe8 & 0x1f = 0x08 0x51 | 0x60 = 0x71 0xaa ^ 0xff = 0x55 These operators are very useful when storing several boolean values in an integer or char. Also, you can somtimes make use of the fact that -- in ASCII codes -- bit 5 (i.e. the 32's) is set (1) in the lower case letters, but cleared (0) in the corresponding capital letter. Bit Shift Operators These operators shift the bits of a binary number to the left or the right. Bits that "fall off the end" are lost for all time, and zeros are shifted into the opposite end. x = a << b; // bits of a, left hand shifted b times y = a >> b; // bits of a, right hand shifted b times These operators are meant to be combined with the bitwise operators above. Suppose we wished to store a day of the week day (between 0 and 6), a date within the month date (between 1 and 31), and a month month (between 1 and 12) in an int variable ddm. We need 3 bits to store day, 5 bits to store date and 4 bits to store month, and we could build up an expression like this: ddm = (day << 9) | (date << 4) | month; and then the reverse would be day = ((ddm & 7<<9) >>9); date = ((ddm & 31<<4) >>4); month = (ddm & 15); We use the AND operator to select just the bits we are interested in, the two shift operators to position them where we want, and the OR operator to assemble the groups of bits together. Increment and Decrement The ++ and -- operators -- a shorthand notation for adding and subtracting one from a variable -- can each be used in two different ways. If the operator comes after the variable name, then the variable is incremented or decremented after its value is read and passed on. If the operator comes before the variable name, then the variable is modified before its value is read. a = b++; // equivalent to a = b; b += 1 a = b--; // equivalent to a = b; b -= 1 a = ++b; // equivalent to b += 1; a = b a = --b; // equivalent to b -= 1; a = b Other The comma, pointer/structure/array operators, type casts. Control structures if (else) instruction The general look of a C if-then-else statement is something like if(expression){ A } else { B } If expression is different from 0 then A (whatever that might be) is executed, otherwise, that is expression is 0, B is executed. The real issue here is of course; what is expression, A and B. expression is from the compilers point of view any value that can be interpreted as a number, that's almost anything in C. For instance the value 2 would be syntactically correct. The key issue is that 2 is different from 0, thus A would be executed. A and B is any piece of code actually, for example printf("Hello World!"); Here's an example of an if statement: if(customers > 0){ printf("There are people in the shop"); // state the obvious getHelp(); // call some functions that gets more personnel } else { drinkMoreCoffee(); // do what you're trained to do } The tertiary operator (above) can be used as a quick form of the if statement. switch instruction The general look of a switch statement: switch(variable) { case 1: printf("Variable is 1\n"); break; case 2: printf("Variable is 2\n"); break; default: printf("Variable is some other value\n"); break; } The switch statement also provides the advantage of control to 'fall through' case statements, for example switch(variable) { case 1: case 2: printf("Variable is either 1 or 2\n"); break; default: printf("Variable is some other value\n"); break; } while (do) instruction The general look of while statement: while(expression){ do something } expression is the same thing as with if statements, i.e. something that can be evaluated either true (different from zero) or false (that is zero). What's happening here is that we first test if expression is true, if so the body of the while statement is executed as long as expression is true. For example: int a = 0; while(a < 5){ a++; printf("%d, ", a); } printf("\n"); This would produce the output: 1, 2, 3, 4, 5, Key note is that whether a is less than 5 or not is just tested in the beginning of the while loop, so it's possible to write the number 5. Then of course the loop is terminated. The brother while loop is the so called do-while-loop do { do something } while(expression); The key note here is that whether expression is true or not is tested at the end of the loop, that means that the body of the loop is executed at least once. It's of course possible to construct a loop that runs forever (infinite loop). For example: int a = 0; while(a < 3){ printf("I'm a fruitcake\n"); } for instruction The general look of a for-loop is: for(A;B;C){ do something } Here A is executed just once when we enter the for-loop, typically to initialize some variables. B is a truth conditional like the ones in the while loop, if B is true then we continue looping. C is executed every time at the end of the loop. For example: for(i = 0; i < 5; i++){ printf("%d, ", i); } printf("\n"); This would produce the output: 0, 1, 2, 3, 4, to guide you through it: First i is set to 0, this happens just once. Then we test if i is less than 5, clearly, it's 0. Now we enter the for-loop and print the value of, i. At the end of the loop i is incremented by 1. Then test again weather i is less than 5, print it's values, and so on. Please note that A, B and C can all be omitted, This is valid syntax: for(;;){ printf("I'm looping forever and I'm happy with it.\n"); } It's not too common to introduce loops like this, but it works. The idea is that you can do something like: int i = 0; for(;i < 10; printf("Hello")){ i++; } Also you can do more things in A and C, For example you want to initialize variables i to 0 and j to 5 at the beginning of the loop. for(i = 1, j = 5; (i*j) > 0; j++, j--){ printf("%d, ", i*j); } The , between i = 0 and j = 5 is the separator here. Same style goes at the end where j is incremented and j decremented. Functions First of all a function can be thought of as a way to store a procedure. This procedure contains some instructions that you want to carry out many times. Also it's a way to structure your program. It can also be regarded as a function in a more mathematical sense. A wide variety of functions are available in the standard library, glibc (Some of these are actually in the math library, accessed by linking the program with -lm). Here is the general outfit of a C function: return_type function_name(argument_1, argument_2, ..., argument_n){ function_body } A simple example of a function: int max_i(int a, int b){ if(a > b){ return a; } return b; } Functions can of course call other functions, for example: int find_max(int *nums, int len){ int max = 0, i; for(i = 0; i < len; i++){ max = max_i(nums[i], max); } return max; } Further functions can call themselves, this example calculates n!. int fac(int n){ if(n == 1){ return 1; } return n*fac(n - 1); } Functions can return all basic types such as, int, float, double, char, etc. They can also return pointers to all these. They can return pointers to structs and void. If a function is declared to return void it simply returns nothing. Don't confuse this with functions that returns pointers to void, that is void*. returning void* is simply returning a general pointer to something we don't the type of. An example of a function that 'returns' void. void printObvious(){ printf("I'm a function that returns nothing.\n"); } As we can see, we can omit the return statement since this function does not return anything. Advanced Function usage Sometimes it pays to take to deeper look. A function is actually a pointer to an area of code from where instructions will be executed. So you can use that. It is nothing dirty since it is done for e.g. by shared libraries. Have a look at this example: /* Make the necessary includes */ #include <stdio.h> /* provide some functions to play with */ int add(int a, int b) { return a+b; } int mul(int a, int b) { return a*b; } /* note the third argument */ int call(int a,int b,int (*fkt)() ) { return fkt(a,b); } The main function uses call(), which is actually a wrapper for add() and mul(). Providing a pointer to a function, you can modify the behaviour of a function. This is useful when a fairly complex function is used, that needs a few modifications to be more flexible. Beware: Do not use this without a proper understanding of what you are doing! int main() { printf(" add=%d\n",call(2,3,add)); printf(" mul=%d\n",call(2,3,mul)); return 0; } Compile this with 'gcc -Wall example.c'. The result should be: add=5 mul=6 Special function "main()" We used it rather often but 'main()' is a special name. This is the entrypoint when code gets executed. you will have noticed that the return value of main() is int. what does it mean ? try this int main() { return 99; } compile with 'gcc example.c' and try this on you shell: ./a.out echo $? You see '99' the return code is the exit code of a.out. This value is used to indicate errors/problems to following program (see: shell progamming). History of C C was designed by Dennis Ritchie during the early 1970s and immediately used to reimplement Unix. It was called C \u2018D\u2019 or \u2018P\u2019. C became immensely popular outside Bell Labs after about 1980 and is now the dominant language in systems and microcomputer applications programming. C is often described, with a mixture of fondness and disdain varying according to the speaker, as \u201ca language that combines all the elegance and power of assembly language with all the readability and maintainability of assembly language\u201d. See also History of Unix, ident style. Books - C Programming Language, Brian W. Kernighan, Dennis Ritchie - C: A Reference Manual, Samuel P. Harbison, Guy L. Steele - The C Puzzle Book, Alan R. Feuer For beginning users: - C How to Program, by Dietel et al. (Only the first two versions are recommended by my source.) - Practical C Programming, by Steve Oualline Tutorial Material Since this page serves as something of language overview, more lengthy examples would fit better on their own page. Check out CProgrammingExamples for some examples, that might help you getting started with C programming. See also External links - Write in C! (netzreport.googlepages.com) - famous song about why to use C (satire) This article is based, in whole or in part, on entry or entries in the Jargon File.
http://wiki.linuxquestions.org/wiki/C
crawl-001
refinedweb
3,634
63.8
Why aren't changes on my Amazon S3 bucket showing on the Storage Gateway file share? Last updated: 2020-02-04, the AWS Command Line Interface (AWS CLI), or through an AWS Lambda function. Resolution Using the Storage Gateway console To refresh the cache using the Storage Gateway console, see Refreshing Objects in Your Amazon S3 Bucket. Using the AWS CLI 1. Run the list-file-shares command: $ aws storagegateway list-file-shares As another option, you can create a script or scheduled cron job to run the refresh-cache command at certain intervals. For example, the following cron job runs the command every 12 hours: 0 */12 * * * root aws storagegateway refresh-cache --file-share-arn arn:aws:storagegateway:eu-west-1:12345678910:share/share-FFDEE12 Note: You must schedule the cron job using the credentials of an AWS Identity and Access Management (IAM) user or role that has permissions to run the refresh-cache command. Using a Lambda function You can create a Lambda function that runs the RefreshCache API on a certain schedule. The following example function uses boto3: import json import boto3 client = boto3.client('storagegateway') def lambda_handler(event, context): print(event) response = client.refresh_cache( FileShareARN='arn:aws:storagegateway:ap-southeast-2:123456789012:share/share-EEFFBD9C' ) print(response) return 'Your FileShare Cache has been Refreshed' Note the following considerations for automating the refresh cache operation: - If there are millions of files in the S3 bucket, then the refresh cache operation can take several hours. By default, the objects and folders at the root of the bucket are refreshed. You can choose to run RefreshCache on a specific folder or list of folders instead of refreshing the entire bucket. - It's not a best practice to invoke the refresh cache operation based on an event-driven operation, such as an Amazon S3 event notification, unless the events are spaced well apart. Instead, run the refresh cache operation on a timer. For example, you can use an Amazon CloudWatch Event rule to run an AWS Lambda function on a schedule. This configuration can space the refresh cache calls apart by a few hours. - It's a best practice to set up notifications for when a refresh cache operation completes. To do this, create an Amazon Simple Notification Service (Amazon SNS) topic and subscription. Then, create an Amazon CloudWatch Event that triggers on a Storage Gateway Refresh Cache Event and set the SNS topic as the target. Did this article help you? Anything we could improve? Need more help?
https://aws.amazon.com/premiumsupport/knowledge-center/storage-gateway-s3-changes-not-showing/
CC-MAIN-2020-10
refinedweb
419
54.02
Next article: Solving Simulator Bootstrap Errors Previous article: Friday Q&A 2012-04-27: PLCrashReporter and Unwinding the Stack With DWARF Tags: dangerous debugging dwarf fridayqna guest semi-evil Here I am, yet again! This week, I'm continuing where my last article left off, regarding PLCrashReporter and unwinding stack frames on x86_64. In particular, I go into how I got at and used all the various data I discussed in last week's article, and why some of the existing solutions in the wild weren't suited for our use. Why not just use one of those things over there? The first thing I did when I took this project on was look for a simple solution. They do exist, in a lot of cases, and they end up unused because no one knew quite there to find them. The first idea I had was to use Apple's own implementation of libunwind. It's built into the system, always available, and does exactly what was needed: providing the addresses of functions on the stack, using all information available. Whoops. Apple's library: - Has no public API for accessing the stack of any thread other than the current one. - Calls into dyld(not async-signal safe) - Calls dladdr(not async-signal safe) - Allocates memory (not async-signal safe) - Has no fallback when compact unwinding, DWARF, and frame pointer walking all fail. - Doesn't symbolicate. - Isn't guaranteed to be available before Lion. - Is licensed under APSL, which made forking it not an option. So, it was basically completely useless for our purposes. The next thought was the original libunwind, available here. Whoops again: - No Darwin support. - No Mach-O support. - No compact unwind encoding support. - No fallback stack scanner. - Convoluted source code with no documentation on porting or extending. Also essentially useless for our purposes. The remaining option was to create my own implementation of a DWARF parser, a compact unwind encoding parser, and a stack scanner. I could have integrated it directly into PLCrashReporter, but the lack of a stack unwinding library in the wild made me think it would be better to write it as entirely independent code. So I popped open Xcode and created a new target, which I called libtinyunwind. A little API design The idea behind libtinyunwind was to be exactly what it said: A nice, small unwinding library that did only as much as was necessary to gather a backtrace after a crash. (It could also potentially be used for exception unwinding, but only if I were to implement the C++ ABI for doing so. Apple's libunwind already does that.) Because I was trying to solve the issue on x86_64 only, I also didn't worry too much about making it cross-platform just yet, though I kept it in mind. I took quite a bit of inspiration from both PLCrashReporter and the original libunwind when designing the API. First, the public interface to the library. A stack unwinder has to provide: - Tracking of binary images loaded into (and unloaded from) the active process. - Derivation of state contexts from any existing thread. - One-at-a-time in-order iteration of stack frames in a context. - Access to whatever register data is available in each frame. - Preferably, symbolication of any returned function addresses. Based on PLCrashReporter's higher-level implementation, I created the following set of functions. In this discussion, I use the short function and data type names for simplicity and readability, but the real function names and data types are namespaced with a tinyunw_ prefix. int set_image_tracking(bool tracking_flag); int getcontext(context_t *context); int getthreadcontext(context_t *context, thread_t thread); int init_cursor(context_t *context, cursor_t *cursor); int step(cursor_t *cursor, flags_t flags); int get_register(cursor_t *cursor, register_t regnum, word_t *value); const char *register_name(register_t regnum); int get_symbol_info(word_t ip, word_t *start_addr, const char **name); The context_t is a typedef around x86_thread_state64_t, whereas the cursor_t is an opaque structure type. register_t is an enum of the available registers on x86_64, and word_t is a typedef of uint64_t. Making them opaque types will simplify making the library cross-platform at a later date. Because the code that uses the context and cursor must be async-signal safe, I couldn't simply write typedef cursor_struct *cursor_t;. The client code has to be able to allocate context and cursors on its stack, and if the compiler doesn't know the size of the structure, it can't do that. The solution was this somewhat ugly trick: typedef struct cursor_t { uint64_t opaque[120]; } cursor_t; In fact, the actual cursor structure, defined in an internal header, weighs in at only 352 bytes, not 960, but the extra space allows for 1) future expansion without breaking binary compatibility, and 2) leeway in the actual implementation. Since in the library's intended use case, you would only have one cursor around at any given time, a loss of 608 bytes in a 64-bit address space wasn't particularly worrisome. It is a little bit excessive, but not difficult to adjust as needed. The public header also defines a set of error codes, in the UNIX style, for the functions to return (again, remember that the real ones have prefixes): enum { ESUCCESS = 0, /* no error */ ENOFRAME = 1, /* no more frames to unwind */ EUNSPEC = -6540, /* unknown error */ ENOMEM = -6541, /* out of memory */ EBADREG = -6542, /* bad register number */ EINVALIDIP = -6545, /* invalid IP */ EBADFRAME = -6546, /* bad frame */ EINVAL = -6547, /* unsupported operation or bad value */ ENOINFO = -6549, /* no unwind info available */ }; Most of these codes correspond to the same values in Apple's libunwind.h header file, for closer interoperability with those familiar with that library. There is also a set of flags for the step() function: enum { FLAG_NO_DWARF = (1 << 0), FLAG_NO_COMPACT = (1 << 1), FLAG_NO_STACKSCAN = (1 << 2), FLAG_TRY_FRAME_POINTER = (1 << 3), }; typedef int flags_t; This allows the client of the library to control exactly which information gets used during an attempt to step through a stack. This is useful in several cases: - If a bug is discovered in one of the implementations, that implementation can be shut off without removing the entire library. - If the client code knows ahead of time what information is and isn't available, or if it just wants faster execution at the expense of accuracy (DWARF is much slower than the other methods), it can avoid what might otherwise be a costly search through the binary's debug information. - If the client is concerned with accuracy more than the maximum information possible, turning off the stack scanner removes most of the potential for garbage data. - A client of the library could offer a user (presumably a developer) the option of using only some of the data available so that they could see whether a program had included (or excluded) the desired information. Here's a very basic example of how to use the API: int main(int argc, char **argv) { /* ... */ set_image_tracking(true); /* ... */ } void walk_thread_stack(thread_t thread) { context_t context; cursor_t cursor; int res = ESUCCESS, n = 0; word_t reg = 0, addr = 0; const char *name = NULL; getthreadcontext(&context, thread); init_cursor(&context, &cursor); while (true) { res = step(&cursor, 0); if (res == ESUCCESS) { if (get_register(&cursor, X86_64_RIP, ®) != ESUCCESS) break; if (get_symbol_info(reg, &addr, &name) != ESUCCESS) break; printf("Frame %d has IP %p, which is in function %s, starting at address %p\n", n, reg, addr, name); continue; } else if (res == ENOFRAME || res == ENOINFO) printf("End of stack.\n"); else printf("Error %d\n", res); break; } } The call to set_image_tracking() at the beginning is extremely important; without it, only the stack scanner works, and addresses can't be symbolicated. Why do I have to track binary images, anyway? You might wonder why the library doesn't just scan the address space of the process to find the information it needs. Unfortunately, that's just not feasible. There are a lot of gotchas involved in how libraries are loaded into an executable at runtime, so many that it would be a practical impossibility to figure it all out during async-signal time. This means the library has to keep internal track of binary images as they're loaded into and unloaded from a process. Fortunately, dyld provides a nice easy (and more importantly, documented and stable) way to do that: _dyld_register_func_for_add_image and _dyld_register_func_for_remove_image. When an image (keep in mind that in this context, "image" means any bit of executable code loaded into a process during runtime, including the executable itself) is loaded, libtinyunwind immediately parses it as Mach-O and stores it in an async-safe read-write-locked linked list (implementation courtesy of PLCrashReporter, a very nice bit of code on Landon's part!) Why, you might ask? Because that's how it finds: - The address of the image's executable code, also known as its TEXT section. Used by all methods. - The address of the image's __eh_frameand __debug_framesections. Used by the DWARF parser. - The address of the image's __unwind_infosection. Used by the compact unwind parser. - The image's __LINKEDITsegment and symbol tables. Used by symbolication. All of this information could be parsed out at async-signal time, but there's no reason not to parse it as soon as the image is loaded into the process, and there is one advantage to doing it when it's safe to call normal APIs: It can (and does) also call dladdr() to get the image's name on disk. It's all very nice to know that someone called a function named foo, but was it foo in the main application, foo in some third-party library, or foo in CoreFoundation? (No, there isn't really a foo there. :) Armed with all of this data, libtinyunwind can get to the work of actually unwinding a stack. Let's put it all in context Step one of unwinding a stack is getting a thread state, also known as a context. This is, in its simplest form, a snapshot of all the CPU registers for the thread you're trying to examine. It can be obtained from the Mach API thread_get_state (which is how getthreadcontext() works), or retrieved directly in assembly language if you happen to already be executing on the thread in question. For fun, here's the getcontext() implementation: movq %rax, (%rdi) movq %rbx, 8(%rdi) movq %rcx, 16(%rdi) movq %rdx, 24(%rdi) movq %rdi, 32(%rdi) movq %rsi, 40(%rdi) movq %rbp, 48(%rdi) movq %rsp, 56(%rdi) addq $8, 56(%rdi) movq %r8, 64(%rdi) movq %r9, 72(%rdi) movq %r10, 80(%rdi) movq %r11, 88(%rdi) movq %r12, 96(%rdi) movq %r13,104(%rdi) movq %r14,112(%rdi) movq %r15,120(%rdi) movq (%rsp),%rsi movq %rsi,128(%rdi) # store return address as rip # skip rflags - pushq is unsafe with stack in unknown state, lahf may be unsupported # skip cs # skip fs # skip gs xorl %eax, %eax # return TINYUNW_ESUCCESS ret The function has no prologue or epilogue, as that would corrupt the base and stack pointers. The context in which to store the information is pointed to by rdi (first integer argument register). The register values are mostly loaded directly into the context. The stack pointer is incremented by 8 (one 64-bit word) to compensate for the saved return address pushed by the call to this function. The return address is stored as rip in the context structure, obtained by dereferencing the stack pointer per the semantics of call. In essence, this function pretends that it is not itself on the stack. The flags register is skipped because there's no safe way to load it at async-signal safe time, and the segment registers are skipped because they're not meaningful in 64-bit code. There's not really a lot of point to using this in lieu of just calling thread_get_state() unless you're concerned about calling as few system APIs as possible. It's also useful on non-Mach-based platforms, where getting at a context state can get a good bit harder. Lay back and unwind So, now you have a context, and a cursor with which to iterate it. How does that iteration actually work? The step() function uses the following logic: Is the cursor's ripvalue NULL, or does it fall in the predetermined range for the symbols startor thread_start? If so, immediately return ENOFRAME; the top of the stack has been reached. The scanner explicitly stops at startand thread_startbecause the stack scanner has a tendency to run off the bottom of thread stacks in particular, and because the DWARF and compact unwind encodings do not always encode a foolproof way to detect the bottom of the stack which can be used to avoid trying the stack scanner. One of these symbols is guaranteed to always be at the bottom of any stack, so they're safe stopping points. If the client has not requested that the compact unwind encoding be skipped, try to find a stack frame using it. Return on success or any error; if no compact unwind information exists, continue. If the client has not requested that DWARF not be used, try to find a stack frame that way. Return on success or any error; if no DWARF information exists, continue. If the client has requested a frame pointer scan, try to use rbpas a pointer to the next stack frame. Return on success or... well, you get the idea. Finally, if all else has failed, try a stack scan starting from the last valid frame. Let's examine each method in order. Wow, that's compact; can you expand on that? The compact unwind encoding parser first checks whether any image loaded into the process contains the current rip value in the cursor's current context. If not, it immediately returns "no info", because if can't even tell where to look. It's not useful to search the unwind table of every image in the process; that's no better for false positives than the stack scanner. It also returns no info if the image it found doesn't have compact unwind information. The next step is to do the two-level table lookup of the rip value, as discussed in part 1. Since both levels of table are ordered ascending, the lookup code does a binary search for the function address. Addresses in the unwind table are stored as offsets from the image's Mach-O header address, so the rip value first has that subtracted from it. Assuming a matching entry is found, the second-level table contains the encoding of the function's unwind information. The compact unwind encoding has five types of actual information encoding: - Compatibility encoding. This encoding appears to be an historical holdover, and is never used on OS X. Both Apple's libunwindand libtinyunwindinterpret it as meaning "no unwind information available". - DWARF encoding. This means the unwind information for the function was too complex to be represented in the compact encoding, and the DWARF data should be searched instead. libtinyunwindhandles this by simply returning "no info" and letting the DWARF parser search next. - RBP frame encoding. The unwind information is for a function with a frame pointer. The saved register numbers are read from the encoding and the register values are updated from the thread's stack. The current rbpis dereferenced to find the new rbp, rspis set to the old rbpplus two words (frame pointer and return address), and ripis set to the return address on the stack ( rbp+ 8). - Stack immediate encoding and stack indirect encoding. These two encodings are for functions with no frame pointer. Registers are handled identically for both encodings (identically to RBP frame encoding, but with a different encoding for the saved register numbers). The stack size is calculated as a number in the immediate encoding. For the indirect encoding, the function is required to start with a subl %rsp, $some_number_hereinstruction, which is parsed to get the stack size. rspis set to the old rsp, plus the stack size, minus the number of saved registers, plus 8 (the return address). ripis set to the return address on the stack. And that's it! With rsp and rip (and when possible, rbp) updated, everything necessary to proceed to the next stack frame has been done. Success is returned at this point. I'm feeling a little DWARFed by the (virtual) machine If only DWARF parsing were so simple! Unfortunately, it isn't. The DWARF parser starts off with the same step the compact unwind parser does: Look for the image containing rip. No image? No DWARF info? Give up right then and there. Oh drat, we found something. Now we have to search the debug info section for an Function Data Entry (as discussed last week) matching the function address. This means parsing out the whole thing. We start at the beginning of the section and parse one entry at a time. The algorithim goes like this: - Is the next entry an FDE or a CIE? If it's a CIE, skip it. We parse those as part of the FDE. Unfortunately, that means we parse each CIE one time for every single FDE parsed. That's because we're running at async-signal time, and there's nowhere to cache the CIEs we find. - It's an FDE? Parse it out, including the CIE. If it contains the function address we're looking for, return it. Otherwise continue onward. I'm going to interrupt myself here to discuss a bit about how DWARF data is parsed. DWARF is a very interesting data format; it contains a number of different encodings for various information, all of which may end up being used at any given time. For example, a CIE starts with simple 32-bit and 64-bit and 8-bit numbers. Then it has a C string which describes the "augmentations" for all FDEs that use it. Then it has a couple of "ULEB128" and "SLEB128" numbers. "LEB128" stands for "Little Endian Base-128", which the DWARF standard says is "a scheme for encoding integers densely that exploits the assumption that most integers are small in magnitude." Despite the name, it is not in fact little-endian. In my own opinion, LEB128 exists mostly to make things more difficult; I think it's more than a little foolish trying to save a couple zero bytes in integer numbers in an encoding that deals with virtual machine opcodes. I can only assume there's some thought behind it that I don't understand. In any case, the augmentation string in a CIE must be parsed character-by-character to learn certain critical things about the data in associated FDEs. In particular, it gives the size of augmentation data (necessary to correctly parse an FDE) and the encoding of pointer values in the FDE (necessary to even tell whether a function offset is contained by the entry at all). Other information in the CIE gives alignment factors for code and data, points out which column in the virtual CFA table represents the function return address, and gives the actual version of the DWARF data. Versions 1 (a .eh_frame section produced by GCC or Clang) and 3 (DWARF 2 standard) are identical, and are the only ones libtinyunwind tries to understand. The pointer encodings are also a bit fun; a pointer in an FDE can be encoded in no less than 36 different ways (9 numerical representations, ranging from signed and unsigned 8-bit to signed and unsigned 64-bit and including uleb128 and sleb128, several encodings (of which only two are supported) for the "base value" of the pointer, and a flag for indirection of the value). When all of this is said and done, we end up with (hopefully) an FDE (with included CIE) for the function we're unwinding. Now we have to run the CFA program. This means setting up a virtual machine state, running all instructions in the CIE, then running all instructions in the FDE, halting immediately once the virtual CFA PC passes the current value of rip for the function. Running any instructions past this point would result in an incorrect register state, since the actual code that was run never got there! DWARF has push and pop state instructions. Since we can't allocate memory, a hard size limit on the depth of the virtual stack is imposed. The virtual state is fairly large, so the limit is 8. Fortunately, I've yet to see a DWARF encoding that uses even one, so I think that limit is safe. The actual opcodes are mostly straightforward. The virtual machine maintains a CFA register number, a CFA register offset, a CFA PC, and a set of register values and locations, encoded by numbers. The machine registers that those numbers correspond to are architecture-specific; libtinyunwind maps them onto the x86_64 register set with the obvious switch-case statement. DWARF has opcodes which: - Do nothing (nop) - Modify the CFA PC (set to n, advance by 1/2/4/n) - Modify a register's value (set to n, set to CFA +/- n, set to other register, set undefined, set to result of expression) - Save and restore the DWARF state (push/pop the virtual stack) - Set CFA register (set to n, set to n +/- m, set to current +/- m, set to result of expression) - Various GNU extensions and user opcodes, all of which are treated as errors by libtinyunwind, as they aren't used on Darwin or in modern code (with one exception; the args_size opcode is parsed but not used). Once the CFA program has been run, it produces a virtual machine state, a snapshot of the DWARF CFA table at the given rip. This state must now be applied to the current register state. First, the value of the CFA register is determined. The CFA register can be either the value of a particular machine register (before applying any changes) plus or minus an offset, or the result of a DWARF expression. libtinyunwind does not currently parse DWARF expressions, as they're very rare in the wild and missing data falls back on the stack scanner; it will be implemented at some point in the furture. Next, for every register in the virtual state, apply the virtual register value and location to the real register. A register's location can be "unused" (don't change the real one), "CFA value +/- offset" (set the real register to the CFA register's value), "register" (set the real register to the current value of another virtual register), or "expression" (as above, unimplemented). Finally, update rip with the value of the virtual register listed in the CIE as the return address register, and update rsp to the value of the CFA register (the CFA register is defined as always being the final value of the stack pointer). And we're finally done. If an error occurred during any of this, it's immediately returned, and the DWARF parser bails out completely. Recovering from anything going wrong in all that is just not worth the trouble. Function to CPU: I was framed! Walking the stack with the frame pointer is by far the simplest method of them all. All it takes is dereferencing the current value of rbp, and doing a simple check to make sure it points to somewhere remotely sane in the process stack. There's no way of being entirely certain that it hasn't put you in entirely the wrong place, of course. If you trust it, update rsp with the old rbp plus 16, update rip by dereferencing the old rbp + 8, and you're done. libtinyunwind's frame pointer function currently doesn't exist. Another thing to do in the future, like the DWARF expression evaluator. This is mostly because the frame pointer attempt isn't much better than the stack scanner for functions with stack frames, and it's worse for functions without them. Do you see a return address in this stack? Take your time. A stack scanner does work something a bit like a police lineup, in fact; it goes through the stack one pointer-sized word at a time until it finds something that looks like a return address, and uses it. There's not too much to say about the implementation of the stack scanner in libtinyunwind. It just saves off the last place it looked on the stack each time it finds something that looks like a return address, and uses that as its starting point next time it's called. If it doesn't find an address within some arbitrary number of words (50 was the value coded in), it gives up. rip is updated with the found address, rbp is updated with the next word before it on the stack (a best guess), and that's that. You left without even getting the function's name? Once a function has been found on the stack, it's really rather helpful to know just which function it is, and maybe even where inside it the process was at the time. libtinyunwind provides a symbolication facility with the aforementioned get_symbol_info function. get_symbol_info is the only function in libtinyunwind that currently works for 32-bit processes. get_symbol_info first checks whether image tracking is turned on, because without it there's nothing to symbolicate with. Next, it does the same thing all the unwinding methods do: Looks for an image that contains the rip value being searched. If it can't find an image, or that image doesn't seem to have a symbol table, it gives up. Next, it searches the image's global and local symbol tables for a matching symbol. A symbol table is stored as a list of starting addresses. This means that if the image has five symbols starting at 0x001, 0x005, 0x009, 0x015, and 0x020, and you ask for a function containing address 0x014, the table has to be searched until both 0x009 and 0x015 are found so that both lower and upper bounds are established. The global table is searched first, then the local table. Both are always searched in their entirety; symbol tables are not guaranteed to be ordered, and the only way to be sure a given result is correct is to make sure every bound has been checked. When a matching symbol table entry is found, its starting address is read from the entry, and the name is read from the image's string table. A direct, read-only pointer to the name is returned, making the function async-signal safe. Memory safety One particular quirk of libtinyunwind is that an async-signal safe crash handler, running after something has already gone horribly wrong enough to cause a crash in the first place, may be working with hugely invalid memory addresses. In this situation, any memory you read from could result in a crash, and crashing in a crash handler either deadlocks the process (as the UNIX signal remains blocked even though the signal handler can't continue executing) or just causes immediate termination. Either way, you've lost the crash data you were so interested in gathering. Fortunately, you can read process memory in a way that simply returns an error if you access an invalid address, instead of setting off a fresh EXC_BAD_ACCESS. I have to credit Landon for this one as well, as it's another bit I copied from PLCrashReporter itself. The key is the vm_read_overwrite() function. I do not know exactly how it works, and I certainly don't understand why it's named the way it is, but it reads process memory without crashing the process on invalid access, and that's the important part. libtinyunwind uses it all over the place so it can fail gracefully when memory's too corrupted to do anything with. Conclusion That just about wraps up my discussion of stack unwinding. As you've seen during my commentary, there are some pieces still missing from libtinyunwind, most importantly multi-architecture support, but they won't be missing forever. I had a whole lot of fun with this project, and I'm very grateful to have had the opportunity to do it; I intend to continue. The code is licensed under the same terms as PLCrashReporter itself; I hope there will be a release fairly soon. I'll be back with another Friday Q&A after Mike's next articles. Until then, happy coding! thread_get_state(), we can't get at the information we need at all, and without vm_read_overwrite(), we can't do it and expect it to work much of the time. Reading the kernel source says they're both safe as currently implemented (and have been for some time), so that ends up having to be good enough. Really, though, if you look at the list of declared-safe APIs, it's hard to believe that read()could be safe where vm_read_overwrite()wasn't, and fork()would have to get at the same information that thread_get_state()does. Add your thoughts, post a comment: Spam and off-topic posts will be deleted without notice. Culprits may be publicly humiliated at my sole discretion.
https://www.mikeash.com/pyblog/friday-qa-2012-05-04-plcrashreporter-and-unwinding-the-stack-with-dwarf-part-2.html
CC-MAIN-2017-34
refinedweb
4,867
59.84
Understanding Practical API Design, Static Typing and Functional Programming or an exception or other backdoors that cause the death of millions of kittens worldwide. - If I call moveon a tic-tac-toe board, but the game has finished, I should get a compile-time type-error. In other words, calling moveon inappropriate game states (i.e. move doesn’t make sense) is disallowed by the types. - If I call takeMoveBackon a tic-tac-toe board, but no moves have yet been made, I get a compile-time type-error. - If I call whoWonOrDrawon a tic-tac-toe board, but the game hasn’t yet finished, I get a compile-time type-error. - I should be able to call various functions on a game board that is in any state of play e.g. isPositionOccupiedworks! March 6th, 2011 at 4:00 am Those are good rules and a very nice API. My only small gripe is the API of (say) MoveResult seems a bit cryptic to someone unfamiliar with FunctionalJava. Maybe in Scala it would be simpler. FWIW I would have dispensed with BoardLike and merged it into Board instead, unless there’s some objection. And I’d have simply named the inner classes Board.Finished and Board.Empty. I find myself doing that a lot, e.g. MyList with subclasses MyList.Mutable and MyList.Immutable. March 6th, 2011 at 8:26 am When you say: If you write a function, I must be able to call it with the same arguments and always get the same results, forever You literally mean a “function” not a “method”, is that correct? March 6th, 2011 at 9:01 am Jonathan, MoveResult is a church-encoding of an algebraic data type, which Java does not have. It is only as “cryptic” as it should be and no more. Even in Scala and sometimes Haskell, I encode the data type like this, since it is *easier to read*. Board is not the only instance of BoardLike. Names don’t mean very much to me. Hossam, I literally mean a function, in that it returns the same result for its given arguments. I don’t care about how you model this in the language. March 6th, 2011 at 11:02 am Excellent insight. Alas even at Major software companies we have a lot of trouble with this. I always thought it was due to the amazingly long cycle between API creation and customer bug reporting but it sounds like it’s a fundamental educational issue to some extent. Thanks for writing it up, Kav March 6th, 2011 at 12:04 pm > Board is not the only instance of BoardLike. Unless I’m missing something, is there any need for the distinction between Board and BoardLike? Can’t it all go in an abstract Board class (though no doubt with some concrete methods and fields) with (Board)Finished and (Board)Empty as the only subclasses? March 6th, 2011 at 12:20 pm Interesting restrictions, interesting results. As someone who sees the elegance in your result, but would likely have some difficulty reproducing the results, what areas of study would you suggest to pursue in order to improve my ability to produce APIs like this? March 6th, 2011 at 12:37 pm Hi Jonathan, the Board class has a move method. It’s important that a (Board)Finished does not have this method, so subclassing will not work. It’s great to see you work through these issues in your mind Hope these sort of exercise are helpful for you! March 6th, 2011 at 12:48 pm Hi Chris, In my time teaching these sort of techniques, I have found it very difficult to simply pile a bunch of articles on a person and expect a useful result. Instead, I recommend practice, coupled with knowledge acquisition and doing this iteratively. For example, you might set yourself a similar goal and model say, the game of chess. In doing so, you will likely hit some barriers then ask how to best overcome them — this is when you will likely have to read about some concept or something. However, it is very common for there to be a disconnection between this concept and how it will help a student overcome the barrier. In times like these, I use several methods of explanation that will help the student to make this connection in such a way that they feel confident in exploiting it. It’s very tough for me to hand you a bunch of keywords and expect you to be able to head off on your own and learn it all for yourself. Nevertheless, I have seen this happen on one or two occasions! The key techniques here that were exploited are static typing and software correctness verification in general, which is an incredibly deep topic and also widely misunderstood (and you are surely aware that this doesn’t stop the proliferation of opinion!) and the functional programming thesis. In terms of understanding static typing, there are some “easy bite-offs” so to speak — topics that you may read and learn about, probably understand quite easily and have a good return on this investment of effort. However, I do not have a “formula” that I can confidently give you to help you understand the topic more deeply. Such topics as the Curry-Howard Isomorphism and perhaps the Free Theorems (Wadler) paper are great places to start, since even if you were just a casual programmer (and not an interested one like you are), these would still be beneficial. As for learning functional programming and why it is important, I recommend, in this order of high to low importance: practice, become very sceptical of the vast amounts of misinformation that may throw you off-track, Why Functional Programming Matters (Hughes), The Essence of Functional Programming (Wadler). I have also given a presentation about learning functional programming, but I don’t think it was video-recorded (can anyone find a recording? I can’t). Here are the slides: Also, I’m happy to answer any questions you might have on your learning journey. I can also refer you to others who can help answer questions too — some people have different approaches to teaching these topics that can be complementary and helpful to various students. Good luck! March 6th, 2011 at 10:10 pm Hi, I did not understand yet how to get a FinishedBoard. Starting from, EmptyBoard a = Board.EmptyBoard.empty() Board b = a.move(E) MoveResult r = b.move() I have no idea how to proceed. March 6th, 2011 at 11:57 pm Hi Pedro, Once you have a MoveResult, you might a FinishedBoard, but you also might not. This is determined by which function is called as the argument when you call MoveResult.fold. March 7th, 2011 at 12:18 am Ah! So is the fold just a replacement for pattern matching? March 7th, 2011 at 7:47 am Pedro, Precisely. You are probably familiar with scala.Option. It can be rewritten like so: This data structure is exactly equivalent (isomorphic) to scala.Option March 7th, 2011 at 9:13 am Hi Tony, Thanks for the thought provoking post. I have been trying to move to a more fp style in the code I write, but this application of compile-time type-errors to what is seemingly run-time state change (urgh, state!) is an eye opener. MoveResult.Fold seems to be the key, I’ve gone away and read about Scala.Option, but was hoping you could expand on exactly how this method operates? - Are we passing in a predicate and two functions, if the predicate is true we execute (or return?) the first function, false we execute (or return?) the second function? I’m going to try and write a c# version, could you post a link to source in a few days? Cheers, Adam Webber March 7th, 2011 at 6:48 pm Hi, thanks for this post, this is really interesting. I am also interested in a C# solution and would be happy to see the source in some days. March 7th, 2011 at 7:24 pm Hi Adam, You might think of the MoveResult.fold function as a switch that can act on arguments. One of those functions will be executed to produce a result — which one is executed depends on what the result of the move actually is. If you are familiar with algebraic data types (as in Haskell, ML or Scala), there is another explanation regarding switch between the church encoding of that type and the type itself. March 7th, 2011 at 7:44 pm Thank you Tony for the best sales pitch I have ever seen for functional programming. I believe that these are exactly the points needed to be made to make some IT department, lost in the alternate reality of “object orientation” and “software development methodologies”, aware of the benefits of correct methods. To trick the object oriented mind into understanding your MoveResult class you could let the catamorphism masquerade as a visitor: public interface MoveResultVisitor { public X positionAlreadyOccupied(); public X keepPlaying(Board board); public X gameOver(Board.FinishedBoard board); } Cheers, Joel March 7th, 2011 at 7:47 pm Hi Tony Thank you for the interesting exercise ! If the MoveResult.fold function is a switch, can we use pattern matching instead if we use Scala ? For example: moveResult.board match { case b:Board => keepPlaying(b); case bf:Board.Finished => finishGame(bf) } Does it make sense ? March 7th, 2011 at 8:20 pm Hi Joel, Thanks for the feedback. Your visitor will not work because it is conjunctive rather than disjunctive. Remember that MoveResultdenotes one (and only one) of a position already occupied, keep playing with a board or game over with a finished board. Otherwise yes, the visitor pattern is just a fancy name for what is essentially (without the useless ceremony) catamorphism. Most design patterns are quite silly like this, March 7th, 2011 at 8:26 pm Michael, yes it certainly does make sense. However, you shouldn’t be type-casing in your pattern-match. Rather you should be delineating with your own type (as in MoveResult) with multiple constructors. It is unfortunate that Scala permits type-casing like this. March 7th, 2011 at 9:00 pm Tony, thanks ! Can you help to get rid of type-casting in my example with the Scala pattern matching ? March 7th, 2011 at 10:07 pm Is the actual implementation of the Java available? I think I understand what’s going on, but I want to check. In particular I want to answer the question: “Are keepPlaying, keepPlayingOr and tryMove just utility functions?”. March 7th, 2011 at 11:57 pm Hi Tony, The generic parameter was lost in translation: public interface MoveResultVisitor<X> { public X positionAlreadyOccupied(); public X keepPlaying(Board board); public X gameOver(Board.FinishedBoard board); } The visitor is equivalent to P3<X, F<Board,X>, F<Board.FinishedBoard,X>> Implementing the visitor pattern would be a matter of simply changing the type of MoveResult.fold to public abstract <X> X fold(MoveResultVisitor<X> visitor); I can see one reason not to do that though: The visitor pattern as preached by GoF relies on mutable state and to a FP newbie this may seem like an invitation to keep up the bad work. March 8th, 2011 at 7:31 am Tom, Here is the Java source I don’t know if you would call those functions, utility functions. March 8th, 2011 at 9:17 am Is this pro-functional, anti-object-oriented, or both? Or neither? I ask because the premise of Scala - which you mention having an implementation of this in - is that OO and FP are complimentary. As I think about it, I think that this post illustrates that FP is a mindset, not a language feature. You can do functional in just about any language. I suppose that’s the only way for it to make sense that you didn’t go into your Haskell and Scala implementations. I presume that many would have read such a thing as a anti-Java/pro-Scala rant and the world isn’t exactly lacking for those. Anyway, very interesting and thought provoking. March 8th, 2011 at 10:18 am Steve, It is neither, they are not in contention, nor are they dichotomous. What you refer to as the premise of Scala, is not the premise of Scala, but the stated premise of Scala. That stated premise of Scala is, in my opinion, total rubbish, and a useless distraction at best. Functional Programming is not a mindset — it’s a thesis. This thesis exists independently to all of our minds. However, Functional Programming is not a dichotomy, rather a continuum, and yes, all languages allow you to adhere to this thesis to some extent, along that continuum. Java is one of those — moreover, it is a language that explicitly goes out of its way to make adherence to this thesis extremely difficult, so raises the question of just how far you can take it. Nevertheless, it can be overcome to a greater extent than I predicted when we wrote Functional Java. I am writing Scala at this moment for work. In the kindest words, I am not feeling particularly “pro-Scala” at the moment. I use lots of languages. Stop marrying them and open your mind. If I was to write a “anti-Java” rant, I’d fucking destroy it. March 8th, 2011 at 12:03 pm Tony, I’ve just came across your site as I’m starting to learn fp (learning w/ scala) and I’m really impressed with the quality and intellectual level of the posts you write. I’m always of the opinion software devs can aim higher and I completely agree with you on that. I look forward to more articles and more witty jabs and sarcasm. Thanks March 10th, 2011 at 6:17 am Tony, Funny to hear you exhort people to “open their mind” when according to you, except for Haskell, any programming language is a useless pile of garbage. March 10th, 2011 at 9:10 am Jo, Opening your mind will prevent you from creating then attacking straw man positions. You should try it. It’s way more exciting than your dull sarcasm. Promise. April 5th, 2011 at 5:58 am Uhh, so you return a union type? This is not a difficult problem, but the way you explain it makes it seem like it is… April 5th, 2011 at 6:34 am GBH, I didn’t say anything about the difficulty, except to the extent that some people find it difficult. In fact, I thought it was easier that it seems to have turned out to be. April 5th, 2011 at 10:26 am A ten minute exercise in Haskell. My day job is Ruby: I have _no_ idea how I’d enforce those constraints. Maybe a preprocessor, so you can scrounge a compile-time step? Freedom is slavery… April 5th, 2011 at 12:55 pm “If call move on a tic-tac-toe board, but the game has finished, I should get a compile-time type-error.” Your Java solution lacks any of the “compile time” guarantees you listed. I do believe it can be done in Haskell or other language with advanced type system, seeing it Java would be impressive though. Programmers do think of proofs writing code, encoding them in type systems is not necessary. It would be nice if the machine checked the proof, but encoding proofs in type systems is a lot of effort for little gain. Perhaps the cost is worth when working on mission critical software, say some primary space shuttle systems. Static type system are a mid point between no verification at all and full blown theorem prover. They provide some guarantees imposing minimum hassle on the user. April 5th, 2011 at 4:19 pm Kamil, No, the Java solution provides exactly those guarantees. This is a fact that is easy to disprove were it not to be true. Luckily, it is true, so you won’t be able to disprove it. Perhaps you mean, “the Java solution to the extent that my imagination can conceive”, not the API solution that was given. There is no cost to writing an API properly. There are people attempting this problem using theorem provers, such as Coq and Agda. PS: You don’t know what a static type system is. I recommend changing this. April 5th, 2011 at 8:16 pm Interesting post. Will you post the Haskell code as well? It would be very interesting for comparison. April 5th, 2011 at 9:19 pm Thanks for the excellent post! My Java understanding is not quite good enough to grasp exactly what that fold is doing, but just seeing that an API like this is possible in Java is amazing. Can you sketch how the Haskell solution would look like? Would that require GADTs? April 5th, 2011 at 10:50 pm For me at least, I unit tests demonstrating client API usage would be instructive. April 6th, 2011 at 4:12 am Tony, “If I call move on a tic-tac-toe board, but the game has finished, I should get a compile-time type-error.” Here is a counter example. I break the Board.moveTo method so that it alway returns MoveResult.keepPlaing. After a couple of moves it is bound to get to a finishing state, where no moves are possible but the system will attempt to because I introduced a bug. The type system is happy despite the code being wrong. There is no compile-time type-error. I hope you see that you did not achieve static verification of that property. You can convince yourself of the correctness of the code by doing proofs in your head, but you did not encode them into the type system. April 6th, 2011 at 7:10 am Dammit, should know better than to post from an iPhone in a hurry at the airport. Try again… I’d be interested to see your approach applied to what I’d call the “distributed calendar” problem: I have a variable number if colleagues, each of us in a different location with unreliable network access. At any time I can grant or revoke permission to any of them to schedule a meeting with me. Those with permission can request a meeting at any time and I can accept or reject that request. If I accept the request the meeting is added to my calendar and theirs. I am automatically notified of an imminent meeting a number of minutes before the meeting, a number which I can choose, and change at any time before the meeting. My calendar always shows my meeting schedule using the timezone of my current location. I am genuinely interested to see the advantages of your approach when applied to a “software engineering” problem like this, as opposed to a ”computer science homework” problem. April 6th, 2011 at 7:37 am Kamil, Assuming the API is written bug free, which is the assumption he’s making to ensure that these properties hold, a consumer of the API *would* get a compile-time error if he/she misused it. That’s the guarantee he’s after, and that’s the guarantee that’s desirable when writing a public API. April 6th, 2011 at 11:31 am Kamil, You are missing the point. On the assumption that you do not have access to the code, which you do not, then yes this property holds — I just haven’t proven that property. I’m quite certain I stated this above. To restate, I could give you this API and you would be forced to accept these code properties. It is as possible to do this in Java as it is in Haskell, so regardless of your misunderstanding, whichever way you decide to look at it (including the way you currently are, which is beside the point), you cannot say there is a difference between Haskell and Java. If I gave you the library, and asked you to give me the chain of function calls that breaks the invariant, then you win a prize. I am very very confident that you are unable to do this. I hope this is clear. April 6th, 2011 at 11:35 am Keith, There is nothing about this problem that makes it not a “software engineering” and “computer science homework.” I expect this false dichotomy makes it difficult for you to see that you can apply the exact same techniques, because it is exactly the same problem-solving approach. Much of what you said about “notification” can be dismissed as trivial. If I understood the essence of your problem, rather than the trivial/irrelevant parts, maybe I could go further. April 6th, 2011 at 11:37 am Here is the code April 6th, 2011 at 3:07 pm You can dismiss a problem as trivial, or you can show how trivial it is to solve. Only April 6th, 2011 at 3:19 pm For one thing, the tic-tac-toe API doesn’t have to deal with any messy operational issues. The essence of my question is: how do you cost-effectively build a system out if pure functions when its semantics depend on handling multiple overlapping sequences of asynchronous requests made over unreliable channels? April 6th, 2011 at 4:55 pm Keith, When you say “messy operational issues”, what do you mean? Try to be precise here. You allude to I/O as if it somehow makes the problem more difficult — it doesn’t — quite the contrary. This is the entire point of this approach to programming. I don’t “dismiss it as trivial”, any more than you over-estimate the triviality. Indeed, the given tic-tac-toe API has a console application implemented just to demonstrate the outer layer — it’s not a stretch to imagine other forms of I/O. The point is that any I/O (whatever it may be) is clearly delineated from the algebraic representation of the problem at hand (which happens to be the hard bit). I could well have written a game server and so on — since I have this API very clear, then this outer layer will become extremely simple. There is no intertwining of the essence of the problem (representing a game API) with “messy operational issues.” Yes indeed, your given problem is very trivial. As soon as you let go of the idea that you have somehow made the problem more difficult by introducing “messy operational issues”, the sooner you will attain your desired insight. April 6th, 2011 at 9:37 pm Hi Tony Having just started out learning Haskell, I’d be interested in seeing the Haskell version. April 6th, 2011 at 10:28 pm Tony, I don’t think I agree that implementing an algebra of meetings on calendars would help much with the distributed calendar problem. It takes away one seat of latent defects, true, but not the major one, I think. This problem isn’t about managing a priority queue correctly. It’s about correct temporal ordering of side-effects in the world in response to events in the world, some of which change the parameterization of the rules about that ordering, and about maintaining consistant state over many agents connected by an unreliable transport. Those are the hard parts. Separating what I would call the essential domain of the system from the interaction domains isn’t a new idea, and isn’t unique to statically-typed functional programming. It does mean that the interaction domains can be treated separately, true. But then what? How does statically-typed functional programming help us get those interaction domains right? April 7th, 2011 at 9:27 am An window manager for an X11 system has many client and X11 calls to interweave correctly and a great deal of state to manage. The user may be typing and clicking and the applications will be issuing sizing requests and more. The XMonad program, written in Haskell, is a powerful window manager. Its code is slim but with many tests and is very solid because of static techniques. April 7th, 2011 at 2:54 pm Keith, The best way to manage those issues is with type-system level effect-tracking. I prefer Haskell’s, though there are others. I still don’t agree that it is all that difficult. I expect this is because I would insist on using effect-tracking before I considered solving it — anything else is just too impractical. April 7th, 2011 at 3:20 pm Tony, reference for this language feature? Unfortunately, googling “haskell effect-tracking” leads to a tweet citing a stackoverflow answer…by yourself. What would be a (non-circular April 7th, 2011 at 3:30 pm Keith, try this: April 7th, 2011 at 3:54 pm Tony, I see. So your answer boils down to “use the IO Monad and it’ll be super easy”. OK then. April 7th, 2011 at 5:40 pm Keith, No not the IO monad. The monad implementation is irrelevant. I wish to emphasise this, since I see it a lot — totally, absolutely irrelevant — as relevant as any other arbitrary programming concept. Rather, use a type system that delineates between values of the type (#RealWorld -> (#RealWorld, t)) and t. It won’t be super-easy; it will be much easier than you are making it out to be. April 8th, 2011 at 7:04 pm Oh dear, oh dear, oh dear. I’m too old. I wish had read this article 8 1/2 years ago. April 9th, 2011 at 9:42 am Colin, Why 8 1/2 specifically? April 11th, 2011 at 9:54 am Tony, would you mind to provide an example of how to use this API for a full game? I still fail to see the right way to do so. As `fold` seems to be very important here, and is called internally AFAIK, are some methods like `MoveResult.gameOver` even meant to be called by the client? April 11th, 2011 at 7:40 pm JK, Here is a console application that uses the API By the way, you use “fold” all the time — it’s just called something else and probably on a different algebraic data type. e.g. if/else is the fold for the boolean algebraic type. April 12th, 2011 at 4:46 am Hi Tony! ) Here is a nice scala solution to this exercise including some explanations: I started the exercise myself in java but I now wonder how painful that will be, so I may restart using scala. To put something useful into my wining post ( April 22nd, 2011 at 5:47 am Hi Tony! When I first read your blog, I was thinking, “How can one statically ensure something that will only be known at run time?”, and I still don’t quite get it. Your saying that your API will throw a compile-time error when one applies “move” to a board in a finished state. So shouldn’t I get a compile time error in a (Haskell) program like this: module Main where import Board import Position b1 = Position.NW –> empty Just b2 = keepPlaying $ Position.SW –> b1 Just b3 = keepPlaying $ Position.N –> b2 Just b4 = keepPlaying $ Position.S –> b3 Just b5 = keepPlaying $ Position.NE –> b4 Just b6 = keepPlaying $ Position.SE –> b5 main = return () Is your point mainly that in a good API, “–>” should lead to a “Either Board | FinishedBoard” kind of data type (in Haskell terms) instead of a “Board” type, so that one can use the more detailed type information for type checking? April 23rd, 2011 at 7:51 pm Hello Martin, the answer to your final question is yes. May 26th, 2011 at 5:41 am [...] read the delightful article on a type safe tic-tac-toe API recently. It got me thinking how one might do this for an application with a complex GUI and data [...] July 8th, 2011 at 1:44 pm The part I’m trying to wrap my head around (since your code seems to have disappeared) is this: in an imperative system, you’d have a board called the CurrentBoard. Each move would either (depending on the design) mutate that board or alternatively (more functionally) create a new board. But even if you chose the latter style, you would still have to update the CurrentBoard variable to point to the newly created board, a big FP no-no. In fact, as I understand it, the only FP no-no. And here’s the thing FP I don’t get: every system has state. Unlike functions, no (or nearly no) system exists solely to make calculations on its input. Every system I have ever worked on takes input, stores it for some time, and then later regurgitates it back in some form. I just don’t see how you do that just by composing referentially transparent functions. I asked the same question on StackOverflow; didn’t get a satisfactory answer. July 9th, 2011 at 9:23 am Malvolio, I don’t use stackoverflow, since as you allude to, you receive answers that are worse than nothing and I agree in your case, you received precisely that. I’m happy to help of course — perhaps on IRC? September 13th, 2011 at 9:00 pm Your post excellently conveys the paradigm of FP and its practical benefits in developing robust software by showing a concrete example. However, I think it could be made more instructional: 1. For FP newbies like me who don’t grok everything the first time, it would be great to see at least the usage of the API (e.g. the implementation of the Main class), or even better, more detailed JavaDocs or the implementation. Unfortunately, the link does not work. On github, I only find. Please provide us with a working link! 2. I presume it is the point of your course, but could you show the “algorithm”, the patterns of designing such stateless APIs? Thank you very much! September 15th, 2011 at 7:48 am Hi Dénes, Included in that link you gave is a usage of the API in Java, Scala and Haskell to implement a basic console–based interactive game. I apologise for the link not working — I changed its location. Here are some answers: September 18th, 2011 at 12:25 am In the scala example, I don’t understand what is the inheritance: B => BoardLike in the gameloop function used for. It is only called twice with v=>v . Is it some type conversion trick ? thanks Miguel Negrão September 18th, 2011 at 11:47 am Hi Miguel, Which code are you referring to exactly? October 18th, 2011 at 6:36 pm Interesting, thought-provoking post. I am wondering if it’s possible to provide such strong guarantees in most “real world” applications, though. Image processing is a big part of my work, and I can’t have a drawing function return a new copy on every call - that would be very slow. The usual solution would be to use a handle/pointer, which breaks this rule: » If you write a function, I must be able to call it with the same arguments and always get the same results, forever. In Haskell I think it would be possible to use a function ala `withMVar’ or `withFile’ and a monad to allow a user to do stuff like: withImage :: Image -> (ImagePtr -> IO ()) -> IO Image test :: Image -> IO Image test img = withImage img $ do drawCircle (0, 20) 5; drawLine (4,4) (8,8); But drawCircle and drawLine are still opaque. Using a data structure like difference lists also sounds impossible, since it would drastically affect performance (and prevent using optimized C libraries in the implementation). How is it possible to have a robust API under this kind of constraints? January 7th, 2012 at 9:47 am I wanted the Java source. The links are broken (even the last one). I would be delighted to know how can you produce a compiler error in Java for something that would be verified only in runtime. That’s what really got me. February 24th, 2012 at 5:33 am The answers are here as of Feb 2012: Poke around the site for more implementations in other languages and other problems/solutions.
http://web.archive.org/web/20120325044648/http:/blog.tmorris.net/understanding-practical-api-design-static-typing-and-functional-programming/
CC-MAIN-2017-30
refinedweb
5,415
71.04
The Rust/WinRT language projectionThe Rust/WinRT language projection bindings for the target programming language. As you can imagine, this allows developers to more easily build apps and components for Windows using their desired language. You can then use those Windows APIs to build desktop apps, store apps, or something more unique like a component, NT service, or device driver. Getting startedGetting started Start by adding the following to your Cargo.toml file: [dependencies] winrt = "0.7" This will allow Cargo to download, build, and cache the Rust/WinRT support as a package directly from crates.io. use winrt::*; // Now use the `import` macro to import the desired winmd files and types: import!( dependencies os types windows::data::xml::dom::* windows::foundation::* windows::ui::* ); // Finally, make use of any WinRT APIs as needed. For example, here is // an example of using the `XmlDocument` class to parse an XML document: fn main() -> Result<()> { use windows::data::xml::dom::*; let doc = XmlDocument::new()?; doc.load_xml("<html>hello world</html>")?; let root = doc.document_element()?; assert!(root.node_name()? == "html"); assert!(root.inner_text()? == "hello world"); Ok(()) } For a more complete example, take a look at Robert Mikhayelyan's Minesweeper. SafetySafety We believe that WinRT bindings can map to 100% safe Rust. However, often times WinRT APIs are implemented in non-memory safe languages (e.g., C++). WinRT-rs users can be sure that (modulo bugs), the WinRT interop bindings generated by this crate are 100% safe to use. Users should, however, make sure that the code that implements the APIs being called through WinRT-rs bindings are either written in safe Rust or have been audited for memory safety and correctly adhere to the WinRT contract. WinRT APIs written in safe Rust and consumed from Rust using WinRT-rs should therefore be 100% memory safe. We take these safety gurantees very seriously. Please let us know if you run into issues where you see Rust's memory safety guarantees being violated through use of this crate. IDE supportIDE support WinRT is developed with and tested for the rust-analyzer VS Code extension. We want WinRT-rs to work well with rust-analyzer, so if you run into issues, please file a bug report so we can look into it. There are, however, a few things to note about WinRT-rs and rust-analyzer: - WinRT-rs can sometimes generate a lot of code causing rust-analyzer to slow down. This can mean it may take upwards of a several minutes when running rust-analyzer for the first time on a code base where large WinRT namespaces are used. Additionally, it may take a second for some code completion hints to show. These are known issues. We hope to work with the rust-analyzer team to address these performance concerns. - If you generate code using a winrt::build!in a build script, it is important to turn on the "rust-analyzer.cargo.loadOutDirsFromCheck" setting in VS Code. This runs cargo checkso that rust-analyzer is aware of generated code in the OUT_DIR. Leaving this setting off will cause rust-analyzer to not recognize the generated namespaces breaking code completion. Cross-platform supportCross-platform support While support for platforms other than Windows (i.e., *-windows-msvc targets) is possible and on the long-term roadmap, support outside of Windows is not an immediate goal. If you are interested in support outside of Windows, please let us know. Project ReunionProject Reunion Project Reunion is a set of libraries, frameworks, components, and tools that you can use to access powerful Windows platform functionality from all kinds of apps on many versions of Windows. Project Reunion combines the power of Win32 native applications alongside modern APIs, so your apps light up everywhere your users are. Other Project Reunion components include WinUI, WebView2, MSIX, C++/WinRT, and C#/WinRT. If you'd like to learn more, contribute to Project Reunion, or have app model questions, visit Project Reunion on GitHub.
https://reposhub.com/linux/miscellaneous/microsoft-winrt-rs.html
CC-MAIN-2021-43
refinedweb
658
54.93
Recently, Scott Hanselman has proposed a survey to know which part of the .NET Framework real-world developers are using. The result will be interesting mostly for Microsoft engineers in charge of the .NET Framework. However, it might be interesting for a team to know which tier code its code base really uses. You certainly know coarsely if your code base is using or not, libraries such as ADO.NET, WPF, Windows Form, ASP.NET but also NHibernate, NUnit or Log4Net. But can you answer these 2 questions? · Which part of the code base uses which library? · Which types and members of the library are really used by your code base? Before rambling on why you should care about these questions and what are the perspectives offered by an accurate control of the usage of tier code, let’s illustrate how NDepend can help answering such questions and more in seconds. Let’s analyze the code of the OSS (yet very professional) application Paint.NET v3.0. Assemblies of the application are in black while library/tier/framework assemblies are in blue. The Dependency Matrix shows which assemblies of the application are using which tier assemblies. For example, we can see that the library SharpZipLib is only used by the assembly Paint.NET. Things get really interesting when we unfold tier assemblies. Indeed, during analyzes, NDepend only focus on code elements of tier assemblies that are really used by the application. Here the Dependency Matrix unfold possibility is a powerful tool to dig in who is using what. For example, the following screenshot shows that 8 members of the class List<T> are used by 7 methods of the assembly Paint.DotNet.Data. One can easily browse this coupling with the Dependency Matrix… …but also, with the Dependency Graph which is clearly more appropriate here: Diff in the usage of tier code NDepend allows comparing 2 different builds of an application, to know which code has been refactored, added or removed. While a code base is evolving, the way it uses libraries is evolving also. Some libraries are discarded, some tier classes that wasn’t used are now used… While comparing 2 builds, NDepend also compare the tier code usage. Hence, while unfolding a library code in the class browser, we can easily pinpoint which tier code elements that weren’t used are now used (in bold), which tier code elements are not used anymore (striked) and which tier assemblies/namespaces/classes contains some usage change (underlined). The following screenshot illustrate the usage diff of collections between Paint.NET v2.72 and Paint.NET v3.0. We can see at a glance for example that between these 2 releases, developers of Paint.Net thought that using the interface IDictionary<TKey,TValue> was a good idea. If you prefer, you can harness the 3 dedicated Code Query language conditions IsUsedRecently / IsNotUsedAnymore / IsUsedDifferently to query the diff in the usage of tier code: SELECT TYPES FROM NAMESPACES “System.Collections.Generic” WHERE IsUsedRecently / IsNotUsedAnymore / IsUsedDifferently Constraining the usage of tier code While this is cool to control the usage of tier code with such accuracy, I would like to explain how this possibility is useful for developers. One of the direct application is to forbid some incorrect usage of a library. For example, as explained here, while running with .NET v2.0 runtime, the ultra-popular method String.IsNullOrEmpty(String) can raise a NullReferenceException. I don’t really know if this bug has been fixed but in fact I don’t care, because we wrote the following CQL rule to make sure that we don’t use this method (we use our own implementation actually): // <Name>String.IsNullOrEmpty() is bugged and must not be used</Name> WARN IF Count > 0 IN SELECT METHODS WHERE IsDirectlyUsing “OPTIONAL:System.String.IsNullOrEmpty(String)” Notice the OPTIONAL: prefix. Without it, this query wouldn’t compile. Indeed, as the method IsNullOrEmpty() is not used by our code base, the analysis doesn’t reference it. Without the OPTIONAL: prefix the CQL compiler would emit a ‘Cannot find method named …’ error. Let’s dig in another real-world example. We are relying on the DevExpress DXperience Windows Form library to enhance the usability of our product. Amongst plenty of cool stuff, this library lets control the skinning of controls. This is only possible if you use the DXperience buttons (and other controls) instead of the classical Windows Form button. To prevent a developer to use a classical Windows Form button, and then to guarantee a coherent skinning of our UI, we wrote the following rule: // <Name>All buttons should be of type DevExpress.XtraEditors.SimpleButton and not System.Windows.Forms.Button</Name> WARN IF Count > 0 IN SELECT FIELDS FROM ASSEMBLIES WHERE IsOfType “OPTIONAL:System.Windows.Forms.Button” The possibilities to control how your code uses libraries are endless. We provided by default a set of around 30 rules (some borrowed from FxCop, some others from our experience) about the usage of the .NET Framework. We expect to release more default rules in the future, also relative to popular framework usage such as NHibernate or Log4Net. What is really cool is that each time a developer detects a particular library usage issue, he can very easily define some custom rules about it. The rules can be named appropriately and contain further comment detailing the issue. This way its co-worker will be aware of this issue and won’t redo the same error in the future. Hence such set CQL rules helps capitalizing on the experience acquired the hard-way on a library. Btw, don’t hesitate to report us the coolest rules you found on any popular library (.NET framework included). Separation of Concerns and usage of tier code I would like to mention that a few months ago, I explored in this blog post, Dependencies and Concerns, an interesting application of controlling the usage of tier code. Basically the idea is, tell me what you are using and I can tell you with what you are concerned about. Hence, the post explains how you can write some rules, to forbid for example using some ADO.NET stuff at the same time as using UI stuff. In other words, you get a mean to write rules to check that concerns of you application are properly separated (like, the UI code shouldn’t use directly the DB code). Another interesting field to explore is to make sure that special concerns such as threading, error handling, logging, users’ authentication, security permissions… are strictly used within some bounded regions of your code. WARN IF Count > 0 IN SELECT METHODS OUT OF NAMESPACES “Product.UI.ThreadingHelper”, “Product.DB.ThreadingHelper” WHERE IsDirectlyUsing “System.Threading”
http://codebetter.com/patricksmacchia/2008/10/20/controlling-the-usage-of-libraries/
CC-MAIN-2015-06
refinedweb
1,120
54.52
1. Create a m-file function which encapsulate your subroutine, and save it to a folder: 2. Add this folder to Matlab path: in Matlab, File > SetPath 3. In MATLAB command window, type “deploytool” 4. In MATLAB window, click the File new icon to create a New Deployment Project. - In the New Deployment Project dialog box, select MATLAB Builder NE and .NET Component. - In the name textbox, type whatever meaningful titles, and then click OK. 5. Select “Generate Verbose Output” and Add the source *.m file to the project, and then save the project. 6. Build the component by clicking the “Build “button in the Deployment Tool toolbar. The build process begins, and a log of the build appears in the Output pane of the Deployment Tool. The files that are needed for the component are copied to two newly created subdirectories, src and distrib. A copy of the build log is placed in the src directory. The building process may take quite a few seconds…, have a cup of coffee now… Now the output folders and files may like this: 7. Now, almost done! Let us try and test it in VisualStudio.net, write source code for a C# application that accesses the component, for instance: NDimVoronoiDiagram vg=new NDimVoronoiDiagram ( ); MWArray [] Results=new MWArray[2]; Results = (MWArray [])vg.CalVoronoiDiagram(2, (MWNumericArray)X, (MWNumericArray)Y); double [,] VoronoiVertices =(double [,]) Results[0].ToArray(); object[,] VoronoiEdgeIndice = (object[,])Results[1].ToArray(); 8. Add two references, \toolbox\dotnetbuilder\bin\win64\v2.0\MWArray.dll and the generated dll, in our case, NDimVoronoiDiagram.dll, build the solution, and that is it. Note that a ” Runtime Error R6034, An application has made an attempt to load … ” occurs one when initializing the NDimVoronoiDiagram object, and I am running Matlab on Vista x64, and I cannot figure out the reason, and if any one has solutions, please let me know. ***************************************** Extra note I: I put the matlab project inside my VS project folder, and compile it, it results in the failure of reflecting the output dll using ObjectBrowser in VS, and this directly leads to unknown namespace which contains the Matlab class.Very weird. Extra note II: The namespace, class name and the method name follows the rules as dipicted in the figure below. aminD February 17, 2010 at 5:39 pm ThanX alot ! Majd April 11, 2010 at 5:13 am Thanks very much , this is the most useful tutorial on the net. ف wildchild ۞ April 20, 2010 at 4:57 pm that was the common error if you are using Matlab 2009a. i heard the later version fix this error. i too have similiar error using 2009a. now, i’m using 2007a and its working just fine Iman April 27, 2010 at 6:28 pm That’s cool,really good and useful tutorial. Aidan June 17, 2010 at 10:37 pm How did you get the image of the plot to show in the program window? The code for that would be very useful! xinyustudio June 18, 2010 at 12:33 am You can try MS Chart control, which is shipped for free in .Net 4.0 library. The control which I use in the post is called ZedGraph control. Google it and get it. Good luck and happy coding! Aris July 9, 2010 at 10:51 pm What about if your .m file functions calling sub-functions. Do these subfunctions needed to be added as .Net components as well? xinyustudio July 9, 2010 at 11:20 pm Interesting question, shall look into that. Mehdi September 20, 2010 at 7:37 pm Hi I wrote this code in my m file and I made the dll. But it didn’t work. Is some thing wrong in my code? Is it necessary to use “Function”? my code: cd(‘c:\S_function_final’) open untitled22.mdl [t,x,y] = sim(‘untitled22’) xinyustudio September 20, 2010 at 8:00 pm Yes, the m file should be declared as functions, even though it contains zero argument. More details can be found in Matlab help. Mehdi September 21, 2010 at 9:03 pm Thanks for your answer. I changed the m file code to this (my m file name is A3): function open cd(‘c:\S_function_final’) open untitled22.mdl [t,x,y] = sim(‘untitled22’) end and in my .net project I wrote this: Dim o As New A3new.A3newclass o.A3() but it didn’t work and this is the error: mwmcr::evaluatefunction error: error using ==> open at 127 file ‘Untitled22.mdl’ not found. Error in A3 at 2 xinyustudio September 22, 2010 at 9:44 am Mehdi, you are right this might not work, and the function should be like below: SomeAction.m ================================== function SomeAction() % You might need (), even though no arguments %Put your code here end ================================== The discussion is not strongly related to the topic in this post, this is more a Matlab related issue, and less relevant to the Matlab+.Net. Anyway, hope it is useful to you. Darko November 23, 2010 at 7:25 am I made .dll from my .m file, but now I have problem how to take my outputs from the function. My function have 2 outputs. If someone know how to use the value from outputs in my C# code please help me. xinyustudio November 23, 2010 at 8:22 pm Suppose your function in Matlab is like this: [A, B]=GetSomeOutput(C) —————–C#—————– MWArray[] Output=GetSomeOutput(C); A=Output[0]; B=Output[1]; —————–C#—————– You can view the signature of the compiled functions (DLL) using “Object Browser” in Visual Studio. Is this what you want? Abd October 29, 2011 at 11:07 am I have tried to add WMArray as namespace ,in C# , but allways i got error says that MWArray is could not be found , and also The gerenerated DLL , which I made it , I could not use it ..is a TESTDLL and magicsqurearray inside it ,, any help please ali kipel December 22, 2011 at 4:42 pm I thing Abd is Right. What the MWArray [] Results=new MWArray[2]; I didnt find reference about MWArray how can get the variable values from matlab. I mean I use ANS in matlab how can . Please say somethings thank you.. ali kipel December 22, 2011 at 4:43 pm And Can you send me some example about this thank you Armin January 25, 2012 at 12:31 pm thankss alot , very very nice, Skyns March 22, 2012 at 2:56 pm Please, help me to solve the problem: my mablab function: —————————— function [y]=xmin(x) [b, a]=butter(6,0.2); [y]=filtfilt(b, a, x); —————————— C#: ——————————- const int X = 150; MWArray[] In = new MWArray[X]; MWArray[] Out = new MWArray[X]; filtfilt ff = new filtfilt(); for (int i = 0; i < X; i++) if (i < 50) In[i] = 0; else if (i < 100) In[i] = 1; else In[i] = 0; ff.xmin(1, ref Out, In); //accessing matlab function(here appeares acception!) ——————————- After building C# project I get acception: ————————————————– An unhandled exception of type 'System.Exception' occurred in MWArray.dll Additional information: … MWMCR::EvaluateFunction error … Error using xmin Too many input arguments.. —————————————————- HOW CAN I PUT AN ARRAY FOR INPUT INTO THE FUNCTION: ff.xmin(1, ref Out, In); ??? please, help, It is very important. Monim Sudan March 25, 2013 at 3:09 pm Thanks and Regards Nice test
https://xinyustudio.wordpress.com/2009/07/13/using-matlab-functions-in-c/
CC-MAIN-2016-18
refinedweb
1,222
73.98
I just registered on this board for help with a problem I'm having. I recently had to edit an older assignment to use a linked list and after completion of the program it seg faults right off the bat. I understand the difficulties with trying to diagnose these but I really have no idea where to start, I've had a lot of problems with seg faults in the past and something about arrays or pointers or possibly using the wrong scanning function but in general I just must be missing something about these at least. Here's the beginning of my code, the rest is simple functions that work similarily to the add() function. The gist of the program is that it's supposed to open a file and read its contents into a linked list, then shoudl dynamically update the linked list based on what the user inputted and then rewrites the file at the end. The file is also ciphered using a simple cipher before being written to the file. Any minor thoughts or things I could try would help as well.Any minor thoughts or things I could try would help as well.Code:#include<stdlib.h> #include<stdio.h> #include<string.h> char* decipher(char* decipher); char* cipher(char* cipher); void menu(list* ptr); list* add(char* bar[], list* ptr); list* edit(char* bar[], list* ptr); list* verify(char* foo[], list* ptr); list* del(char* bar[], list* ptr); void addToList(list* ptr, char* foo, char* poo, char* boo); void printList(list* ptr); //prototypes #include"cipher.c" #include"menu.c" typedef struct list { char *user; char *pass; char *type; struct list *next; } list, node; list* initializeList() { char buffer[50]; node* initial; node* ptr; FILE* addUser = fopen("password.csv", "rt"); initial = (node*)malloc(sizeof(node)); if (addUser != NULL) { fgets(buffer, 50, addUser); //Initializes first node of list initial->user = strtok(buffer, " ,"); initial->pass = strtok(buffer, " ,"); initial->type = strtok(buffer, "\n"); initial->next = NULL; //ready's addition of next node ptr = initial; while(!feof(addUser)) { while(ptr->user != NULL) ptr = ptr->next; node* link = (node*)malloc(sizeof(node)); fgets(buffer, 50, addUser); link->user = strtok(buffer, " ,"); link->pass = strtok(buffer, " ,"); link->type = strtok(buffer, "\n"); ptr->next = link; } } fclose(addUser); return initial; } int main(int argc, char* argv[]) { printf("lolol"); list* linkList = initializeList(); char* choice = argv[1]; int i; if (!strcmp("-menu", choice)){//If statement processes menu mode, if specified by user menu(linkList); printList(linkList); free(linkList); return (-1); } for (i = 2; i < argc; i++){ if (!strcmp(argv[i],"-menu"))//Determines if menu was incorrectly specified at command-line { printf("Syntax Error: -menu must be the first argument.\n"); return (-1); } } if (!strcmp(choice, "-add")) add(argv, linkList); else if (!strcmp(choice, "-del")) del(argv, linkList); else if (!strcmp(choice, "-edit")) edit(argv, linkList); else if (!strcmp(choice, "verify")) verify(argv, linkList); else { printf("Syntax Error: possible arguments include -menu to enter menu-driven mode or," " -add, -del, -edit, or -verify followed by the entry arguments.\n"); return (-1); } printList(linkList); free(linkList); return 0; } list* add(char* array[], list* linkList){ node* ptr = linkList; char *userCheck; char *ciphered[3]; printf("How about here"); while (ptr->user != NULL) { userCheck = strdup(ptr->user); userCheck = decipher(userCheck); if (!strcmp(array[2], userCheck)) { printf("Entry already exists"); //Checks if user is already present in the directory return (-1); //Does not allow for more than one instance of the same name. } ptr = ptr->next; } ciphered[0] = strdup(cipher(array[2]));//Passes user, password and type to be ciphered ciphered[1] = strdup(cipher(array[3])); ciphered[2] = strdup(cipher(array[4])); ptr = (node*)malloc(sizeof(node)); //creates new struct for contents to be added addToList(ptr, ciphered[0], ciphered[1], ciphered[2]); return linkList; }
http://cboard.cprogramming.com/c-programming/125051-confusion-using-pointers.html
CC-MAIN-2015-27
refinedweb
622
50.16
it's not a complaint you're making, as every time we discover one of these vulnerabilities it's fixed within grsecurity (like this 64kb heap infoleak I actually reported and wasn't credited for:-...), and I have it on good authority from Linus that issuing a patch is the same as full disclosure. Is it only a problem when the shoe's on the other foot? -Brad 2694 r + Dec 11 12:12PM tytso@mit.edu Re: ext4 bug 2695 r + Dec 11 03:37PM tytso@mit.edu └─> X-Spam-ASN: AS14742 69.25.192.0/20 X-Spam-Checker-Version: SpamAssassin 3.2.4 (2008-01-01) on X-Spam-Level: X-Spam-Status: No, score=0.0 required=5.0 tests=BAYES_50 autolearn=ham version=3.2.4 From: tytso@mit.edu To: Brad Spengler <spender@grsecurity.net> Subject: Re: ext4 bug X-SA-Exim-Connect-IP: <locally generated> X-SA-Exim-Mail-From: tytso@thunk.org X-SA-Exim-Scanned: No (on thunker.thunk.org); SAEximRunCond expanded to false On Fri, Dec 11, 2009 at 01:51:32PM -0500, Brad Spengler wrote: > I've also got two local DoS mm-related bugs to be fixed if you'd like to > take a look at them. They exist in all 64bit kernels since 2.6.26 or > so. The first is an easy fix (we've fixed it in grsec for some time), > but the other one requires some more thinking and decision making (it's > memory exhaustion that causes a complete lockup of the machine -- and > the OOM killer is unaware of the memory because it's not > associated/accounted for by any task). Sure, send them my way! - Ted 842 sF Dec 11 11:57AM To tytso@mit.ed ext4 bug 843 sF Dec 11 01:51PM To tytso@mit.ed └─> 844 sF Dec 11 05:34PM To tytso@mit.ed └─┬─> 845 sF Dec 11 05:40PM To tytso@mit.ed └─> To: tytso@mit.edu Subject: Re: ext4 bug [-- PGP output follows (current time: Thu 09 Sep 2010 07:33:02 PM EDT) --] gpg: Signature made Fri 11 Dec 2009 05:34:56 PM EST using DSA key ID 4245D46A gpg: Good signature from "Bradley Spengler (spender) <spender@grsecurity.net>" [-- End of PGP output --] [-- The following data is signed --] > Sure, send them my way! > > - Ted Ok, the second issue should be clear with the following PoC: (make sure to set your stack soft-limit to unlimited first, and compile it as 32bit, run on a 64bit machine) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define NUM_ARGS 9000 int main(void) { char **args; char *str; int i; str = malloc(128 * 1024); memset(str, 'A', 128 * 1024 - 1); str[128 * 1024 - 1] = '\0'; args = malloc(NUM_ARGS * sizeof(char *)); for (i = 0; i < (NUM_ARGS - 1); i++) args[i] = str; args[i] = NULL; execv("/bin/sh", args); printf("execve failed\n"); return 0; } It requires very little memory on the part of the program doing the exec, but then explodes in kernel-space as each 128KB arg is copied into its own allocation thousands of times. The system slows to the point of being unusable (or with the right arg amount, will halt the box from the problem below) Meanwhile, none of the processes involved in this will get killed by the OOM killer, as none of the memory is accounted for. (that's where the thinking comes in on how to properly fix it) first issue is fs/exec.c:shift_arg_pages() Using the PoC above, you can change NUM_ARGS such that instead of exhausting all memory and locking up the system, you cause the stack to expand down so far that it tries to wrap around the address space, triggering the BUG_ON(new_start > new_end) The reason this is possible on 64bit machines is because the resource check in get_arg_page: if (size > rlim[RLIMIT_STACK].rlim_cur / 4) allows stack sizes that are larger than the 32bit address space, as rlim_cur is a long, and the RLIM_INFINITY soft limit is being treated an actual size count, being both larger than the possible addressing on x86 and x64, even after being divided by 4. So by carefully choosing NUM_ARGS, you can cause the stack randomization present in the kernel to attempt to shift the arg pages down below the beginning of the address space, triggering the BUG. It can be made easier (depending on the amount of RAM on the machine) by using the 3G personality. [-- End of signed data --] [-- PGP output follows (current time: Thu 09 Sep 2010 07:33:33 PM EDT) --] gpg: Signature made Fri 11 Dec 2009 05:40:37 PM EST using DSA key ID 4245D46A gpg: Good signature from "Bradley Spengler (spender) <spender@grsecurity.net>" [-- End of PGP output --] Sorry, NUM_ARGS should be set larger -- around 24550 or so, to fill up the full 3GB. And the resource exhaustion works on 32bit, just the BUG_ON is only triggerable on 64bit machines. Another old security problem Posted Sep 10, 2010 20:23 UTC (Fri) by gregkh (subscriber, #8) [Link] That's sad, as security@kernel.org is the only group that will guarantee that we will look at the issue and work to resolve it in a quick manner. > Is it only a problem when the shoe's on the other foot? No, I was worried that something got reported to security@kernel.org that we did not respond to in a timely manner. If you notify random kernel developers, one of whom is not part of the kernel security team, then we can't guarantee any type of response. Which, sadly, seems to be the case here. Otherwise the problem would have been resolved a long time ago. In the future, it would be great if you could notify security@kernel.org about these types of problems so that they can be handled properly. thanks. Posted Sep 10, 2010 20:31 UTC (Fri) by Trelane (guest, #56877) [Link] since he was being responsive, chose to share some additional vulnerabilities with him. With the general upstream attitude and handling of security bugs, on principle I don't email vendor-sec or security@. Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/404372/
CC-MAIN-2013-48
refinedweb
1,038
62.27
README ¶ k8router This is a software project by SOSETH and VIS to manage several external load-balancers which forward traffic to several Kubernetes clusters. Externally expose kubernetes ingresses using HAProxy and terminate TLS for them. Problem Description Given a set of n Kubernetes clusters and m pairs of load-balancers to each of them, the goal of the project is to transport information about available domains in each cluster to all load-balancers such that any router is able to forward traffic any cluster. Open Tasks - Figure out why update/patch on the fake client set doesn't get propagated. This prevents us from writing more interesting unit tests... - systemd integration (instead of doing sudo systemctl ...) Prerequisites - HAProxy, installed and configured to use a conf.d-style configuration format. Have a look here for more information. - Kubernetes clusters and client configurations for a k8routeruser. - The user must be able to watch Ingresses in all namespaces in all clusters. See k8s-rbac.ymlfor more information. - Certificates for all your domains. sysctl net.ipv4.vs.conntrack = 1 - Source-NAT rule for the service IP subnet Each Kubernetes cluster has to expose its API to all the routers. Every kubelet node has to be accessible by all routers. Configuration An example configuration might look like this: haproxyDropinPath: /etc/haproxy/conf.d/90-k8router.conf haproxyTemplatePath: /root/template clusters: - name: local kubeconfig: /etc/k8router/k8s/kubeconfig.yml certificates: - cert: /foo name: realcert domains: - example.org - cert: /bar name: dummycert domains: - '*.org' - '*.com' ips: - 1.2.3.4 This will generate a configuration at /etc/haproxy/conf.d/90-k8router.conf from /root/template for one cluster ( /etc/k8router/k8s/kubeconfig.yml), using two certificates and one external IP. An example template file is included here, note that the certificates are specified as directories (see the HAProxy docs on this one). Running Execute ./k8router -verbose -config <path/to/config> in a terminal, the log output should tell you if something goes wrong. Due to missing systemd integration we still require passwordless sudo for the service user.
https://pkg.go.dev/github.com/vsk8s/k8router@v0.1.9
CC-MAIN-2021-43
refinedweb
341
51.34
dynamicSubstring – simplifying your substring logic Introduction A common mapping requirement that crops up every now and then is the requirement to extract a portion of data from a source field. This can be easily achieved with the standard function substring from the Text category. However, the substring function can only be configured with static start position and character count parameter values. If the input to the function is a dynamic content of variable length, it is possible to encounter the familiar “java.lang.StringIndexOutOfBoundsException: String index out of range” exception when the input is shorter than expected. Below are some common approaches to handle such scenarios: - Create a custom substring UDF based on java.lang.String’s substring method with arguments as input instead of parameters. - Create a mapping logic to determine length of input and reconstruct it prior to input of substring function. In this blog, I will share an alternative approach using a simple UDF named dynamicSubstring. The usage and configuration is similar to the standard substring function, however it will dynamically calculate the length of the input value so that the substring operation does not trigger the out of range exception. Source code The UDF is a Single Values execution type UDF, having 1 String input argument and 2 configurable parameters. @LibraryMethod(title="dynamicSubstring", description="Get substring of input", category="FL_TextPool", type=ExecutionType.SINGLE_VALUE) public String dynamicSubstring ( @Argument(title="Input String") String input, @Parameter(title="Start index") int start, @Parameter(title="Length of output") int length, Container container) throws StreamTransformationException{ // ---------------------------------------------------------- // Extracts the substring of an input String // ---------------------------------------------------------- // input - input string // start - position index for start of string // length - length of substring // ---------------------------------------------------------- int startPos = start; int endPos = start + length - 1; String output = ""; if ( startPos < 0 ) { // (1) Start position is before start of input, return empty string output = ""; } else if ( startPos >= 0 && startPos < input.length() ) { if ( endPos < input.length() ) { // (2) Start & end positions are before end of input, return the partial substring output = input.substring( startPos, endPos + 1 ); } else if ( endPos >= input.length() ) { // (3) Start position is before start of input but end position is after end of input, return from start till end of input output = input.substring( startPos, input.length() ); } } else if ( startPos >= input.length() ) { // (4) Start position is after end of input, return empty string output = ""; } return output; } Testing Results Scenario 1 Start position and end position is less than length of input. This scenario can be achieved by standard function without any exception. Scenario 2 The input value is now shorter that scenario 1 such that start position is less than input length, but the end position is more than input length. For standard function, this will cause an exception. However, for dynamicSubstring, it will just extract from the start position until the end of the input. Scenario 3 Finally, the input value has shortened significantly such that the start position is more than the input length. Again this will cause an exception with the standard function. However, for dynamicSubstring, it will just return an empty string. Conclusion With the usage of dynamicSubstring, we can now simplify mapping logic that involve substring operations on content that is variable in length. Good tips, thanks ! Hi Eng, A great way to work with substrings. Also, in the cases that you know the start and the end positions, it's possible to do it easily: imports java.lang.String; public String subStringDinamico(String a,String b,String c,Container container){ int inicio =0; int fin = 0; try { inicio=Integer.parseInt(a); fin = Integer.parseInt(b); } catch(NumberFormatException e) { } return (c.substring(inicio,fin)); } Although the exception could happen instead of your code that you avoid it. Regards. Hi Inaki Yes, my logic above are for the times when I don't care if the extracted length is less than the configured length - I just don't want to get any exception. By the way, for your logic above, you can simplify it further if you define the input arguments as integer directly so that you don't need to parse the string 🙂 Rgds Eng Swee Hi Eng, Good one, This is very common requirement when we work with substring function. Regards, Praveen. Hi Eng, A very common issue most of the consultants face while working with substring. Thanks for this Regards, Sriram Eng, Appreciate your effort to address a common requirement. Just for reader benefit, this can also be achieved using below UDF. Trim can be used to delete pre and post spaces, after substring. Hi Raghu Thanks for sharing the UDF. That would be something along the lines of the second point I mentioned in the Intro section above. It would however require 4 functions (including trim after substring) instead of a single function. Anyway, it's always good to have options available for comparison. 😉 Rgds Eng Swee Hi, great blog. Thanks. I called that UDF safeSubstring having one input and two integer Parameters instead of Arguments, as properties. Is there a way to get properties show like in the standard substring function, like on the image below?
https://blogs.sap.com/2015/03/24/dynamicsubstring-simplifying-your-substring-logic/
CC-MAIN-2021-43
refinedweb
841
54.63
For Day 19, the challenge is to follow a map, recording letters that are passed on the route. import time UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) with open("input.txt", "r") as o: m = o.readlines() y = 0 x = m[y].index("|") direction = DOWN path = [] steps = 0 def read(m, x, y): if len(m) <= y or len(m[y]) <= x: return " " return m[y][x] def peek(m, x, y, direction): x += direction[0] y += direction[1] return read(m, x, y) while True: if read(m, x, y).isalpha(): path.append(m[y][x]) elif read(m, x, y) == " ": break elif m[y][x] == "+" and peek(m, x, y, direction) == " ": # We need to turn if direction[0] == 0: # Moving up or down possible_directions = [LEFT, RIGHT] else: # Moving left or right possible_directions = [UP, DOWN] direction = None for d in possible_directions: if not peek(m, x, y, d) == " ": direction = d if not direction: print "Done" break x += direction[0] y += direction[1] steps += 1 print "Part 1", "".join(path) print "Part 2", steps Advent of Code runs every day up to Christmas, you should join in!. Get the latest posts delivered right to your inbox.
https://blog.jscott.me/advent-of-code-day-19/
CC-MAIN-2018-43
refinedweb
201
66.67
Perl offers three slightly different mechanisms for executing external commands: system($command, @arguments); # For example: system( "sh", "script.sh", "--help" ); system("sh script.sh --help"); [download] Read the documentation for system for the nuances of how various invocations are slightly different. This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more. my $output = `script.sh --option`; my $output = qx/script.sh --option/; [download] There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more. The way to do this is to use a systen call to run your script: system("script.sh"); [download] However I thought that I'd mention a couple of points to go with this. I like to do this sometimes ... my $shell_out = <<`SHELL`; for fs in `/sbin/fdisk -l | grep -v swap | grep Linux | cut -d ' ' -f1 +` do /sbin/e2label \$fs | grep recovery > /dev/null 2>&1 && echo "Y +ES" && exit 0 done echo "NO" exit 0 SHELL [download] A slightly longer version using the exec method with forked pipes (and an optional timeout value). # two parameters: # cmd - a command or reference to an array of command + arguments # timeout - number of seconds to wait (0 = forever) # returns: # cmd exit status (-1 if timed out) # cmd results (STDERR and STDOUT merged into an array ref) sub ExecCmd { my $cmd = shift || return(0, []); my $timeout = shift || 0; # opening a pipe creates a forked process my $pid = open(my $pipe, '-|'); return(-1, "Can't fork: $!") unless defined $pid; if ($pid) { # this code is running in the parent process my @result = (); if ($timeout) { my $failed = 1; eval { # set a signal to die if the timeout is reached local $SIG{ALRM} = sub { die "alarm\n" }; alarm $timeout; @result = <$pipe>; alarm 0; $failed = 0; }; return(-1, ['command timeout', @result]) if $failed; } else { @result = <$pipe>; } close($pipe); # return exit status, command output return ($? >> 8), \@result; } # this code is running in the forked child process { # skip warnings in this block no warnings; # redirect STDERR to STDOUT open(STDERR, '>&STDOUT'); # exec transfers control of the process # to the command ref($cmd) eq 'ARRAY' ? exec(@$cmd) : exec($cmd); } # this code will not execute unless exec fails! print "Can't exec @$cmd: $!"; exit 1; } [download] If );
http://www.perlmonks.org/index.pl/?node_id=78523
CC-MAIN-2015-48
refinedweb
386
59.74
Are you sure? This action might not be possible to undo. Are you sure you want to continue? Foundations of IBM Cloud Computing Architecture V1 Total Questions: 143 Question: 1. Which resources are typically provided by an Infrastructure as a Service cloud computing delivery model? A. applications B. virtual machines C. virtual private networks D. middleware software stacks Answer: B Question:. Answer: B Question: 3. Which concept aligns business and IT assets, helps provide flexible IT capacity, and provides real time allocation of IT resources in line with demand from business processes? A. elasticity B. virtualization C. dynamic infrastructure D. automated management of resources Answer: C Question: Answer: B Question:. Answer: AD Question: 6. What is one functionality of IBM Tivoli Service Automation Manager? A. software discovery B. business service monitoring C. virtual server provisioning D. out of the box cloud solution Answer: C Question: 7. A company is currently using IBM LotusLive and would like their mobile users to have access to the instant messaging feature. How can this be accomplished? A. Mobile users can install IBM LotusLive Engage on their mobile device. B. Mobile devices with a. Answer: B Question:. Answer: C Question: 9. A customer is struggling with inconsistent software builds in the testing and staging environment. Which cloud attribute can help resolve the problem? A. pervasiveness B. elastic scaling C. flexible pricing D. automatic provisioning Answer: D Question: Answer: A Question:. Private Cloud C. B. What advantage is there for an enterprise to adopt a virtual private cloud model? A. Answer: C . Which cloud computing model will satisfy all these requirements? A.D. Obtain maximum control over aspects such as security and performance since the entire infrastructure will be managed within the IT department. Answer: D Question: 12. Manage sensitive data in a compliant and secure manner and benefit from flexible pricing models for select services or infrastructure. A company wants to build a test environment to test software updates and new solutions. The company does not want to invest in infrastructure that may be idle for a significant amount of time. Public Cloud B. External Cloud D. Reduce infrastructure costs since all data centers will be managed in a third party cloud. Reduce costs by adopting a flexible pricing model for the entire operation. The environment should mirror the production environment and be secure and inaccessible from outside the company network. Virtual Private Cloud Answer: D Question: 13. C. An enterprise that does not want to sacrifice security or make changes to their management practices but needs additional resources for test and development of new solutions. D. public cloud C. chat. A company would like to leverage cloud computing to provide advanced collaboration services (i. C. Resources are dynamically provisioned on a self service basis from an off site third party provider who shares resources in a multitenanted infrastructure. private cloud D. B.e. It shifts the bulk of the costs from capital expenditures and IT infrastructure investment to an utility operating expense model. A company is considering a cloud environment to improve the operating efficiency for their data and applications. It shifts the bulk of the costs from capital expenditures to creating a virtualized and elastic infrastructure within the enterprise data center.Question: 14. E. The company is part of an industry where strict security and data privacy issues are of the highest importance. and web conferences) for its employees but does not have the IT resources to deploy such an infrastructure. Which two statements are true about the public cloud model? (Choose two. Which cloud computing model would best fit the company 抯 needs? . video.) A. Which type of cloud would be a good choice? A. Answer: CE Question: 16. D. hybrid cloud B. Resources and infrastructure are managed and maintained by the enterprise IT operations staff. It meets security and auditing requirements for highly regulated industries. governed cloud Answer: C Question: 15. Software as a Service C. Infrastructure as a Service Answer: B Question: 18. Private Cloud D. A company has decided to leverage the web conferencing services provided by a cloud provider and to pay for those services as they are used. Public Cloud C. D. Which statement best describes the Software as a Service cloud delivery model? A. B. Answer: D . An application delivered to the client from the cloud which eliminates the need to install and run the application on the customer's own computers and simplifying maintenance and support. The cloud provider manages the infrastructure and any application upgrades. and testing of industry aligned applications. Application as a Service D. A virtual machine provisioned and provided from the cloud which allows the customer to deploy custom applications. Platform as a Service B.A. A multitenant storage service provisioned from the cloud which allows the customer to leverage the cloud for storing software data. This is an example of what type of cloud delivery model? A. C. Hybrid Cloud B. Virtual Private Cloud Answer: B Question: 17. development. A solution stack or set of middleware delivered to the client from the cloud which provides services for the design. Answer: D Question: 21. A company is running out of storage space to store a customer database and dynamically requests additional space via the cloud provider 抯 web services interface. develops a custom application.Question: 19. A company requires more processing power to perform its financial analysis calculations and acquires additional computational resources. C. A cloud provider offers an environment for building applications that will run from the customer's environment. Software as a Service B. A company obtains an environment with a software stack from a cloud provider. Computing as a Service D. and makes that application available to its customers on the Internet. A company requires a customer relationship management solution and obtains an application that addresses their requirements from a cloud provider. D. B. Which cloud computing delivery model are they using? . Which delivery model is an example of a cloud computing environment that provides users with a web based email service? A. Platform as a Service C. How can a company leverage the Platform as a Service cloud computing delivery model? A. Infrastructure as a Service Answer: A Question: 20. Platform as a Service B. It provides the entire infrastructure along with a completed application that is accessible using a web based front end. It provides a runtime environment for applications and includes a set of basic services such as storage and databases. D. Development as a Service D. Which delivery model is an example of a cloud computing environment that provides users access to virtual machines? A. Which statement is true about the Platform as a Service cloud computing delivery model? A. Software as a Service C. Infrastructure as a Service Answer: D . Software as a Service C. B. It provides a virtual machine and storage so that computing platforms can be created. It is required by the infrastructure as a service delivery model so that end user applications can be delivered on the cloud. Platform as a Service B. Application as a Service D. Answer: B Question: 23. Infrastructure as a Service Answer: A Question: 22. C.A. It offers Software as a Service. Application Service Provider D. Internet Service Provider B. Which business type provides Software as a Service? A. . Platform as a Service B. Infrastructure as a Service Answer: D Question: 25.Question: 24. C. What is true about an application service provider? A. It offers access to the Internet. What type of cloud computing model fits these requirements? A. A company interested in cloud computing is looking for a provider who offers a set of basic services such as virtual server provisioning and ondemand storage that can be combined into a platform for deploying and running customized applications. B. Infrastructure Service Provider Answer: C Question: 26. Platform Service Provider C. Software as a Service C. Application as a Service D. It offers metered service to the customer. It delivers Infrastructure as a Service. It delivers Communications as a Service. What is true about grid computing? A. Answer: D Question: 29. C. Grid computing is a type of infrastructure as a service. D. B. Cluster computing is an example of grid computing. C. It is distributed computing where autonomous computers perform independent tasks. It offers a computer infrastructure service. Answer: A Question: 28. C. B.D. B. It is parallel and distributed computing where computer infrastructure is offered as a service. Cloud computing is an example of grid computing. What is true about an application service provider? A. It delivers Software as a Service. . What is grid computing? A. It is parallel computing where autonomous computers act together to perform very large tasks. Answer: A Question: 27. D. It is interconnected computing where a computing platform is delivered to consumers. It delivers Platform as a Service. Utility computing runs in a cloud computing environment. The tasks run on a computer using a peertopeer system. Answer: A Question: 32. B. C. C. What is true about utility computing and cloud computing? A. It is a service model where customers pay a flat rate for usage. Answer: C Question: 31. It delivers computing resource as a metered service. It is a computing model where computer resources are provided ondemand. Grid computing can run in a cloud computing environment.D. The tasks are small and independent. Utility computing is not related to cloud computing. D. D. B. What is true about the tasks running on grid computing? A. What is utility computing? A. B. Cloud computing can be delivered as utility computing. The tasks are divided among the computers. . Answer: D Question: 30. It is an organization that maintains the computer infrastructure for a public service. C. The tasks run on a single computer. Answer: D . Answer: B Question: 33. It improves server performance. It maximizes server utilization by implementing automated provisioning. There is no operational cost for a cloud computing environment. The resources can quickly move from one cloud environment to another. metering B. What is one benefit of cloud computing? A.D. It minimizes network traffic to the virtual machines. multitenancy D. security C. virtualization Answer: A Question: 34. B. D. A workload can quickly move to a cloud computing environment. C. What is one benefit of a cloud computing environment? A. It automatically transforms physical servers into virtual machines. D. Utility computing is the only billing model for cloud computing. C. Computer resources can be quickly provisioned. Answer: A Question: 35. Which computing feature is related to utility computing? A. B. C. patches are automatically installed on the clients. A public cloud provides the same level of security as a private cloud. It is compromised because it is a shared environment. Which statement is true about the security of the cloud computing environment? A. customers do not need to worry about installing patches in the virtual instances. C. In an Infrastructure as a Service (IaaS) environment. C. A cloud computing service can schedule a maintenance outage that affects the availability of the resources. Which statement is true about the reliability of a cloud computing solution? A. B. B. A public cloud is less reliable than a private cloud. patches are automatically installed on the clients. Access to critical data is better controlled in a private cloud environment. Answer: B Question: 37. D. Answer: D Question: 38. Which statement is true about the maintenance of a cloud computing environment? A. In a Software as a Service (SaaS) environment. Cloud computing improves the reliability through the use of multiple sites. Multitenant applications are not able to run in a cloud environment. B.Question: 36. . A hybrid cloud strategy represents the best approach for a reliable cloud computing environment. D. In a SaaS environment. It cannot be used to host location based applications.) A. higher costs C. customers do not need to worry about installing patches in the virtual instances. In an IaaS environment. Answer: B Question: 40. cost savings . Answer: B Question: 39. What are two common areas of concern often expressed by customers when proposing a multitenancy software solution compared to a singletenancy solution? (Choose two. less efficient use of computing resources Answer: AD Question: 41. B. data privacy B. complexity to customize solution E.D. C. greater network latency D. It can improve a web server response time by having servers closer to the end user. D. What is an advantage of a multitenancy cloud environment over a singletenancy environment? A. It introduces latency as the servers are geographically dispersed. Which statement is true about a cloud computing environment? A. It enables users to access systems regardless of their location. B. B. Answer: C Question: 44. C. and their computer systems do not have the computation capacity to perform this analysis. D. D. C. It adds extra load to the underlying physical infrastructure and has no role in cloud computing. B. It removes operating system inefficiencies. easy to customize C. It optimizes the utilization of computing resources. How can this analysis be completed quickly and cost effectively? . How can IT resource consolidation and virtualization help companies deliver services? A. It scales applications better than traditional clustering of application servers. It creates more maintenance work but virtualization makes it easy to scale applications. What is the role of virtualization in cloud computing? A. faster performance D. Answer: C Question: 43. higher data security Answer: A Question: 42. It allocates computing resources more efficiently and reduces maintenance costs. A company must perform a complex analysis for a client. It improves the performance of web applications. It reduces the network traffic. Which cloud computing feature allows for server consolidation resulting in increased asset utilization and decreased data center energy needs? A. The company would like to consolidate to reduce the number of total resources in their data center and decrease energy costs. B. Provisioning D. Virtualization Answer: D Question: 46. C. Order new hardware to boost computational power. Virtualization Answer: D . Elasticity C. Provisioning D. Virtualize existing hardware to extract efficiency and utilize the extra capacity. A company currently experiences 7 to 10 percent utilization of its development and test computing resources. Answer: D Question: 45. Temporarily access computational power on demand from a cloud service provider.A. Automation B. Governance C. Consolidate the existing hardware to find required computational capacity. Which feature of cloud computing allows resource consolidation? A. D. Automation B. resources are not as reliable as in cluster computing because cluster computing has redundant nodes for high availability. In cloud computing. Answer: B . summer months. C. The company does not need to do anything because they are already using server virtualization techniques. In cloud computing. The company already uses server virtualization techniques in order to consolidate the total number of required resources. D. A company operates data centers in two different regions. Answer: D Question: 48. resources are treated independently; in cluster computing. The company can further leverage virtualization to easily and quickly move as many assets from the data center in the warmer region to the data center in the cooler region during the summer season. computers work independently. In cloud computing. How might the company further reduce operating costs at this data center? A. resources are virtualized; in cluster computing. C. the resources are seen as a single system. B.Question: 47. The company can leverage provisioning to optimize the availability of their environments in the summer season. resources are running physically in a computer system. The company can shut down the data center in the summer season. Which statement is true about cluster computing and cloud computing? A. computers work together; in cluster computing. In cloud computing. Energy costs for one of the data centers increases during the warmer. B. D. . C. which scenario should be considered first? A. Which statement is true about sharing resources in a cloud computing and cluster computing environments? A. A cluster computing environment can be deployed in a cloud computing environment. D. B. An area where most of the approval can be delegated. D. File systems are normally shared in a cluster computing and cloud computing environment. An area where there is no documented approval process. Which statement is true about cloud computing and cluster computing? A. Answer: A Question: 51. Answer: C Question: 50. D. An area where the approval process can be automated. B. C. File systems are normally shared in a cluster computing environment but not in cloud computing environment. A cloud computing environment can be deployed in a cluster computing environment. C. An area where the approval process is complex. B. When implementing a cloud computing environment. File systems are not shared in cluster computing or cloud computing environments.Question: 49. File systems are normally shared in a cloud computing environment but not in a cluster computing environment. A cloud computing environment cannot be deployed without a cluster computing environment. A cluster computing environment cannot be deployed without a cloud computing environment. D. How is a business approval process related to a cloud computing environment? A. C. . Create a virtualized end user / client infrastructure. stores. Create a virtualized server infrastructure. It defines the access to a cloud computing resource. and protects data as part of its business. A cloud computing environment requires an expedited business approval process. B. D. B. D. Answer: D Question: 53. C. It defines the authorization process for a cloud computing implementation. It defines the responsibilities for the cloud computing environment. A business approval process is required to deploy a cloud computing environment.Answer: B Question: 52. A business approval process must be documented before implementing a cloud computing environment. If defines the authorization process for cloud computing provisioning. C. Create a virtualized information infrastructure. A company gathers. B. manages. Answer: C Question: 54. A cloud computing environment can be implemented without a business approval process. Why is a defined approval process important for a cloud computing implementation? A. Create a virtualized application infrastructure. How can it create business value from the data? A. centralization of resources Answer: BED Question: 56. which term is used to describe the nature of IT infrastructure and allows dynamic scaling depending on the demand for resources? A. product integration B. consolidation D. automated provisioning C.Answer: C Question: 55. In cloud computing. elasticity B. service standardization E. flexible infrastructure F. virtualization Answer: A . which three options provide a complete set of dynamic infrastructure capabilities? (Choose three. In addition to resource virtualization and consolidation.) A. clustering C. network virtualization D. Three times its original costs. Answer: A .Question: 57. D. A company has peak customer demand for its IT services in the month of April. Four times its original costs of deployment. Outsource all of IT services to a cloud based provider. Assuming that the company has deployed its system in a true cloud environment. A company that originally planned its web based IT system to support 10. Answer: C Question: 58. C. B. Acquire additional IT resources and design the system to handle the peak load. what are the incremental maintenance costs to adding new resources to this environment? A. Twice its original costs. B. Negligible. C.000 users suddenly notices that there is a four times increase in demand. It has enough IT resources to handle off peak demand but not peak load. Virtualize its servers and implement a cloud based system. D. What is the best approach to handle this situation? A. Utilize an external cloud service provider to handle the peak load. D.Question: 59. After a request for the new environment is approved. How does automation increase the effectiveness of an IT organization? A. It reduces the manual intervention needed for deploying and managing IT services. B. It provides usage monitoring and cost allocation capabilities. It reduces costs by increasing asset utilization. By provisioning the requested environment after the request approval without the need for manual intervention. C. Automation optimizes availability by maintaining configurations and managing changes to resources. What is the benefit of using automation techniques in conjunction with cloud computing? A. B. C. Automation reduces costs by increasing asset utilization. D. . D. By implementing an extension to the cloud environment. the provisioning process is manually initiated by a system administrator. By sending an alert to a system administrator indicating that an environment needs to be provisioned. B. Answer: A Question: 61. It optimizes availability by maintaining configurations and managing changes to resources. Automation allows for sharing of computer resources. Automation reduces human errors. C. By sending an alert to an approver indicating that a request needs attention. Answer: D Question: 60. How can the company use automation to improve this process? A. A company has implemented a cloud computing solution. It adds security constraints to a cloud environment. It reduces the number of application environments to set up. It reduces the complexity of the application environments. How can provisioning capabilities in a cloud computing solution improve setup efficiencies? A. D. B. Answer: D . What is the definition of provisioning as an automated process related to cloud computing? A. C. It provides server consolidation capability. It handles computing resource management processes. It allows the employees to reduce the number of managed servers. It moves data from one cloud to another. B. C.Answer: C Question: 62. It allows the employees to capture complex environments and set them up in a consistent manner. Application developers and testers are required to routinely setup complex multitiered application environments to complete their tasks. Answer: D Question: 63. D. C. It reduces the operating expenses by isolating the end users from the complexity of IT operations. It reduces the capital expenditures required for setting up the infrastructure. B.) A. B. It is easier to obtain a software instance in a cloud computing environment. Customers have access to the cloud services and infrastructure at anytime. . Answer: AD Question: 66. They provide customers with unlimited storage in the cloud. D. They enable customers to pay only for what they use. Flexible billing models enable customers to pay only for what they use. It reduces the number of environments the team must recreate. It reduces the amount of computer hardware used by the team. Product support professionals repeatedly create complex application environments in order to debug problems reported by customers.Question: 64. It helps the team identify bugs in the code. D. It allows the team to rapidly deploy complex application environments. D. C. How might provisioning in a cloud computing solution help the product support team's efficiency? A. B. Answer: D Question: 65. What advantage do flexible pricing models provide to customers of a public cloud? A. They provide customers with unlimited bandwidth. C. What are two ways a public cloud helps customers reduce their IT costs? (Choose two. They allow the customers to dynamically increase capacity without additional cost. E. A customer who deals with highly sensitive user information. A private cloud helps businesses reduce their cost in what two ways? (Choose two. A customer who is not too concerned about security control over their data. It reduces operating costs by having the internal IT department manage all the computing resources. Answer: C Question: 68. D. B. E. It reduces operating costs by having maximum control over the data and infrastructure. and the system load is almost a constant at all times. A customer whose IT infrastructure is underutilized. Answer: AD . A customer who does not have the IT infrastructure to handle variable system load. C. It reduces infrastructure cost by adopting virtualization techniques. B. C.) A. It reduces infrastructure cost by owning all of the computing resources. It reduces infrastructure cost by consolidating computing resources and distributed computing.Answer: B Question: 67. Which customer scenario best fits a deployment on a public cloud? A. D. A private cloud enables a business to reduce operating costs by using their own IT department to manage computing resources. and network by virtualizing resources to be more flexible. An enterprise can reduce the cost from capital expenditures and IT infrastructure investment to an utility operating expense model. B. D. An enterprise that is not too concerned about control over their data.Question: 69. C. An enterprise that manages sensitive data requiring maximum control and does not have enough infrastructure capacity to handle variable load. and the load on their systems is almost a constant at all times. What is an advantage of building a private cloud infrastructure? A. Answer: D Question: 70. Answer: D . A private cloud enables a business to reduce operating costs by having maximum control over the data and infrastructure. C. An enterprise can consolidate hardware. and meet on demand requirements. Which business scenario is best suited to maximize the benefits gained from using a private cloud? A. and the load on their systems is highly unpredictable. An enterprise that is focused primarily on short term projects. D. storage. An enterprise that manages sensitive data and the load on their systems is fairly consistent. B. dynamic. and the system load is highly unpredictable. It can manage sensitive data in a compliant and secure manner. An enterprise whose IT infrastructure is underutilized on average. Answer: D Question: 72. Answer: BD . It can have maximum control over aspects such as security and performance since the entire infrastructure will be managed within their own IT department. E. It can pool their existing infrastructure to be more flexible and increase their capacity for short term needs. A small start up business that is focused primarily on short term projects. B. An enterprise that is not too concerned about control over their data and has a large existing infrastructure that is capable of handling future needs. B. It can reduce their cost drastically since they will be adopting a flexible pricing model for their entire operations.Question: 71. and the system load is fairly consistent. D. What are two advantages of adopting a hybrid cloud model for an enterprise? (Choose two. An enterprise that needs highly controlled storage and access to their data and that has a large existing infrastructure but needs additional resources for test and development of new solutions. D. It can reduce their infrastructure cost since all their data centers will be managed in a third party cloud. C. Which scenario best illustrates the benefits of using a hybrid cloud? A. C. and benefit from flexible pricing models for select services or infrastructure.) A. What is a common trait of cloud architectures? A. Answer: D . single tiered B. synchronous web services D. C. terminal emulators C. What are two traits of a cloud computing architecture? (Choose two. single tiered B. What is a common design element often found in cloud architectures? A. asynchronous web services Answer: D Question: 75. not scalable C. ondemand access to resources D. B. D. It must use publicly accessible computing resources. internet/intranet accessible server E. While in operation the application automatically scales up or down based on resource needs.Question: 73. client and server run in the same physical environment Answer: CD Question: 74. A fixed set of computing resources is preallocated to each application.) A. It dictates monolithic application designs. metered C. subscription D. per user based Answer: A . computation and storage) and the amount of those resources used? A. metered B. resource based Answer: C Question: 77. Which billing model allows companies to have a predetermined and recurring costs for services used in a cloud environment? A. Which billing model is based on the packaging of computing resources (i. recurring C. subscription D. utility B.e.Question: 76. data C. recurring D. utility B. infrastructure B. application. platform. What are the components of a cloud computing environment? A. the company is able to easily increase the resources needed in the cloud environment. session. As the holiday season approaches.Question: 78. transport. network. platform. monthly C. the company is able to reduce the resource usage. application. application. infrastructure. presentation. application. server Answer: D . What type of cloud computing billing model is this company using? A. subscription Answer: A Question: 79. network. client. This allows the company to effectively manage the required computational resources and thereby reduce costs. When the season has ended. A company that provides gift giving advice has leveraged collaborative services in a cloud computing environment to provide on line chat between its employees and customers. client. data D. Network C. What is used to logically assign and separate physical resources such as memory and CPU in a cloud computing model? A. bios B. Client C. a load balancer D. a hypervisor C. Which two options are cloud computing architectural layers? (Choose two. Session D. Data B.) A. Infrastructure Answer: C Question: 82.Question: 80. Platform E. Application Answer: DE Question: 81. Software as a Service is considered to be included in which cloud computing layer? A. Data B. a blade chassis Answer: B . Application D. Question: 83. Answer: B . B. utility based B. D. software based D. What type of hypervisor provides the highest efficiency and performance? A. B. A public IP address for each instance that is connected to a virtual private bridge. Answer: D Question: 84. It requires a separate license for the native operating system. C. A private IP address for each instance that attaches to the OS software ethernet bridge. storage based C. It has minimum functionality to support only one type of operating system. A private IP address for each instance that is connected to a virtual private bridge. A public IP address for each instance that attaches to the OS software ethernet bridge. It runs directly on server hardware to provide virtual machines with timesharing resources. What is a common mechanism of communications among virtual machines running in a cloud environment? A. Which statement is true about a bare metal hypervisor? A. D. firmware based Answer: D Question: 85. It can only be hosted on an existing operating system. C. Not enough computing capacity during peak usage times. Running out of storage space and network bandwidth at peak usage times. The guest operating system gets a private IP and cannot talk to other guest operating systems. C. D. What are two common concerns in a cloud environment? (Choose two. can talk to other guest operating systems. Inability to use proxy servers and load balancers. and can access the Internet that the host machine can access. E. Answer: D Question: 87. they should not be able to read or modify each other's network traffic. B. Illegal access to private data stored by applications in the cloud.Question: 86. Answer: CE . B. and can access the Internet that the host machine can access. The guest operating system gets a public IP and can talk to the internet that the host machine can access. The guest operating system gets a private IP. D. C. If two guest instances are running on the same host or on different hosts connected to the same physical ethernet.) A. What is a characteristic of a guest operating system whose network is configured as a Virtual NAT device? A. The guest operating system gets a public IP. can talk to other guest operating systems. Trying it out in a staging environment. Trying it out directly in a production environment. B. D. Increased IT labor costs to manager the cloud environment. Answer: D Question: 89. Acquiring new servers to support virtualization. What are some challenges that existing data centers face as they move toward supporting cloud computing? A. certain network performance characteristics should be closely evaluated so that users are not negatively impacted. network packet loss rate D. Which approach is generally considered the easiest when beginning to adopt a cloud computing deployment model? A. network buffer overflow rate . C. Trying it out in a testing environment. data protection. Trying it out at the beginning of a new project. When building data center clouds.Question: 88. B. Storage capacity. Answer: A Question: 90. Greater energy consumption for the same load of applications. and storage provisioning as instances accumulate and scale up. network latency B. C.) A. What are the two most important characteristics that should be examined? (Choose two. network security C. D. The network should not connect more than a certain number of servers (reduce the number of servers). network servers B. The network should not include many layers of devices to create connectivity (reduce the number of switches/routers). What does the term "flat" mean? A. Data center clouds are formed by connecting two or more data center cloud networks over wide area network. When building such data center clouds.E. network routing information loss Answer: AC Question: 91. The network should not connect more than two clouds together (reduce the number of clouds connected). network routing protocols Answer: C Question: 92. which component is mainly responsible for increasing the network latency? A. The network should not connect more than a certain number of users (reduce the number of users). network interfaces D. When building data center clouds it is important to plan the network to be as flat as possible in order to reduce latency and packet loss. D. network clients C. B. Answer: D . C. C. The company should provide a command line interface. The company should provide a proprietary remote API. web browser D.Question: 93. AJAX C. PHP B. local client C. A large infrastructure as a service provider wants to allow users to provision new server capacity from a variety of different interface technologies. The company should provide an HTTP REST API. D. B. XHTML . How do users access Software as a Service cloud services? A. What is one technology used in client side browser code that queries back end systems for data from the cloud services? A. Answer: A Question: 94. Cloud service providers typically provide web based management consoles that provide users insight on the state of cloud services. command line Answer: C Question: 95. Which web technology should the service provider use to build an interface that users can leverage? A. thick client B. HTML D. The company should provide an XML RPC service. A company delivers Software as a Service that allows users to fill out and submit tax forms on line. The company is based in New York and operates its data center there. Build the system according to peak demand requirements. Build the system with high end hardware to ensure system performance. Design a robust load balancing architecture that monitors application performance and routes request to application instances appropriately.Answer: B Question: 96. Build a data center in New York and backup user data there. A cloud service provider wants to provide storage as a service to users. What should the company do to accommodate the spike in demand on the date when the tax forms are due? A. D. Answer: B Question: 97. C. Monitor the system and lease additional hardware during the peak tax season. What should the company do in order to ensure high availability for the storage services they provide? A. D. Build a data center in Chicago and backup user data there. B. Answer: D . Backup user data on removable media for offsite storage. Instruct users to keep their own backups for the information they store. B. C. Which company is likely to provide the highest availability? A. Company B stores user data in its primary data center in Chicago and replicates it to a data center in Atlanta. CPU Brand E. Company C D. Company D Answer: B Question: 99. Company C stores user data in its primary data center in Los Angeles and stores replicas in the same data center. Company B C. Company D stores user data in its primary data center in St Louis and does not replicate the data. CPU B. Which three input parameters are required when creating an instance of the IBM Smart Cloud for Development and Test? (Choose three. Location D.) A. Operating System Answer: AEF . MIPS C. Company A B. Storage Size F.Question: 98. Four different companies provide Storage as a Service capabilities: Company A stores user data in its primary data center in New York and replicates the data to a backup data center also in New York. What is the name of the public cloud offering from IBM Rational? A.Question: 100. IBM Smart Business Development and Test on the IBM Cloud D. IBM Tivoli Storage Manager B. Credit Card C. IBM Tivoli Business Service Manager C. IBM Rational Monthly SaaS B. IBM Rational Public Cloud C. Bring Your Own Answer: D Question: 101. Utility B. IBM Tivoli for Operating System Deployment D. IBM Tivoli Provisioning Manager for Images Answer: D . Which licensing model is supported for the IBM Smart Business Development and Test Cloud? A. Which Tivoli product migrates an operating system replica from RedHat KVM to VMware? A. IBM Rational Collaborative Application Lifecycle Management Cloud Answer: C Question: 102. Monthly Billing D. Question: 103. It clones WebSphere topologies across an enterprise. B. IBM CloudBurst B. IBM CloudBurst B. IBM Cloud Services Lifecycle Management D. What is the main purpose of an IBM CloudBurst solution? A. The IBM Smart Business Development and Test Cloud D. Answer: A Question: 104. The IBM Smart Business Development and Test on the IBM Cloud Answer: C . IBM CloudBurst for Development and Test C. IBM Service Management Center for Cloud Computing Answer: D Question: 105. D. Which IBM Cloud solution is differentiated by its focus on automating existing processes to increase efficiencies in enterprise data centers? A. C. It provides an out of the box cloud solution. IBM Smart Business Storage Cloud C. What would be used to satisfy a requirement for an on premises cloud installation? A. It provides the software base to build a cloud solution. It provides a feature to deploy IBM WebSphere Application Servers topologies in a cloud environment. deployment. applications. However. A smaller independent web software development company with minimal IT staff wants a "cloud in a box" that can reuse assets between development and test depending on their own internal development cycle needs. IBM CloudBurst B. IBM Service Management Center for Cloud Computing D.Question: 106. Which option should the company choose? A. test. A client wants to automate the on site design. and management of services such as middleware containers. IBM Smart Business Development and Test Cloud D. Which option would fit the client's requirement? A. IBM Server and Application Provisioning and Release Management Answer: A . hardware. and production. IBM Tivoli Service Automation Manager C. IBM Service Management Center for Cloud Computing Answer: B Question: 107. IBM WebSphere CloudBurst Appliance B. they want to keep the code inhouse at all times. IBM Implementation Services for Cloud Computing C. and networks from existing assets for development. Which product helps manage software license and compliance risk? A. IBM Informix Dynamic Server D. IBM Tivoli Asset Management for IT C. Which IBM database server offering is best suited for this client scenario? A. and high availability solutions. IBM Tivoli Service Automation Manager D. low cost. They want a reliable. IBM Service Management Center for Cloud Computing Answer: B Question: 109. IBM InfoSphere Information Server Answer: C . near hands free administration. IBM Lotus Domino Server B. A small business is experiencing a significant increase in their data and it is putting a strain on their infrastructure.Question: 108. IBM InfoSphere DataStage C. IBM CloudBurst B. full function data server that delivers the highest OLTP performance. They are concerned about their ability to meet the demand without significant capital expenditures so they are considering a low cost cloud solution. What benefits can be achieved by a small business adopting a cloud based solution with IBM Informix Dynamic Server? A. It will enable data integration from disparate sources and deliver trusted and complete information at the time it is required and in the format it is needed. IBM Lotus Domino Server B. mainframe. IBM DB2 Enterprise Server C. and application migrations. B. It will enable reporting. A large organization is considering a data integration project that will last six months. and integrate the data across diverse sources (structured. full function data server that delivers the highest OLTP performance and near hands free administration. Answer: B Question: 111. and application sources) to deliver trusted information. Which IBM database server offering is best suited for this client scenario? A. cleanse. D. They are looking for a solution that will enable them to derive value from the complex information spread across their systems. SOA.Question: 110. It will provide a low cost. and scorecarding on a single service oriented architecture. The solution should profile. unstructured. C. eBusiness. dashboarding. IBM InfoSphere Information Server Answer: D . MDM. It will enable capture and delivery of changed data from heterogeneous systems to support warehousing. analysis. IBM Informix Dynamic Server D. IBM InfoSphere Information Server C. dashboards. eBusiness. It will enable them to use reports. D. This will enable them to manage conflicting priorities. The solution should help them bring together all of their data assets across the organization via reports. IBM Cognos 8 Business Intelligence Answer: D Question: 113. and performance management in order to make quick decisions. analysis. scorecards. SOA. the workforce. IBM InfoSphere Replication Server D. It will provide a powerful document management system with ready to use workflow and process capabilities to automate and drive their content related tasks and activities. It will enable them to capture and deliver changed data from heterogeneous systems to support warehousing. and scorecards to identify and analyze trends and to respond to consumer buying needs and behaviors. It will provide a low cost. An insurance company wants to build a business analytics solution in the cloud.Question: 112. They need a comprehensive view across claims. full function data server that delivers the highest OLTP performance and near hands free administration. maximize operational efficiency. IBM FileNet Content Manager B. and application migrations. and manage growth and product offerings. What benefit can a retail organization gain by adopting a cloud based solution with IBM Cognos 8 Business Intelligence? A. and budgets. B. Which IBM offering is best suited for this client scenario? A. analysis. plans. Answer: C . MDM. C. tackle compliance issues quickly. customer service. C. and summary/reports through multiple browsers and platforms. Answer: D Question: 115. IBM Smart Business Cloud Conferences Answer: A . IBM Lotus Sametime Meetings D. A small telecommunications company looking for a data server solution in the public cloud to deliver performance across multiple workloads. With hardware and software deeply integrated and optimized. IBM LotusLive Events B. IBM Lotus Connections C. Which business scenario is best suited to maximize the benefits gained from using the IBM Smart Analytics System? A. A retail chain that currently has a data warehouse implemented in a virtual private cloud and is looking to add predictive capabilities to uncover consumer buying trends. A government agency looking for a powerful document management system with ready to use workflow and process capabilities to automate their content related tasks. The system is designed to ensure quick implementation with rapid delivery of value. the company is looking for automated email announcements. The IBM Smart Analytics System is an integrated platform that provides broad analytics capabilities on a powerful warehouse foundation with IBM server and storage. IBM Smart Analytics System provides a single point of support for end to end analytics solutions. registration management. B. In addition to web conference services. A health insurance company looking to build a private cloud with predictive capabilities in order to provide insight on plan members and therefore reducing risk and improving efficiency. A company would like to perform a product launch virtually in order to reach a larger audience and save costs. Which IBM offering can meet the needs of this company? A.Question: 114. D. participant rosters. They have a limited budget and cannot afford a hosted email solution. IBM Lotus Sametime B. IBM Lotus Web Conferences Answer: B . Which IBM offering would best meet their needs? A. IBM LotusLive Connections Answer: B Question: 117. the company does not want to incur the expense of deploying and managing an onsite infrastructure but would like to leverage the services offered by the cloud. Which IBM cloud services would best meet their needs without having to hire IT staff to manage and maintain the infrastructure? A. A company with less than 50 employees is looking for a web based email service that provides essential messaging and calendaring capabilities. IBM LotusLive Meetings C. In order to save time and reduce travel costs. IBM LotusLive Connections D. a company is looking for a way to host virtual customer meetings. Features such as video casting. desktop sharing. Because the goal is to reduce cost.Question: 116. IBM LotusLive iNotes C. and polling are important. IBM LotusLive Web Email D. IBM Lotus Notes B. IBM Rational Requirements Composer Answer: BDF . Email can be pushed to devices usingIMAP IDLE.Question: 118. Email can be pushed to devices using POP3 interfaces. IBM Rational Software Architect F. D. Which statement accurately describes how mobile devices are supported by the IBM LotusLive iNotes cloud offering? A. IBM Rational Team Concert C. Email can be pushed to devices using SMTP. Answer: C Question: 119. B. Email can be accessed using the SOAP interface. IBM Rational ClearCase B. IBM Smart Business Cloud Answer: B Question: 120.) A. IBM Rational Quality Manager E. Which three products are built on the IBM Rational Jazz platform? (Choose three. C. IBM Lotus Connections D. IBM LotusLive Mobile C. IBM Storage Cloud B. Which offering supports sharing files and participating in web meetings from a smart phone device? A. IBM Rational Requisite Pro D. Rational ClearQuest B. Rational Requirements Manager Answer: BCF .) A. Rational Software Modeler E.Question: 121. Web User Interfaces D. Which two architectural features make the IBM Rational Jazz platform well suited for the IBM Smart Business Development and Test Cloud? (Choose two. Rational Quality Manager D.) A. Rational Team Concert C. RESTful web services E. Eclipse Modeling Framework Answer: CD Question: 122. Which three tools are included in the IBM Rational Jazz Collaborative Application Lifecycle Management (C/ALM) solution? (Choose three. TCP/IP B. SOAP Services C. Rational Software Architect F. Answer: DE . IBM Smart Business Development and Test Cloud Answer: D Question: 124. D. Improves quality through more accurate configurations and enhanced modeling. E. C. designs. plans. IBM Tivoli Provisioning Manager B.Question: 123. and implements a dynamically scalable virtualized development and testing private cloud environment? A.) A. What are two advantages of using the IBM Smart Business Development and Test Cloud? (Choose two. IBM WebSphere Cloudburst Appliance C. B. Assists in reducing capital and licensing expenses as much as 50 to 75 percent using virtualized resources. Requires 35 to 45 percent less training than in house development. No licensed software required. Which IBM offering evaluates. IBM Tivoli Service Automation Manager D. Reduces short term software costs. IBM WebSphere Application Developer. The IBM Smart Business Development and Test Cloud is used to evaluate. plan. IBM Rational BuildForge C. Answer: C . B. IBM WebSphere CloudBurst Appliance B. A static development and testing cloud environment. It provides an automated workflow engine for IBM WebSphere Process Server. B. IBM WebSphere Integration Developer. design. D.Question: 125. A dynamically scalable virtualized development and testing cloud environment. A dynamically scalable virtualized runtime cloud environment. and implement what type of environment? A. IBM WebSphere CloudBurst Appliance D. It automates the error prone manual application environment build process. Which IBM products are included in the IBM Rational Automation Framework for WebSphere? A. C. It helps automate key line of business processes. It provides an automated framework for writing cloudbased applications. IBM Rational Team Concert. Answer: D Question: 126. C. IBM Rational BuildForge. D. A static runtime cloud environment. What key challenge does IBM Rational Automation Framework for WebSphere help solve? A. IBM Rational Team Concert Answer: A Question: 127. D. It allows geographically distributed work forces to utilize higher levels of collaboration. It allows the architect to model complex topologies using WCA.Question: 128. What is one advantage of adding IBM Rational BuildForge to the IBM WebSphere CloudBurst Appliance (WCA) in the IBM Rational Automation Framework offering? A. B. It allows the application to become more loosely coupled from the WCA pattern by allowing IBM Rational BuildForge to handle application building. Answer: D Question: 129. Answer: C . C. D. C. How can a running application called b illing b e found in a 200 server virtual environment? A. Look at the hypervisor management console. Request an application report from IBM Tivoli Usage and Accounting Manager. Use IBM Rational Asset Manager. Use IBM Tivoli Application Dependency Discovery Manager. It creates higher quality applications by more tightly integrating IBM Rational BuildForge and WCA. B. Answer: C Question: 132. A hypervisor and a hypervisor manager like Virtual Center or VMControl. a hypervisor manager. and monitoring. C. A hypervisor. Use IBM Tivoli Usage and Accounting Manager to collect the metrics for the resources and produce report based on the application. What are the common set of technologies used to create a manageable cloud environment? A. automated provisioning. A hypervisor platform built by IBM that comes with IBM WebSphere Application Server Network Deployment. How can resources used by an application running in a shared virtual environment be measured? A. . What is IBM WebSphere Application Server Hypervisor Edition? A.Question: 130. Each machine receives equal resources in the environment. and an automated provisioning tool like IBM Tivoli Provisioning Manager. a hypervisor manager. a hypervisor manager. D. Use IBM Tivoli Monitoring to calculate the usage based on CPU utilization. C. self service portal. automated provisioning. C. B. A hypervisor. B. and monitoring. D. A hypervisor. B. a self service portal. A single virtual image that contains IBM WebSphere Application Server and IBM Tivoli Provisioning Manager. Use the hypervisor management console. A bare metal hypervisor platform built by IBM. Answer: D Question: 131. IBM WebSphere Application Server C. Which virtualization standard does the WebSphere Application Server Hypervisor Edition use? A. IBM WebSphere MQ B. Open Virtualization Format D. the IBM HTTP Server. and the IBM WebSphere Application Server. Development and test teams spend a lot of time constructing and deploying WebSphere application environments and their computer resources are heavily underutilized. A single virtual image that contains an operating system. Common Image Format B. IBM WebSphere CloudBurst Appliance E.) A. Open Virtual Appliance C. IBM WebSphere Application Server Hypervisor Edition Answer: DE Question: 134. Answer: D Question: 133. IBM WebSphere DataPower Appliance D. Interoperable Image Format Answer: C . Which two solutions can decrease time spent building and deploying environments while increasing asset utilization? (Choose two.D. Implement a TPM device driver to support the custom device. A business workflow is needed to operate in a TPM environment. How are custom devices supported using IBM Tivoli Provisioning Manager (TPM)? A. configuration. D. What is one functionality of IBM Tivoli Provisioning Manager? A. TPM requires multiple reviewers and approvers to execute the workflow. It schedules data center resources. It provides provisioning for all network switches. Answer: A . D. C. C. Answer: D Question: 137. C. and operation of a data center resource. Open the TPM product code and insert the device support logic into TPM code base. TPM workflow is used to automate business decision workflow processes.Question: 135. B. TPM workflow is used to automate the installation. It provides the capability to reserve hardware resources. B. What is the difference between an IBM Tivoli Provisioning Manager (TPM) workflow and a business workflow? A. B. Answer: C Question: 136. It activates and installs appropriate software images. Use industry standard commands to interact with the device. D. Use a logical device operation which automatically selects the most recent driver for all devices. Out of the box reports for privileged user management. Desktop compliance enforcement for cloud users. D. D. Access control to cloud resources. B. Management of cloud subscriber log files. antivirus support B. Federated single sign on to cloud resources. C. Answer: B Question: 139. What functionality is provided by the IBM Security Network Intrusion Prevention System Virtual Appliance for a cloud environment? A. network level IDS/IPS C. Support for custom authentication to cloud resources. host and network level intrusion detection and prevention . Answer: D Question: 140. B. What is the value of IBM Security Information and Event Manager in a cloud provider environment? A. Out of the box SOX compliance. Which functionality is provided by an IBM Security Federated Identity Manager deployment in a cloud provider environment? A.Question: 138. C. Compliance enforcement for access to cloud resources. host level IDS/IPS and antivirus support D. It manages data into storage tiers enabling multitenancy of data. It delivers cloud charge back and billing services. It provides a client portal for provisioning of storage. IBM's storage cloud offering that maps business applications to specific storage devices in the cloud. . Which statement best describes the IBM Smart Business Storage Cloud offering? A. IBM's storage cloud offering provides a fixed block of storage to cloud applications. What is the IBM Smart Business Storage Cloud? A. C. It provides end to end management of heterogeneous storage environments. What value does IBM Tivoli Storage Productivity Center provide for administering cloud services environments? A. Answer: A Question: 143. Automated data tiering and information life cycle management is available in the IBM Storage Cloud. D. B. B. The performance of the IBM Storage Cloud is limited only by the performance of its fastest disk.Answer: D Question: 141. C. B. D. Answer: D Question: 142. IBM's storage cloud offering that dynamically provisions block storage to cloud applications. IBM's storage cloud offering based on Scale Out NAS technology. The performance of backups and file system scanning of the IBM Storage Cloud degrades significantly for very large systems due to long file system scan times. D.C. Answer: C . The IBM Storage Cloud offers extreme performance and scalability and supports an unlimited storage under a single global namespace.
https://de.scribd.com/document/89907645/Dumps-Questions-000-032
CC-MAIN-2017-43
refinedweb
8,982
52.56
At the top of the HTML hierarchy stands Steven Pemberton, chair of the HTML working group of the World Wide Web Consortium (W3C). A lover of language, a writer, and an editor, as well as an organizer and a leader in the web community, he has had both subtle and profound influences over the Web, not only in HTML standards, but in concepts that permeate the Web. He has been at the center of the forces that have been guiding the Web for over a decade. I recently had the pleasure of speaking with him at his home in Amsterdam by telephone. Steven Pemberton was born in England, in the county of Surrey, in the village of Ash, about 30 miles southwest of London. He grew up in St. Albans, about 20 miles north of London. "It was originally a Roman city called Verulamium, so there are a lot of Roman ruins around, a lot of history. I went to St. Albans School; it was founded in 948 a.d.," reminisces Pemberton. He went to university at the University of Sussex, which is located on the south coast of England in Brighton and studied electronics. When he went to college, "you couldn't mix. You either had to go with the arts or with the sciences. I would have liked to have done some languages, as well," says Pemberton. Instead, over the years he studied languages on his own, as a personal interest. "I'm fascinated by languages, that's for sure," admits Pemberton. "I speak French, Dutch, and English and all fairly well and some smatterings of other languages." His interest in languages effected his career and how he approached his work in favorable ways. In 1993, Pemberton became editor of the bulletin for SIGCHI (Special Interest Group for Computers and Human Interactions). As editor, he wrote editorial essays: "I wrote those pieces on the last page, sort of opinion pieces." His editorial column, Views and Feelings, ran for five years. He reincarnated the column when he became editor for Interactions. The new column, Reflections, is still running. These published musings of his are very interesting commentaries, many dealing with linguistics and computational linguistics. Pemberton has also co-authored a couple books, one entitled Pascal Implementations: The P4 Compiler and Interpreter (Ellis Horwood 1982), "which to my great pleasure was translated into Japanese," boasts Pemberton. "I've recently put that book on the Web in its entirety and it's turned out to be quite popular." His other book was The ABC Programmer's Handbook (Prentice-Hall 1990). It's on the programming language ABC, which Pemberton was instrumental in creating. "ABC was designed to be easy to learn and easy to use," explains Pemberton. "Initially, we started off creating it as a beginner language, something like the language BASIC, but much more powerful." Actually, it was useful to programmers of all levels. "It still has a small user base, but the reason ABC is famous is because it formed a basis for Python. I certainly use it all the time, but then I would," confesses Pemberton. This root of Python, the language ABC and its development into an interface called Views, can be said to be one of the conceptual roots of the Web. "While we were designing ABC we came across many generalized features that we realized could be applied not only to a programming environment, but also to a computer environment. We ended by incorporating them into the Views system, which if you'd see it now, you'd say it's a browser. That's not how we classified it then. We saw it as more of an applications environment. If you put it in terms of today, it has an extensible markup language, style sheets, client-side scripting, and a DOM," Pemberton points out. What's fascinating about Views as an application environment is that in the late 1980's, Pemberton had an understanding of what the browser could be that most would not realize until a decade later as an interface to web services. He says, "Much of what we're doing now with the Web, we were doing more than ten years ago with the Views system, except not over TCP/IP." I suspect that his notion of the browser, and his role as a leader in HTML, has shaped our concept of web applications. Besides being a software developer, Pemberton is also a systems researcher. Both publications he edited were about the study of computer and human interactions. In his employment with the W3C, he conducts meetings and research into web standards and usage. For his other employer, CWI (Centrum voor Wiskunde en Informatica), he's a researcher. "All of my research comes from the viewpoint of how to make systems easier to use," says Pemberton. "I'm very interested in usability and I apply that to the Web. It's also part of the design of HTML: you not only have the authors of documents -- you want usability for them -- but also the underlying architecture must support usability so that it shows through to the end-user, the person doing the browsing." Before the W3C, when CERN was responsible for HTML, Pemberton organized two workshops at the first conference about the Web. Eventually, he says, "it became clear that the people at CERN were going to MIT to form the World Wide Web Consortium. We were worried that it would leave Europe a bit lost of a center to organize around the Web. So in order to keep research activities going in Europe we organized the World Wide Web Working Group (W4G) within ERCIM, the European Research Consortium for Informatics and Mathematics (which is now the W3C European host)." He chaired the W4G for a few years and eventually became involved in W3C, as well. "I chaired the first W3C event, which was the first style sheet workshop," recalls Pemberton. "Out of that was born W3C's CSS working group, of which I became a member." In that role, he was one of the co-authors of CSS1 and CSS2. Since the CSS and the HTML working groups met in the same location, back-to-back, so that member representatives could attend both sessions, Pemberton joined the HTML working group and helped to develop HTML 4, and in time became its chair. Because of the growth of XML and the deferring of styling to CSS, it was determined that HTML would mature no further than HTML 4. "When we published HTML 4, the group was then basically closed. Six months later, though, when XML was up and running, people came up with the idea that maybe there should be an XML version of HTML," says Pemberton. Therefore, he was asked to conduct a workshop on the future of HTML and how it might relate to XML. He recalls that "it was a successful workshop where there were clear directions that the participants felt that HTML should take: XML had something to offer HTML and HTML had something to offer XML." Consequently, the HTML working group was reformed, with Pemberton as chair, to develop XHTML, XML compliant HTML. Inevitably, forms activities was spun off into a separate working group. "The members who were only interested in forms, were coming to HTML working group meetings, spending days doing nothing of interest to them," explains Pemberton. He became chair of the Forms working group, too. For some, the reason for XHTML may not be apparent. Pemberton says, "The point in the first place was to create a new version of HTML that would be as close as possible to HTML 4, but expressed in XML. We took the existing definition of HTML and made the minimal number of changes to make it good XML." This may seem persnickety, but they had immediate and future objectives. "The initial advantages were very small," Pemberton says, "but we knew there would be greater future advantages. It would mean that you would be able to combine XHTML with other things and get something sensible out of it. We're just seeing that happening now with browsers." It takes time to decide on standards and for browser vendors to adapt. "We have a time-line of about four-to-five years. When we produced XHTML in 1999, many people didn't see the point. It didn't actually give you any new functionality at that moment, but we knew it would in the future. Now, there are browsers that allow you to combine XHTML and SVG in a single document, for instance. This was part of the expected design, that once browsers started recognizing different namespaces, they would start processing combinations of those namespaces in a principal way. The theory was to create an XML version of HTML so that when the technology caught up with us, as it were, you could start doing extensible and interesting things with it." "It was a way of giving people a chance to use XML," he adds, "sort of a step over the line, before XML really had reached a critical mass." As for XHTML 2.0, Pemberton says, "The second step, now that we've got an XML version, is to take what we have and to clean it up, identify problems of the old HTML, create fixes for those problems, more usability, accessibility, internationalization, device independence, and to add new functionality that people have been looking for, that they need and have been doing up to now with scripting." This includes functionality like XForms that allows more possibilities on the client side. The working draft for XHTML 2.0, incidentally, is available. Pemberton says that he hopes for a "last call" this summer. In closing, I asked Pemberton for his thoughts about the future of HTML: "XHTML is now being implemented, and implemented well, in many different browsers, and popping up in lots of unexpected places like cellular telephones, televisions, refrigerators and printers. In some ways an impediment to the full adoption of XHTML is IE (Microsoft Internet Explorer), since its HTML and XML engines are not well integrated. However, there there are some things coming up that make me think IE will evolve into a shell that won't be doing much processing itself. It'll just be a way of combining different markup languages via plugins," says Pemberton. As for the Web itself, he says, "I think that we're only at the early stages of the development of the Web. In a sense, it has disappointed me that it has gone so slowly, but I've learned to live with that slow movement. I believe there are some advantages to it in that people are reviewing these things and we're getting a lot of community buy-in of what's being done." With leaders like Steven Pemberton, I agree that we are probably in the early stages of the Web and can expect to see spectacular developments in time. © , O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.xml.com/pub/a/2003/05/21/pemberton.html
CC-MAIN-2015-06
refinedweb
1,860
61.36
SVFS allows to create virtual filesystem inside file on real filesystem. It can be used to store multiple files inside single file (with directory structure). Unlike archives, SVFS allows to modify files in-place. SVFS files use file-like interface, so they can be used (pretty much) like regular Python file objects. Finally, it’s implemented in pure python and doesn’t use any 3rd party modules, so it should be very portable. Tests show write speed to be around 10-12 MB/s and read speed to be around 26-28 MB/s. Following code creates SVFS, opens file in it, writes string and reads it back: from SVFS import SVFS #Import SVFS class s = SVFS() #Create instance of SVFS class s.CreateSVFS('test.svfs','testvolume',100,100,100) #Create SVFS with 100 inodes and 100 blocks of 100 bytes. s.OpenSVFS('test.svfs') #Open created SVFS with s.open('testfile','w') as file: #Create and open new file for writing in SVFS. file.write('write test') #Write string into file t = s.open('testfile','r') #Open same file for reading print t.read() #Read entire file and print data t.close() #Close file s.CloseSVFS() #Close SVFS That code outputs: write test Which means it works correctly. Version 2.0.0: Initial release This module is maintained by Andrew Stolberg <andrewstolberg@gmail.com>. If you have any questions or want to help, email.
https://pypi.org/project/SVFS/
CC-MAIN-2016-44
refinedweb
235
76.32
Technical Articles Building an SAP Conversational AI Chatbot that Integrates with Qualtrics and SAP Customer Experience (2/4) Hello again and welcome to part 2/4 of the blog series “Building an SAP Conversational AI chatbot that integrates with Qualtrics and SAP Customer Experience“. Building the SAP Conversational AI Chatbot In this part, we are going to create and train our chatbot. In addition to that, you will find useful tips in the appendices, e.g. on debugging the chatbot and creating custom entities. So, without further ado, let’s dive right into it. First, let’s log on to the SAP Conversational AI platform at cai.tools.sap and click on the button, +NEW BOT. 2.1 SAP Conversational AI bot creation wizard, Step 1-2 In step 3, we are going to give our chatbot a unique name along with a description. This step also allows you to further categorize the chatbot into topics that will help with training the bot. The default language selected for the chatbot is ‘English’. Let’s leave it as is. 2.2 SAP Conversational AI bot creation wizard, Step 3 In step 4, we will choose the data type option as ‘Personal’ since the end users would be sharing email ids as well as order details in the chat. Hero bot would not be used by children or adults-at-risk so we can choose the end-user type as ‘Non-vulnerable’. Finally, in step 5, we can set the visibility of the bot to ‘Private’, making sure it is not visible to everyone on the SAP Conversational AI platform. All these options could be easily modified later on, if the need be. 2.3 SAP Conversational AI bot creation wizard, Step 4-5 Click ‘Create a bot’ to complete the wizard. The bot will get created with the selected skills redirecting us to the ‘Train’ tab. We will see a notification stating the chatbot training is currently running. 2.4 Chatbot Train Tab Once the training is finished, we will see a notification along with a timestamp. On the Train tab, we can see a list of intents, automatically created by the bot creation wizard. An intent, from Natural Language Processing (NLP), is an idea that is understandable by the bot. In SAP Conversational AI, it is represented by the name of the intent preceded with an @ sign. If we navigate to the intent @greetings, we will see a list of expressions that could be regarded as a greeting. 2.5 Chatbot skill @greetings We are now going to add a custom intent, specific to our use-case. Staying on the Train tab, navigate to the sub-tab Intent and click on the button + CREATE to add a new intent, @orderinquiry and navigate to the intent. Click inside the input field Add an Expression and create an expression ‘I did not receive my order yet’ and press enter to add it to the list of expressions. A similar expression that we can add to the list could be ‘My order is not here yet’ and/or ‘where is my order?’ and so on. You can also use a CSV file to import a list of expressions to be included inside an intent. Once done, press the Train button on the top of the screen to update the chatbot to understand the latest intent/expressions. Intents could be forked from other bots or intents. Based on the entered expressions, similar expressions are automatically suggested for you to add to the list. Subsequently, we are going to add the following intents: @createticket, @yessurvey, @nosurveyorticket. Expressions include keywords called entities. There are gold entities that are automatically determined by the SAP Conversational AI platform when a certain keyword qualifies for the description of that entity. For example, any email address is automatically classified as an email gold entity. Like gold entities, it is also possible to create custom entities for special keywords. For example, product names in SAP Commerce Cloud site could be imported into a custom entity (let’s call it CCB2BProduct) and whenever the product name is found to be part of a conversation the entity is recognized and could be used to trigger a specific action (skill). We are going to create a custom entity in a later step. First, let’s add a skill to our chatbot. Adding New Skills When we created our chatbot, some of the skills were automatically created by the SAP Conversational AI platform. Navigating to the Build tab, we can already see greetings, small-talk and a fallback skill. Let’s now add a skill (+ Create skill button) that would get triggered whenever the chatbot receives an expression matching the @orderinquiry intent. 2.6 Create a new skill Once created, navigate to the skill and go to the Triggers tab. For this skill to trigger, an order inquiry needs to be present in the conversation. We already created the orderinquiry intent for this purpose in a previous step. Click the input field next to If to get autosuggested lists of values that can possibly go into the operand part of the condition. 2.7 Skill Trigger Tab Under the User says, we will choose @orderinquiry and press Save. Once done, we would need to choose an operator (is-present) from the autosuggest list. 2.8 Skill Trigger Condition – Operators Once the trigger is defined, the next step would be to perform an action. (We will come back to the Requirements tab in a later step). There are multiple possibilities when it comes to creating actions inside a skill. You can send a message, make an API call, redirect to another skill and even update a memory variable inside the chatbot. In addition to that, these actions could be repeated based on how you would want to drive the conversation. Messages could be grouped and depending on the evaluated condition, a specific message group is triggered. For our scenario, the first action would be to determine if the user is already logged in, based on which, the user’s email address in the linked profile could be retrieved and used to get a list of recent orders from the Commerce Cloud site. Let’s navigate to the Actions tab and click on ADD NEW MESSAGE GROUP. Adding API Calls Furthermore, in order to access the Commerce Cloud REST API, you need to define OAuth2 credentials and URL. 2.9 API Service Configuration Leave the Headers section as is for now and navigate to Response where the API response structure is defined. The response would be saved inside the variable api_service_response and we can create a namespace to store/retrieve the actual value. 2.10 API Service Response Great! Let’s add a new message group where we would be adding a condition for the trigger. Click ADD CONDITION. Next to If we need to include the operand, which in this case would be the current user’s email address. We will make use of the api response received from the API call we had defined earlier. 2.11 Using _api_service_response in a condition 2.12 Email from _api_service_response You can easily traverse the structure of User entity by going to the API documentation / Swagger UI (and if you want to try out the API). 2.13 API Documentation – Commerce Cloud User Entity Chatbot Memory Fields For the ease of maintainability and usability, we can store the path inside a memory variable which we can then easily refer to instead of having to traverse the complete response structure for use inside the chatbot. Go to the API call we had created earlier and click on UPDATE CONVERSATION > EDIT MEMORY. 2.14 Edit Memory In order to access the memory variables, it is necessary to enclose the reference with curly brackets. If the condition evaluates to true, we are going to trigger sending a message in the chat. Click SEND MESSAGE followed by selecting message type as Button and then create the message that we want to send. 2.15 API Call for retrieving the order list using the email address 2.16 Response Object Structure 2.17 Display order list in the chat using the response object 2.18 API call to retrieve order details using Order ID from the chatbot memory 2.19 Set memory fields to hold order details 2.20 API Call to retrieve product details 2.21 Product response Object 2.22 Retrieve Order Status details from memory Conclusion: At this point, our chatbot is functional enough to handle a conversation that involves providing the end user with an order status. The next step would be to discuss in detail, the Qualtrics integration piece where the chatbot presents the end-user with a Qualtrics survey and would update the survey responses received inside the chat. More of this in part 3. Later! Part 1: Introduction and Getting Started Part 3: Building the Qualtrics Survey and App Part 4: Additional API Calls and Tips ———————————————————————– For more information about SAP Conversational AI: - Visit our web page - Create your account on our platform - Engage with our SAP Community - Ask your questions on SAP Answers - Read our product documentation Appendix. A. Testing the bot using the Debug mode We will continue to add skills to progress the conversation past the email verification. For example, this would include creating a skill for order status retrieval using API calls to Commerce Cloud webservices. We would be able to use memory variables to store the API responses for use inside the chatbot text messages. B. Custom Entity for Order Number Navigate to the Entities section in the Train tab and click CREATE AN ENTITY. Custom Entity Dialog Custom Entity OrderNumber Created What is the different between these memory variables? {{memory.ordernumber.raw}} {{memory.ordernumber.value}} {{nlp.source}} {{#ordernumber.raw}}
https://blogs.sap.com/2020/12/02/building-an-sap-conversational-ai-chatbot-that-integrates-with-qualtrics-and-sap-customer-experience-2-4/?update=updated
CC-MAIN-2021-39
refinedweb
1,639
61.67
>>.'" Congratulations:Congratulations to Judge Alsup (Score:3, Insightful) Long term speaking, its a win for Oracle. It's really only a matter of time before it would have bit them in the butt. There developers use APIs as well.:Decimated (Score:5, Insightful) The original 'reduce by one tenth' decimate is archaic. Modern usage means kill/weaken a significant portion of the group/thing being decimated. And you know this, too. Re:Good to Know :Congratulations to Judge Alsup like.":Decimated definition will also be listed. More likely ahead of the one you've given, illustrating the most common usage of the word. Yes... languages evolve. Words change meaning. Live with it. Re:Seriously? (Score:2, Insightful) Why even bother to have two returns? int max(int a, int b) { return (a > b ? a : b); }:Congratulations to Judge Alsup (Score:5, Insightful) The judge knows more about programming than Oracle does!:Good to Know (Score:5, Insightful). Re:Stallman was right! (Score:4, Insightful)
https://tech.slashdot.org/story/12/05/31/237208/judge-rules-apis-can-not-be-copyrighted/insightful-comments
CC-MAIN-2016-50
refinedweb
164
53.78
[UNSOLVEABLE] Again problems with QWidget in QML this time HWND Hi, I'm trying to create custom QWidget to use in QML. Basically I want VLC to play in QML. All I get is the sound from video, without picture. And in QML designer it says that there is no property for anchors, width or height for my VLC extension. I need to use QWidget because of the HWND property. Maybe QML has one of it's own? Here is my vlc_player.h @#ifndef VLC_PLAYER_H #define VLC_PLAYER_H #include <QtDeclarative/QDeclarativeExtensionPlugin> #include <QtDeclarative/qdeclarative.h> #include <QtGui/QGraphicsProxyWidget> #include <QtGui/QWidget> #include <QDebug> #include <vlc/vlc.h> class vlc_player : public QGraphicsProxyWidget { Q_OBJECT Q_PROPERTY(QString texts WRITE play) public: vlc_player(QGraphicsItem* parent = 0); libvlc_instance_t * inst; libvlc_media_player_t * mp; libvlc_media_t * m; void play(const QString &texts;); private: QWidget *vlcvideo; }; #endif // VLC_PLAYER_H @ vlc_player.cpp @#include "vlc_player.h" #include <QtGui/QWidget> #include <QDebug> vlc_player::vlc_player(QGraphicsItem* parent) : QGraphicsProxyWidget(parent) { vlcvideo = new QWidget(); vlcvideo->setObjectName(QString::fromUtf8("vlcvideo")); vlcvideo->setGeometry(QRect(10, 90, 431, 291)); vlcvideo->setAttribute(Qt::WA_NoSystemBackground); vlcvideo->setStyleSheet("background-color:black;"); vlcvideo->setMinimumSize(400,400); this->setWidget(vlcvideo); qDebug()<<vlcvideo->winId(); /* Load the VLC engine */ inst = libvlc_new (0, NULL); setFlag(QGraphicsItem::ItemHasNoContents, false); } void vlc_player::play(const QString ); } -- @ and part of my qml @ QWidget { id: vlc1 texts: "nasa.wmv" anchors.fill: parent width:400 height:400 }@ Best regards Raivis The QML property is define with Q_PROPERTY(..) statement, so if you want to use anchors, width or height, you need to declare them and write the "Read", "Write" method at least. The common QML item is inherits from QDeclarativeItem, so they have those properties And, QWidget is not a right name for custom QML element below: @ QWidget { id: vlc1 texts: "nasa.wmv" anchors.fill: parent width:400 height:400 } @ Ok I changed the name, now QWidget is named VlcPlayer. Still No picture, just audio. I'll get back to QDeclarativeItem later, now my priority is video output As you mentioned before, do you add width, height property for your widget? Is the code work well with just QWidget? With just a QWidget my code works OK. Now I've made my extension with QDeclarativeItem, it seems that QDeclarativeItem doesn't have setWidget command. Basically the same effect, no video but I have a sound. Here is my full code: VlcPlayer.h @#ifndef VLCPLAYER_H #define VLCPLAYER_H #include <QtDeclarative/QDeclarativeExtensionPlugin> #include <QtDeclarative/qdeclarative.h> #include <QDeclarativeItem> #include <QtGui/QGraphicsProxyWidget> #include <QtGui/QWidget> #include <QDebug> #include <vlc/vlc.h> class VlcPlayer : public QDeclarativeItem { Q_OBJECT Q_PROPERTY(QString media READ playing WRITE play) public: VlcPlayer(QDeclarativeItem* parent = 0); libvlc_instance_t * inst; libvlc_media_player_t * mp; libvlc_media_t * m; void play(const QString &media;); QString playing() const; private: QWidget *vlcvideo; QString m_name; }; #endif // VLCPLAYER_H @ vlcplayer.cpp @#include "vlcplayer.h" #include <QtGui/QWidget> #include <QDebug> VlcPlayer::VlcPlayer(QDeclarativeItem* parent) : QDeclarativeItem(parent) { vlcvideo = new QWidget(); //setFlag(QDeclarativeItem::ItemHasNoContents, false); //setWidget(vlcvideo); /* Load the VLC engine */ inst = libvlc_new (0, NULL); } QString VlcPlayer::playing() const { return m_name; } void VlcPlayer::play(const QString &texts;) { m_name =); } @ main.cpp @#include <QtGui/QApplication> #include "qmlapplicationviewer.h" #include "vlcplayer.h" #include <qdeclarative.h> #include <QDeclarativeView> int main(int argc, char *argv[]) { QApplication app(argc, argv); qmlRegisterType<VlcPlayer>("Vlc", 1, 0, "VlcPlayer"); QmlApplicationViewer viewer; viewer.setMainQmlFile(QLatin1String("qml/widget/main.qml")); viewer.showExpanded(); return app.exec(); } @ main.qml @import QtQuick 1.0 import Vlc 1.0 Rectangle { width: 360 height: 360 VlcPlayer { id: vlc1 clip: false anchors.fill: parent media: "nasa.wmv" } } @ Now in Design mode I don't have any errors. As I mentioned no video either, just the sound! Here is a screen shot what I get when I run my app: !(No video just audio)! I solved my problem, the mistake was trying to use QWidget, somehow I can set the QWidget's background through CSS and it will show up in QML, but vlc won't draw anything on it. The solution is to use QGraphicsScene instead. Well it worked for me. Hi! I have the same problem, but I use phonon module. Can you place code with integration QGraphicsScene to Qml here? Thank you in advance! Sorry when I made that conclusion, I thought I could implement QGraphicsSCene with valid winId, actually you can't. Only the main windows has valid WinId, so the VLC or maybe even phonon draws on top of the QML viewer. I can give you code for how to implement Qgraphicscene without winid, you will be able to draw circles rectangles or anything you want. But you won't get a valid winId. And if you use phonon, maybe check out Qt Multimedia. I once came across, that QML or Qt Quick has built in video/audio player. If I remember correctly the library was called Qt Multimedia. AFAIK, there is a possibility to fore a widget to be a real windows window. Then it will have a valid winId(). I think it was something like: @ x->setAttribute(Qt::WA_NativeWindow, true); x->setAttribute(Qt::WA_DontCreateNativeAncestors, true); @ where x is the widget that should show the video. as description, have a look at "native vs. alient widgets": Thanks...Unfortunately, player based on QtMobility, and Qml element "Video" are play stream video not correctly. That is why I use phonon modul. And recently I've learned that phonon player can output video to widget only... Still, even with set attribute in qt quick my VLC plugin doesn't get a picture. If I understand correctly, when I embed QWidget in QML, it's winId technically won't exist anymore.? Well, I had this problem last summer, I 've to look for my old code. I think I solved it, but I couldn't found my source code at this moment. I think it's on my other computer. Could you inform me about your search results please? It's urgent, for a long time already can't find the solution. @xcoder: would be nice to see a working example, still facing the same problems as you and Roman90. couldn't this be considered as a bug from qt side? regards ..
https://forum.qt.io/topic/7869/unsolveable-again-problems-with-qwidget-in-qml-this-time-hwnd
CC-MAIN-2019-30
refinedweb
1,003
50.43
From: Pavel Vozenilek (pavel_vozenilek_at_[hidden]) Date: 2005-03-15 13:12:40 FSM library written by Andreas Huber has been accepted into Boost, with few conditions and few recomendations. Thanks, Andreas, for your work and stamina to get thus far! Also thanks to all courageous reviewers. Short overview: =============== Opinions of reviewers were mixed. Large group liked the library, some even used it in production code. Other large group had objections Most questioned were performance and API. At the end my opinion is: no single perfect fit exists so it makes little sense to dismiss this library waiting for a hypothetical everyone-is-happy solution. Other variant was to ask for changes and for second review later. FSM is mature, has been developed for years and will be maintained in the future: its not likely such solution would make much of good for end result. Conditions: 1. Name of the library should be changed: - not to suggest that only one FSM implementation may exists in Boost - not to give wrong impression to people who look for tool with maximal runtime efficiency. - to stress the "high-level" nature of the library Names suggested during review were Statechart (by Alexander Nasonov) and umlfsm. 2. Information about performance overhead should be separated into page of its own and made clearly visible. Recomendations: 3. API of the library should be simplified as much as possible. Quirks and dangerous situations should be eliminated as much as possible. 4. The documentation should be improved as much as possible. 5. Runtime overhead should be decreased as much as feasible but without sacrifying currently available features of the library. Detailed information: ===================== 1. Name of the library should include change of namespace as well. 2. The information about runtime overhead. Separate page should be created and made visible on front page. It should contain examples of applications where FSM may not be the best solution (e.g. parsers). 3. API of the library, quirks and features. People asked many ways to simplify the API and increase orthogonality of its features: - the danger in using transit<> should be eliminated (Jonathan Turkanis suggested way how to do it) - the syntax to add deferred event should be cleaned up, even it it adds overhead - similarly posting events from inside FSM: if there's chance to make its syntax easier it should be done (no matter what IMHO) - reducing # of template parameters for state, possibly putting reactions as typedef inside state - it was suggested (by Daryl Green) to deduce reaction-list by examination of class interface - polymorphic events may be added for completeness (Peter Petrov found workaround but it may be better to do it right) - add handling of unknown events - custom allocator for FSM used for all states constructed in it. Perhaps it is possible to detect presence of overloaded operator new in state and it if doesn't exist then use state_machine allocator - not using containers keeping historical data when history feature is not used - possibility to use flyweight classes for states or class factories to create states - eliminate need for mpl::list for history parameter - description of transition guards in header was requested (perhaps it may be optional feature) Whether the library should separate its asynchronous part out was not discussed much. I guess it is better to keep it in and possibly submit it as standalone library. 4. Documentation. Among suggested improvements were: - better indentation in code snippets, inlined comments, syntax highlighting - adding complete examples to code snippets so users can try immediatelly - more information for error handling and asynchronous FSMs - reduce the radius of big black dots for initial states - external documents describing UML mapping should be more visible - avoiding forward declarations of events in code snippets - more examples (e.g. half-adder used twice to create a full-adder, suggested by Dave Gomboc, combination of synchronous and asynchronous machines) The documentation is now very dense, splitting it into smaller parts may help. More hyperlinking would also help a lot. The documentation may contain page "How to" with tricks, workarounds and non-obvious examples of use. For example how to use nested state to keep data related to inner states. I think adding UML and/or FSM tutorial in documentation is not task if this library. 5. Runtime overhead. Best effort should be made but only after stabilizing features and API. Reducing executable code size (per state/transition) may be the first direction here. ------------------------------- I hope that alternative FSM implementations (like the one currently developed by Alexander Nasonov) or dynamic FSM will appear and will be submitted to Boost as well. /Pavel Boost-announce list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
http://lists.boost.org/boost-announce/2005/03/0056.php
crawl-002
refinedweb
791
51.58
Complex Types (CDH 5.5 or higher only). Impala supports the complex types ARRAY, MAP, and STRUCT in CDH 5.5 / Impala 2.3 and higher. The Hive UNION type is not currently supported. Continue reading: Once you understand the basics of complex types, refer to the individual type topics when you need to refresh your memory about syntax and examples: Benefits of Impala Complex Types The reasons for using Impala complex types include the following: You already have data produced by Hive or other non-Impala component that uses the complex type column names. You might need to convert the underlying data to Parquet to use it with Impala. Your data model originates with a non-SQL programming language or a NoSQL data management system. For example, if you are representing Python data expressed as nested lists, dictionaries, and tuples, those data structures correspond closely to Impala ARRAY, MAP, and STRUCT types. Your analytic queries involving multiple tables could benefit from greater locality during join processing. By packing more related data items within each HDFS data block, complex types let join queries avoid the network overhead of the traditional Hadoop shuffle or broadcast join techniques. The Impala complex type support produces result sets with all scalar values, and the scalar components of complex types can be used with all SQL clauses, such as GROUP BY, ORDER BY, all kinds of joins, subqueries, and inline views. The ability to process complex type data entirely in SQL reduces the need to write application-specific code in Java or other programming languages to deconstruct the underlying data structures. Overview of Impala Complex Types The ARRAY and MAP types are closely related: they represent collections with arbitrary numbers of elements, where each element is the same type. In contrast, STRUCT groups together a fixed number of items into a single element. The parts of a STRUCT element (the fields) can be of different types, and each field has a name. The elements of an ARRAY or MAP, or the fields of a STRUCT, can also be other complex types. You can construct elaborate data structures with up to 100 levels of nesting. For example, you can make an ARRAY whose elements are STRUCTs. Within each STRUCT, you can have some fields that are ARRAY, MAP, or another kind of STRUCT. The Impala documentation uses the terms complex and nested types interchangeably; for simplicity, it primarily uses the term complex types, to encompass all the properties of these types. When visualizing your data model in familiar SQL terms, you can think of each ARRAY or MAP as a miniature table, and each STRUCT as a row within such a table. By default, the table represented by an ARRAY has two columns, POS to represent ordering of elements, and ITEM representing the value of each element. Likewise, by default, the table represented by a MAP encodes key-value pairs, and therefore has two columns, KEY and VALUE. The ITEM and VALUE names are only required for the very simplest kinds of ARRAY and MAP columns, ones that hold only scalar values. When the elements within the ARRAY or MAP are of type STRUCT rather than a scalar type, then the result set contains columns with names corresponding to the STRUCT fields rather than ITEM or VALUE. You write most queries that process complex type columns using familiar join syntax, even though the data for both sides of the join resides in a single table. The join notation brings together the scalar values from a row with the values from the complex type columns for that same row. The final result set contains all scalar values, allowing you to do all the familiar filtering, aggregation, ordering, and so on for the complex data entirely in SQL or using business intelligence tools that issue SQL queries. Behind the scenes, Impala ensures that the processing for each row is done efficiently on a single host, without the network traffic involved in broadcast or shuffle joins. The most common type of join query for tables with complex type columns is INNER JOIN, which returns results only in those cases where the complex type contains some elements. Therefore, most query examples in this section use either the INNER JOIN clause or the equivalent comma notation. Design Considerations for Complex Types When planning to use Impala complex types, and designing the Impala schema, first learn how this kind of schema differs from traditional table layouts from the relational database and data warehousing fields. Because you might have already encountered complex types in a Hadoop context while using Hive for ETL, also learn how to write high-performance analytic queries for complex type data using Impala SQL syntax. Continue reading: How Complex Types Differ from Traditional Data Warehouse Schemas Complex types let you associate arbitrary data structures with a particular row. If you are familiar with schema design for relational database management systems or data warehouses, a schema with complex types has the following differences: Logically, related values can now be grouped tightly together in the same table. In traditional data warehousing, related values were typically arranged in one of two ways: Split across multiple normalized tables. Foreign key columns specified which rows from each table were associated with each other. This arrangement avoided duplicate data and therefore the data was compact, but join queries could be expensive because the related data had to be retrieved from separate locations. (In the case of distributed Hadoop queries, the joined tables might even be transmitted between different hosts in a cluster.) Flattened into a single denormalized table. Although this layout eliminated some potential performance issues by removing the need for join queries, the table typically became larger because values were repeated. The extra data volume could cause performance issues in other parts of the workflow, such as longer ETL cycles or more expensive full-table scans during queries. Complex types represent a middle ground that addresses these performance and volume concerns. By physically locating related data within the same data files, complex types increase locality and reduce the expense of join queries. By associating an arbitrary amount of data with a single row, complex types avoid the need to repeat lengthy values such as strings. Because Impala knows which complex type values are associated with each row, you can save storage by avoiding artificial foreign key values that are only used for joins. The flexibility of the STRUCT, ARRAY, and MAP types lets you model familiar constructs such as fact and dimension tables from a data warehouse, and wide tables representing sparse matrixes. Physical Storage for Complex Types Physically, the scalar and complex columns in each row are located adjacent to each other in the same Parquet data file, ensuring that they are processed on the same host rather than being broadcast across the network when cross-referenced within a query. This co-location simplifies the process of copying, converting, and backing all the columns up at once. Because of the column-oriented layout of Parquet files, you can still query only the scalar columns of a table without imposing the I/O penalty of reading the (possibly large) values of the composite columns. Within each Parquet data file, the constituent parts of complex type columns are stored in column-oriented format: Each field of a STRUCT type is stored like a column, with all the scalar values adjacent to each other and encoded, compressed, and so on using the Parquet space-saving techniques. For an ARRAY containing scalar values, all those values (represented by the ITEM pseudocolumn) are stored adjacent to each other. For a MAP, the values of the KEY pseudocolumn are stored adjacent to each other. If the VALUE pseudocolumn is a scalar type, its values are also stored adjacent to each other. If an ARRAY element, STRUCT field, or MAP VALUE part is another complex type, the column-oriented storage applies to the next level down (or the next level after that, and so on for deeply nested types) where the final elements, fields, or values are of scalar types. The numbers represented by the POS pseudocolumn of an ARRAY are not physically stored in the data files. They are synthesized at query time based on the order of the ARRAY elements associated with each row. File Format Support for Impala Complex Types Currently, Impala queries support complex type data only in the Parquet file format. See Using the Parquet File Format with Impala Tables for details about the performance benefits and physical layout of this file format. Because Impala does not parse the data structures containing nested types for unsupported formats such as text, Avro, SequenceFile, or RCFile, you cannot use data files in these formats with Impala, even if the query does not refer to the nested type columns. Also, if a table using an unsupported format originally contained nested type columns, and then those columns were dropped from the table using ALTER TABLE ... DROP COLUMN, any existing data files in the table still contain the nested type data and Impala queries on that table will generate errors. The one exception to the preceding rule is COUNT(*) queries on RCFile tables that include complex types. Such queries are allowed in CDH 5.8 / Impala 2.6 and higher. You can perform DDL operations for tables involving complex types in most file formats other than Parquet. You cannot create tables in Impala with complex types using text files. You can have a partitioned table with complex type columns that uses a non-Parquet format, and use ALTER TABLE to change the file format to Parquet for individual partitions. When you put Parquet data files into those partitions, Impala can execute queries against that data as long as the query does not involve any of the non-Parquet partitions. If you use the parquet-tools command to examine the structure of a Parquet data file that includes complex types, you see that both ARRAY and MAP are represented as a Bag in Parquet terminology, with all fields marked Optional because Impala allows any column to be nullable. Impala supports either 2-level and 3-level encoding within each Parquet data file. When constructing Parquet data files outside Impala, use either encoding style but do not mix 2-level and 3-level encoding within the same data file. Choosing Between Complex Types and Normalized Tables Choosing between multiple normalized fact and dimension tables, or a single table containing complex types, is an important design decision. If you are coming from a traditional database or data warehousing background, you might be familiar with how to split up data between tables. Your business intelligence tools might already be optimized for dealing with this kind of multi-table scenario through join queries. If you are pulling data from Impala into an application written in a programming language that has data structures analogous to the complex types, such as Python or Java, complex types in Impala could simplify data interchange and improve understandability and reliability of your program logic. You might already be faced with existing infrastructure or receive high volumes of data that assume one layout or the other. For example, complex types are popular with web-oriented applications, for example to keep information about an online user all in one place for convenient lookup and analysis, or to deal with sparse or constantly evolving data fields. If some parts of the data change over time while related data remains constant, using multiple normalized tables lets you replace certain parts of the data without reloading the entire data set. Conversely, if you receive related data all bundled together, such as in JSON files, using complex types can save the overhead of splitting the related items across multiple tables. From a performance perspective: In Parquet tables, Impala can skip columns that are not referenced in a query, avoiding the I/O penalty of reading the embedded data. When complex types are nested within a column, the data is physically divided at a very granular level; for example, a query referring to data nested multiple levels deep in a complex type column does not have to read all the data from that column, only the data for the relevant parts of the column type hierarchy. Complex types avoid the possibility of expensive join queries when data from fact and dimension tables is processed in parallel across multiple hosts. All the information for a row containing complex types is typically to be in the same data block, and therefore does not need to be transmitted across the network when joining fields that are all part of the same row. The tradeoff with complex types is that fewer rows fit in each data block. Whether it is better to have more data blocks with fewer rows, or fewer data blocks with many rows, depends on the distribution of your data and the characteristics of your query workload. If the complex columns are rarely referenced, using them might lower efficiency. If you are seeing low parallelism due to a small volume of data (relatively few data blocks) in each table partition, increasing the row size by including complex columns might produce more data blocks and thus spread the work more evenly across the cluster. See Scalability Considerations for Impala for more on this advanced topic. Differences Between Impala and Hive Complex Types Impala can query Parquet tables containing ARRAY, STRUCT, and MAP columns produced by Hive. There are some differences to be aware of between the Impala SQL and HiveQL syntax for complex types, primarily for queries. Impala supports a subset of the syntax that Hive supports for specifying ARRAY, STRUCT, and MAP types in the CREATE TABLE statements. Because Impala STRUCT columns include user-specified field names, you use the NAMED_STRUCT() constructor in Hive rather than the STRUCT() constructor when you populate an Impala STRUCT column using a Hive INSERT statement. The Hive UNION type is not currently supported in Impala. While Impala usually aims for a high degree of compatibility with HiveQL query syntax, Impala syntax differs from Hive for queries involving complex types. The differences are intended to provide extra flexibility for queries involving these kinds of tables. - Impala uses dot notation for referring to element names or elements within complex types, and join notation for cross-referencing scalar columns with the elements of complex types within the same row, rather than the LATERAL VIEW clause and EXPLODE() function of HiveQL. - Using join notation lets you use all the kinds of join queries with complex type columns. For example, you can use a LEFT OUTER JOIN, LEFT ANTI JOIN, or LEFT SEMI JOIN query to evaluate different scenarios where the complex columns do or do not contain any elements. - You can include references to collection types inside subqueries and inline views. For example, you can construct a FROM clause where one of the "tables" is a subquery against a complex type column, or use a subquery against a complex type column as the argument to an IN or EXISTS clause. - The Impala pseudocolumn POS lets you retrieve the position of elements in an array along with the elements themselves, equivalent to the POSEXPLODE() function of HiveQL. You do not use index notation to retrieve a single array element in a query; the join query loops through the array elements and you use WHERE clauses to specify which elements to return. Join clauses involving complex type columns do not require an ON or USING clause. Impala implicitly applies the join key so that the correct array entries or map elements are associated with the correct row from the table. Impala does not currently support the UNION complex type. Limitations and Restrictions for Complex Types Complex type columns can only be used in tables or partitions with the Parquet file format. Complex type columns cannot be used as partition key columns in a partitioned table. When you use complex types with the ORDER BY, GROUP BY, HAVING, or WHERE clauses, you cannot refer to the column name by itself. Instead, you refer to the names of the scalar values within the complex type, such as the ITEM, POS, KEY, or VALUE pseudocolumns, or the field names from a STRUCT. The maximum depth of nesting for complex types is 100 levels. The maximum length of the column definition for any complex type, including declarations for any nested types, is 4000 characters. For ideal performance and scalability, use small or medium-sized collections, where all the complex columns contain at most a few hundred megabytes per row. Remember, all the columns of a row are stored in the same HDFS data block, whose size in Parquet files typically ranges from 256 MB to 1 GB. Including complex type columns in a table introduces some overhead that might make queries that do not reference those columns somewhat slower than Impala queries against tables without any complex type columns. Expect at most a 2x slowdown compared to tables that do not have any complex type columns. Currently, the COMPUTE STATS statement does not collect any statistics for columns containing complex types. Impala uses heuristics to construct execution plans involving complex type columns. Currently, Impala built-in functions and user-defined functions cannot accept complex types as parameters or produce them as function return values. (When the complex type values are materialized in an Impala result set, the result set contains the scalar components of the values, such as the POS or ITEM for an ARRAY, the KEY or VALUE for a MAP, or the fields of a STRUCT; these scalar data items can be used with built-in functions and UDFs as usual.). Currently, Impala can query complex type columns only from Parquet tables or Parquet partitions within partitioned tables. Although you can use complex types in tables with Avro, text, and other file formats as part of your ETL pipeline, for example as intermediate tables populated through Hive, doing analytics through Impala requires that the data eventually ends up in a Parquet table. The requirement for Parquet data files means that you can use complex types with Impala tables hosted on other kinds of file storage systems such as Isilon and Amazon S3, but you cannot use Impala to query complex types from HBase tables. See File Format Support for Impala Complex Types for more details. Using Complex Types in SQL When using complex types through SQL in Impala, you learn the notation for < > delimiters for the complex type columns in CREATE TABLE statements, and how to construct join queries to "unpack" the scalar values nested inside the complex data structures. You might need to condense a traditional RDBMS or data warehouse schema into a smaller number of Parquet tables, and use Hive, Spark, Pig, or other mechanism outside Impala to populate the tables with data. Complex Type Syntax for DDL Statements The definition of data_type, as seen in the CREATE TABLE and ALTER TABLE statements, now includes complex types in addition to primitive types: primitive_type | array_type | map_type | struct_type Unions are not currently supported. Array, struct, and map column type declarations are specified in the CREATE TABLE statement. You can also add or change the type of complex columns through the ALTER TABLE statement. Currently, Impala queries allow complex types only in tables that use the Parquet format. If an Impala query encounters complex types in a table or partition using another file format, the query returns a runtime error. You can use ALTER TABLE ... SET FILEFORMAT PARQUET to change the file format of an existing table containing complex types to Parquet, after which Impala can query it. Make sure to load Parquet files into the table after changing the file format, because the ALTER TABLE ... SET FILEFORMAT statement does not convert existing data to the new file format. Partitioned tables can contain complex type columns. All the partition key columns must be scalar types. Because use cases for Impala complex types require that you already have Parquet data files produced outside of Impala, you can use the Impala CREATE TABLE LIKE PARQUET syntax to produce a table with columns that match the structure of an existing Parquet file, including complex type columns for nested data structures. Remember to include the STORED AS PARQUET clause in this case, because even with CREATE TABLE LIKE PARQUET, the default file format of the resulting table is still text. You cannot use the CREATE TABLE AS SELECT syntax to create a table with nested type columns because the complex columns are omitted from the result set of an Impala SELECT * or SELECT col_name query, and because Impala currently does not support writing Parquet files with complex type columns, For example, when defining a table that holds contact information, you might represent phone numbers differently depending on the expected layout and relationships of the data, and how well you can predict those properties in advance. Here are different ways that you might represent phone numbers in a traditional relational schema, with equivalent representations using complex types. The traditional, simplest way to represent phone numbers in a relational table is to store all contact info in a single table, with all columns having scalar types, and each potential phone number represented as a separate column. In this example, each person can only have these 3 types of phone numbers. If the person does not have a particular kind of phone number, the corresponding column is NULL for that row. CREATE TABLE contacts_fixed_phones ( id BIGINT , name STRING , address STRING , home_phone STRING , work_phone STRING , mobile_phone STRING ) STORED AS PARQUET; Using a complex type column to represent the phone numbers adds some extra flexibility. Now there could be an unlimited number of phone numbers. Because the array elements have an order but not symbolic names, you could decide in advance that phone_number[0] is the home number, [1] is the work number, [2] is the mobile number, and so on. (In subsequent examples, you will see how to create a more flexible naming scheme using other complex type variations, such as a MAP or an ARRAY where each element is a STRUCT.) CREATE TABLE contacts_array_of_phones ( id BIGINT , name STRING , address STRING , phone_number ARRAY < STRING > ) STORED AS PARQUET; Another way to represent an arbitrary set of phone numbers is with a MAP column. With a MAP, each element is associated with a key value that you specify, which could be a numeric, string, or other scalar type. This example uses a STRING key to give each phone number a name, such as 'home' or 'mobile'. A query could filter the data based on the key values, or display the key values in reports. CREATE TABLE contacts_unlimited_phones ( id BIGINT, name STRING, address STRING, phone_number MAP < STRING,STRING > ) STORED AS PARQUET; If you are an experienced database designer, you already know how to work around the limitations of the single-table schema from Traditional Relational Representation of Phone Numbers: Single Table. By normalizing the schema, with the phone numbers in their own table, you can associate an arbitrary set of phone numbers with each person, and associate additional details with each phone number, such as whether it is a home, work, or mobile phone. The flexibility of this approach comes with some drawbacks. Reconstructing all the data for a particular person requires a join query, which might require performance tuning on Hadoop because the data from each table might be transmitted from a different host. Data management tasks such as backups and refreshing the data require dealing with multiple tables instead of a single table. This example illustrates a traditional database schema to store contact info normalized across 2 tables. The fact table establishes the identity and basic information about person. A dimension table stores information only about phone numbers, using an ID value to associate each phone number with a person ID from the fact table. Each person can have 0, 1, or many phones; the categories are not restricted to a few predefined ones; and the phone table can contain as many columns as desired, to represent all sorts of details about each phone number. CREATE TABLE fact_contacts (id BIGINT, name STRING, address STRING) STORED AS PARQUET; CREATE TABLE dim_phones ( contact_id BIGINT , category STRING , international_code STRING , area_code STRING , exchange STRING , extension STRING , mobile BOOLEAN , carrier STRING , current BOOLEAN , service_start_date TIMESTAMP , service_end_date TIMESTAMP ) STORED AS PARQUET; To represent a schema equivalent to the one from Traditional Relational Representation of Phone Numbers: Normalized Tables using complex types, this example uses an ARRAY where each array element is a STRUCT. As with the earlier complex type examples, each person can have an arbitrary set of associated phone numbers. Making each array element into a STRUCT lets us associate multiple data items with each phone number, and give a separate name and type to each data item. The STRUCT fields of the ARRAY elements reproduce the columns of the dimension table from the previous example. You can do all the same kinds of queries with the complex type schema as with the normalized schema from the previous example. The advantages of the complex type design are in the areas of convenience and performance. Now your backup and ETL processes only deal with a single table. When a query uses a join to cross-reference the information about a person with their associated phone numbers, all the relevant data for each row resides in the same HDFS data block, meaning each row can be processed on a single host without requiring network transmission. CREATE TABLE contacts_detailed_phones ( id BIGINT, name STRING, address STRING , phone ARRAY < STRUCT < category: STRING , international_code: STRING , area_code: STRING , exchange: STRING , extension: STRING , mobile: BOOLEAN , carrier: STRING , current: BOOLEAN , service_start_date: TIMESTAMP , service_end_date: TIMESTAMP >> ) STORED AS PARQUET; SQL Statements that Support Complex Types The Impala SQL statements that support complex types are currently CREATE TABLE, ALTER TABLE, DESCRIBE, LOAD DATA, and SELECT. That is, currently Impala can create or alter tables containing complex type columns, examine the structure of a table containing complex type columns, import existing data files containing complex type columns into a table, and query Parquet tables containing complex types.. Continue reading: DDL Statements and Complex Types Column specifications for complex or nested types use < and > delimiters: -- What goes inside the < > for an ARRAY is a single type, either a scalar or another -- complex type (ARRAY, STRUCT, or MAP). CREATE TABLE array_t ( id BIGINT, a1 ARRAY <STRING>, a2 ARRAY <BIGINT>, a3 ARRAY <TIMESTAMP>, a4 ARRAY <STRUCT <f1: STRING, f2: INT, f3: BOOLEAN>> ) STORED AS PARQUET; -- What goes inside the < > for a MAP is two comma-separated types specifying the types of the key-value pair: -- a scalar type representing the key, and a scalar or complex type representing the value. CREATE TABLE map_t ( id BIGINT, m1 MAP <STRING, STRING>, m2 MAP <STRING, BIGINT>, m3 MAP <BIGINT, STRING>, m4 MAP <BIGINT, BIGINT>, m5 MAP <STRING, ARRAY <STRING>> ) STORED AS PARQUET; -- What goes inside the < > for a STRUCT is a comma-separated list of fields, each field defined as -- name:type. The type can be a scalar or a complex type. The field names for each STRUCT do not clash -- with the names of table columns or fields in other STRUCTs. A STRUCT is most often used inside -- an ARRAY or a MAP rather than as a top-level column. CREATE TABLE struct_t ( id BIGINT, s1 STRUCT <f1: STRING, f2: BIGINT>, s2 ARRAY <STRUCT <f1: INT, f2: TIMESTAMP>>, s3 MAP <BIGINT, STRUCT <name: STRING, birthday: TIMESTAMP>> ) STORED AS PARQUET; Queries and Complex Types The result set of an Impala query always contains all scalar types; the elements and fields within any complex type queries must be "unpacked" using join queries. A query cannot directly retrieve the entire value for a complex type column. Impala returns an error in this case. Queries using SELECT * are allowed for tables with complex types, but the columns with complex types are skipped. The following example shows how referring directly to a complex type column returns an error, while SELECT * on the same table succeeds, but only retrieves the scalar columns. SELECT c_orders FROM customer LIMIT 1; ERROR: AnalysisException: Expr 'c_orders' in select list returns a complex type 'ARRAY<STRUCT<o_orderkey:BIGINT,o_orderstatus:STRING, ... l_receiptdate:STRING,l_shipinstruct:STRING,l_shipmode:STRING,l_comment:STRING>>>>'. Only scalar types are allowed in the select list. -- Original column has several scalar and one complex column. DESCRIBE customer; +--------------+------------------------------------+ | name | type | +--------------+------------------------------------+ | c_custkey | bigint | | c_name | string | ... | c_orders | array<struct< | | | o_orderkey:bigint, | | | o_orderstatus:string, | | | o_totalprice:decimal(12,2), | ... | | >> | +--------------+------------------------------------+ -- When we SELECT * from that table, only the scalar columns come back in the result set. CREATE TABLE select_star_customer STORED AS PARQUET AS SELECT * FROM customer; +------------------------+ | summary | +------------------------+ | Inserted 150000 row(s) | +------------------------+ -- The c_orders column, being of complex type, was not included in the SELECT * result set. DESC select_star_customer; +--------------+---------------+ | name | type | +--------------+---------------+ | c_custkey | bigint | | c_name | string | | c_address | string | | c_nationkey | smallint | | c_phone | string | | c_acctbal | decimal(12,2) | | c_mktsegment | string | | c_comment | string | +--------------+---------------+ References to fields within STRUCT columns use dot notation. If the field name is unambiguous, you can omit qualifiers such as table name, column name, or even the ITEM or VALUE pseudocolumn names for STRUCT elements inside an ARRAY or a MAP. SELECT id, address.city FROM customers WHERE address.zip = 94305; References to elements within ARRAY columns use the ITEM pseudocolumn: select r_name, r_nations.item.n_name from region, region.r_nations limit 7; +--------+----------------+ | r_name | item.n_name | +--------+----------------+ | EUROPE | UNITED KINGDOM | | EUROPE | RUSSIA | | EUROPE | ROMANIA | | EUROPE | GERMANY | | EUROPE | FRANCE | | ASIA | VIETNAM | | ASIA | CHINA | +--------+----------------+ References to fields within MAP columns use the KEY and VALUE pseudocolumns. In this example, once the query establishes the alias MAP_FIELD for a MAP column with a STRING key and an INT value, the query can refer to MAP_FIELD.KEY and MAP_FIELD.VALUE, which have zero, one, or many instances for each row from the containing table. DESCRIBE table_0; +---------+-----------------------+ | name | type | +---------+-----------------------+ | field_0 | string | | field_1 | map<string,int> | ... SELECT field_0, map_field.key, map_field.value FROM table_0, table_0.field_1 AS map_field WHERE length(field_0) = 1 LIMIT 10; +---------+-----------+-------+ | field_0 | key | value | +---------+-----------+-------+ | b | gshsgkvd | NULL | | b | twrtcxj6 | 18 | | b | 2vp5 | 39 | | b | fh0s | 13 | | v | 2 | 41 | | v | 8b58mz | 20 | | v | hw | 16 | | v | 65l388pyt | 29 | | v | 03k68g91z | 30 | | v | r2hlg5b | NULL | +---------+-----------+-------+ When complex types are nested inside each other, you use a combination of joins, pseudocolumn names, and dot notation to refer to specific fields at the appropriate level. This is the most frequent form of query syntax for complex columns, because the typical use case involves two levels of complex types, such as an ARRAY of STRUCT elements. SELECT id, phone_numbers.area_code FROM contact_info_many_structs INNER JOIN contact_info_many_structs.phone_numbers phone_numbers LIMIT 3; You can express relationships between ARRAY and MAP columns at different levels as joins. You include comparison operators between fields at the top level and within the nested type columns so that Impala can do the appropriate join operation. For example, the following queries work equivalently. They each return customer and order data for customers that have at least one order. SELECT c.c_name, o.o_orderkey FROM customer c, c.c_orders o LIMIT 5; +--------------------+------------+ | c_name | o_orderkey | +--------------------+------------+ | Customer#000072578 | 558821 | | Customer#000072578 | 2079810 | | Customer#000072578 | 5768068 | | Customer#000072578 | 1805604 | | Customer#000072578 | 3436389 | +--------------------+------------+ SELECT c.c_name, o.o_orderkey FROM customer c INNER JOIN c.c_orders o LIMIT 5; +--------------------+------------+ | c_name | o_orderkey | +--------------------+------------+ | Customer#000072578 | 558821 | | Customer#000072578 | 2079810 | | Customer#000072578 | 5768068 | | Customer#000072578 | 1805604 | | Customer#000072578 | 3436389 | +--------------------+------------+ The following query using an outer join returns customers that have orders, plus customers with no orders (no entries in the C_ORDERS array): SELECT c.c_custkey, o.o_orderkey FROM customer c LEFT OUTER JOIN c.c_orders o LIMIT 5; +-----------+------------+ | c_custkey | o_orderkey | +-----------+------------+ | 60210 | NULL | | 147873 | NULL | | 72578 | 558821 | | 72578 | 2079810 | | 72578 | 5768068 | +-----------+------------+ The following query returns only customers that have no orders. (With LEFT ANTI JOIN or LEFT SEMI JOIN, the query can only refer to columns from the left-hand table, because by definition there is no matching information in the right-hand table.) SELECT c.c_custkey, c.c_name FROM customer c LEFT ANTI JOIN c.c_orders o LIMIT 5; +-----------+--------------------+ | c_custkey | c_name | +-----------+--------------------+ | 60210 | Customer#000060210 | | 147873 | Customer#000147873 | | 141576 | Customer#000141576 | | 85365 | Customer#000085365 | | 70998 | Customer#000070998 | +-----------+--------------------+ You can also perform correlated subqueries to examine the properties of complex type columns for each row in the result set. Count the number of orders per customer. Note the correlated reference to the table alias C. The COUNT(*) operation applies to all the elements of the C_ORDERS array for the corresponding row, avoiding the need for a GROUP BY clause. select c_name, howmany FROM customer c, (SELECT COUNT(*) howmany FROM c.c_orders) v limit 5; +--------------------+---------+ | c_name | howmany | +--------------------+---------+ | Customer#000030065 | 15 | | Customer#000065455 | 18 | | Customer#000113644 | 21 | | Customer#000111078 | 0 | | Customer#000024621 | 0 | +--------------------+---------+ Count the number of orders per customer, ignoring any customers that have not placed any orders: SELECT c_name, howmany_orders FROM customer c, (SELECT COUNT(*) howmany_orders FROM c.c_orders) subq1 WHERE howmany_orders > 0 LIMIT 5; +--------------------+----------------+ | c_name | howmany_orders | +--------------------+----------------+ | Customer#000072578 | 7 | | Customer#000046378 | 26 | | Customer#000069815 | 11 | | Customer#000079058 | 12 | | Customer#000092239 | 26 | +--------------------+----------------+ Count the number of line items in each order. The reference to C.C_ORDERS in the FROM clause is needed because the O_ORDERKEY field is a member of the elements in the C_ORDERS array. The subquery labelled SUBQ1 is correlated: it is re-evaluated for the C_ORDERS.O_LINEITEMS array from each row of the CUSTOMERS table. SELECT c_name, o_orderkey, howmany_line_items FROM customer c, c.c_orders t2, (SELECT COUNT(*) howmany_line_items FROM c.c_orders.o_lineitems) subq1 WHERE howmany_line_items > 0 LIMIT 5; +--------------------+------------+--------------------+ | c_name | o_orderkey | howmany_line_items | +--------------------+------------+--------------------+ | Customer#000020890 | 1884930 | 95 | | Customer#000020890 | 4570754 | 95 | | Customer#000020890 | 3771072 | 95 | | Customer#000020890 | 2555489 | 95 | | Customer#000020890 | 919171 | 95 | +--------------------+------------+--------------------+ Get the number of orders, the average order price, and the maximum items in any order per customer. For this example, the subqueries labelled SUBQ1 and SUBQ2 are correlated: they are re-evaluated for each row from the original CUSTOMER table, and only apply to the complex columns associated with that row. SELECT c_name, howmany, average_price, most_items FROM customer c, (SELECT COUNT(*) howmany, AVG(o_totalprice) average_price FROM c.c_orders) subq1, (SELECT MAX(l_quantity) most_items FROM c.c_orders.o_lineitems ) subq2 LIMIT 5; +--------------------+---------+---------------+------------+ | c_name | howmany | average_price | most_items | +--------------------+---------+---------------+------------+ | Customer#000030065 | 15 | 128908.34 | 50.00 | | Customer#000088191 | 0 | NULL | NULL | | Customer#000101555 | 10 | 164250.31 | 50.00 | | Customer#000022092 | 0 | NULL | NULL | | Customer#000036277 | 27 | 166040.06 | 50.00 | +--------------------+---------+---------------+------------+ For example, these queries show how to access information about the ARRAY elements within the CUSTOMER table from the "nested TPC-H" schema, starting with the initial ARRAY elements and progressing to examine the STRUCT fields of the ARRAY, and then the elements nested within another ARRAY of STRUCT: -- How many orders does each customer have? -- The type of the ARRAY column doesn't matter, this is just counting the elements. SELECT c_custkey, count(*) FROM customer, customer.c_orders GROUP BY c_custkey LIMIT 5; +-----------+----------+ | c_custkey | count(*) | +-----------+----------+ | 61081 | 21 | | 115987 | 15 | | 69685 | 19 | | 109124 | 15 | | 50491 | 12 | +-----------+----------+ -- How many line items are part of each customer order? -- Now we examine a field from a STRUCT nested inside the ARRAY. SELECT c_custkey, c_orders.o_orderkey, count(*) FROM customer, customer.c_orders c_orders, c_orders.o_lineitems GROUP BY c_custkey, c_orders.o_orderkey LIMIT 5; +-----------+------------+----------+ | c_custkey | o_orderkey | count(*) | +-----------+------------+----------+ | 63367 | 4985959 | 7 | | 53989 | 1972230 | 2 | | 143513 | 5750498 | 5 | | 17849 | 4857989 | 1 | | 89881 | 1046437 | 1 | +-----------+------------+----------+ -- What are the line items in each customer order? -- One of the STRUCT fields inside the ARRAY is another -- ARRAY containing STRUCT elements. The join finds -- all the related items from both levels of ARRAY. SELECT c_custkey, o_orderkey, l_partkey FROM customer, customer.c_orders, c_orders.o_lineitems LIMIT 5; +-----------+------------+-----------+ | c_custkey | o_orderkey | l_partkey | +-----------+------------+-----------+ | 113644 | 2738497 | 175846 | | 113644 | 2738497 | 27309 | | 113644 | 2738497 | 175873 | | 113644 | 2738497 | 88559 | | 113644 | 2738497 | 8032 | +-----------+------------+-----------+ Pseudocolumns for ARRAY and MAP Types Each element in an ARRAY type has a position, indexed starting from zero, and a value. Each element in a MAP type represents a key-value pair. Impala provides pseudocolumns that let you retrieve this metadata as part of a query, or filter query results by including such things in a WHERE clause. You refer to the pseudocolumns as part of qualified column names in queries: - ITEM: The value of an array element. If the ARRAY contains STRUCT elements, you can refer to either array_name.ITEM.field_name or use the shorthand array_name.field_name. - POS: The position of an element within an array. - KEY: The value forming the first part of a key-value pair in a map. It is not necessarily unique. - VALUE: The data item forming the second part of a key-value pair in a map. If the VALUE part of the MAP element is a STRUCT, you can refer to either map_name.VALUE.field_name or use the shorthand map_name.field_name. Continue reading: ITEM and POS Pseudocolumns When an ARRAY column contains STRUCT elements, you can refer to a field within the STRUCT using a qualified name of the form array_column.field_name. If the ARRAY contains scalar values, Impala recognizes the special name array_column.ITEM to represent the value of each scalar array element. For example, if a column contained an ARRAY where each element was a STRING, you would use array_name.ITEM to refer to each scalar value in the SELECT list, or the WHERE or other clauses. This example shows a table with two ARRAY columns whose elements are of the scalar type STRING. When referring to the values of the array elements in the SELECT list, WHERE clause, or ORDER BY clause, you use the ITEM pseudocolumn because within the array, the individual elements have no defined names. create TABLE persons_of_interest ( person_id BIGINT, aliases ARRAY <STRING>, associates ARRAY <STRING>, real_name STRING ) STORED AS PARQUET; -- Get all the aliases of each person. SELECT real_name, aliases.ITEM FROM persons_of_interest, persons_of_interest.aliases ORDER BY real_name, aliases.item; -- Search for particular associates of each person. SELECT real_name, associates.ITEM FROM persons_of_interest, persons_of_interest.associates WHERE associates.item LIKE '% MacGuffin'; Because an array is inherently an ordered data structure, Impala recognizes the special name array_column.POS to represent the numeric position of each element within the array. The POS pseudocolumn lets you filter or reorder the result set based on the sequence of array elements. The following example uses a table from a flattened version of the TPC-H schema. The REGION table only has a few rows, such as one row for Europe and one for Asia. The row for each region represents all the countries in that region as an ARRAY of STRUCT elements: [localhost:21000] > desc region; +-------------+--------------------------------------------------------------------+ | name | type | +-------------+--------------------------------------------------------------------+ | r_regionkey | smallint | | r_name | string | | r_comment | string | | r_nations | array<struct<n_nationkey:smallint,n_name:string,n_comment:string>> | +-------------+--------------------------------------------------------------------+ To find the countries within a specific region, you use a join query. To find out the order of elements in the array, you also refer to the POS pseudocolumn in the select list: [localhost:21000] > SELECT r1.r_name, r2.n_name, r2.POS > FROM region r1 INNER JOIN r1.r_nations r2 > WHERE r1.r_name = 'ASIA'; +--------+-----------+-----+ | r_name | n_name | pos | +--------+-----------+-----+ | ASIA | VIETNAM | 0 | | ASIA | CHINA | 1 | | ASIA | JAPAN | 2 | | ASIA | INDONESIA | 3 | | ASIA | INDIA | 4 | +--------+-----------+-----+ Once you know the positions of the elements, you can use that information in subsequent queries, for example to change the ordering of results from the complex type column or to filter certain elements from the array: [localhost:21000] > SELECT r1.r_name, r2.n_name, r2.POS > FROM region r1 INNER JOIN r1.r_nations r2 > WHERE r1. ORDER BY r2.POS DESC; +--------+-----------+-----+ | r_name | n_name | pos | +--------+-----------+-----+ | ASIA | INDIA | 4 | | ASIA | INDONESIA | 3 | | ASIA | JAPAN | 2 | | ASIA | CHINA | 1 | | ASIA | VIETNAM | 0 | +--------+-----------+-----+ [localhost:21000] > SELECT r1.r_name, r2.n_name, r2.POS > FROM region r1 INNER JOIN r1.r_nations r2 > WHERE r1.r_name = 'ASIA' AND r2.POS BETWEEN 1 and 3; +--------+-----------+-----+ | r_name | n_name | pos | +--------+-----------+-----+ | ASIA | CHINA | 1 | | ASIA | JAPAN | 2 | | ASIA | INDONESIA | 3 | +--------+-----------+-----+ KEY and VALUE Pseudocolumns The MAP data type is suitable for representing sparse or wide data structures, where each row might only have entries for a small subset of named fields. Because the element names (the map keys) vary depending on the row, a query must be able to refer to both the key and the value parts of each key-value pair. The KEY and VALUE pseudocolumns let you refer to the parts of the key-value pair independently within the query, as map_column.KEY and map_column.VALUE. The KEY must always be a scalar type, such as STRING, BIGINT, or TIMESTAMP. It can be NULL. Values of the KEY field are not necessarily unique within the same MAP. You apply any required DISTINCT, GROUP BY, and other clauses in the query, and loop through the result set to process all the values matching any specified keys. The VALUE can be either a scalar type or another complex type. If the VALUE is a STRUCT, you can construct a qualified name map_column.VALUE.struct_field to refer to the individual fields inside the value part. If the VALUE is an ARRAY or another MAP, you must include another join condition that establishes a table alias for map_column.VALUE, and then construct another qualified name using that alias, for example table_alias.ITEM or table_alias.KEY and table_alias.VALUE The following example shows different ways to access a MAP column using the KEY and VALUE pseudocolumns. The DETAILS column has a STRING first part with short, standardized values such as 'Recurring', 'Lucid', or 'Anxiety'. This is the "key" that is used to look up particular kinds of elements from the MAP. The second part, also a STRING, is a longer free-form explanation. Impala gives you the standard pseudocolumn names KEY and VALUE for the two parts, and you apply your own conventions and interpretations to the underlying values. CREATE TABLE dream_journal ( dream_id BIGINT, details MAP <STRING,STRING> ) STORED AS PARQUET; -- What are all the types of dreams that are recorded? SELECT DISTINCT details.KEY FROM dream_journal, dream_journal.details; -- How many lucid dreams were recorded? -- Because there is no GROUP BY, we count the 'Lucid' keys across all rows. SELECT COUNT(details.KEY) FROM dream_journal, dream_journal.details WHERE details.KEY = 'Lucid'; -- Print a report of a subset of dreams, filtering based on both the lookup key -- and the detailed value. SELECT dream_id, details.KEY AS "Dream Type", details.VALUE AS "Dream Summary" FROM dream_journal, dream_journal.details WHERE details.KEY IN ('Happy', 'Pleasant', 'Joyous') AND details.VALUE LIKE '%childhood%'; The following example shows a more elaborate version of the previous table, where the VALUE part of the MAP entry is a STRUCT rather than a scalar type. Now instead of referring to the VALUE pseudocolumn directly, you use dot notation to refer to the STRUCT fields inside it. CREATE TABLE better_dream_journal ( dream_id BIGINT, details MAP <STRING,STRUCT <summary: STRING, when_happened: TIMESTAMP, duration: DECIMAL(5,2), woke_up: BOOLEAN> > ) STORED AS PARQUET; -- Do more elaborate reporting and filtering by examining multiple attributes within the same dream. SELECT dream_id, details.KEY AS "Dream Type", details.VALUE.summary AS "Dream Summary", details.VALUE.duration AS "Duration" FROM better_dream_journal, better_dream_journal.details WHERE details.KEY IN ('Anxiety', 'Nightmare') AND details.VALUE.duration > 60 AND details.VALUE.woke_up = TRUE; -- Remember that if the ITEM or VALUE contains a STRUCT, you can reference -- the STRUCT fields directly without the .ITEM or .VALUE qualifier. SELECT dream_id, details.KEY AS "Dream Type", details.summary AS "Dream Summary", details.duration AS "Duration" FROM better_dream_journal, better_dream_journal.details WHERE details.KEY IN ('Anxiety', 'Nightmare') AND details.duration > 60 AND details.woke_up = TRUE; Because the Impala INSERT statement does not currently support creating new data with complex type columns, or copying existing complex type values from one table to another, you primarily use Impala to query Parquet tables with complex types where the data was inserted through Hive, or create tables with complex types where you already have existing Parquet data files. If you have created a Hive table with the Parquet file format and containing complex types, use the same table for Impala queries with no changes. If you have such a Hive table in some other format, use a Hive CREATE TABLE AS SELECT ... STORED AS PARQUET or INSERT ... SELECT statement to produce an equivalent Parquet table that Impala can query. If you have existing Parquet data files containing complex types, located outside of any Impala or Hive table, such as data files created by Spark jobs, you can use an Impala CREATE TABLE ... STORED AS PARQUET statement, followed by an Impala LOAD DATA statement to move the data files into the table. As an alternative, you can use an Impala CREATE EXTERNAL TABLE statement to create a table pointing to the HDFS directory that already contains the data files. Perhaps the simplest way to get started with complex type data is to take a denormalized table containing duplicated values, and use an INSERT ... SELECT statement to copy the data into a Parquet table and condense the repeated values into complex types. With the Hive INSERT statement, you use the COLLECT_LIST(), NAMED_STRUCT(), and MAP() constructor functions within a GROUP BY query to produce the complex type values. COLLECT_LIST() turns a sequence of values into an ARRAY. NAMED_STRUCT() uses the first, third, and so on arguments as the field names for a STRUCT, to match the field names from the CREATE TABLE statement. Using Complex Types as Nested Types The ARRAY, STRUCT, and MAP types can be the top-level types for "nested type" columns. That is, each of these types can contain other complex or scalar types, with multiple levels of nesting to a maximum depth of 100. For example, you can have an array of structures, a map containing other maps, a structure containing an array of other structures, and so on. At the lowest level, there are always scalar types making up the fields of a STRUCT, elements of an ARRAY, and keys and values of a MAP. Schemas involving complex types typically use some level of nesting for the complex type columns. For example, to model a relationship like a dimension table and a fact table, you typically use an ARRAY where each array element is a STRUCT. The STRUCT fields represent what would traditionally be columns in a separate joined table. It makes little sense to use a STRUCT as the top-level type for a column, because you could just make the fields of the STRUCT into regular table columns. Perhaps the only use case for a top-level STRUCT would be to to allow STRUCT fields with the same name as columns to coexist in the same table. The following example shows how a table could have a column named ID, and two separate STRUCT fields also named ID. Because the STRUCT fields are always referenced using qualified names, the identical ID names do not cause a conflict. CREATE TABLE struct_namespaces ( id BIGINT , s1 STRUCT < id: BIGINT, field1: STRING > , s2 STRUCT < id: BIGINT, when_happened: TIMESTAMP > ) STORED AS PARQUET; select id, s1.id, s2.id from struct_namespaces; It is common to make the value portion of each key-value pair in a MAP a STRUCT, ARRAY of STRUCT, or other complex type variation. That way, each key in the MAP can be associated with a flexible and extensible data structure. The key values are not predefined ahead of time (other than by specifying their data type). Therefore, the MAP can accommodate a rapidly evolving schema, or sparse data structures where each row contains only a few data values drawn from a large set of possible choices. Although you can use an ARRAY of scalar values as the top-level column in a table, such a simple array is typically of limited use for analytic queries. The only property of the array elements, aside from the element value, is the ordering sequence available through the POS pseudocolumn. To record any additional item about each array element, such as a TIMESTAMP or a symbolic name, you use an ARRAY of STRUCT rather than of scalar values. If you are considering having multiple ARRAY or MAP columns, with related items under the same position in each ARRAY or the same key in each MAP, prefer to use a STRUCT to group all the related items into a single ARRAY or MAP. Doing so avoids the additional storage overhead and potential duplication of key values from having an extra complex type column. Also, because each ARRAY or MAP that you reference in the query SELECT list requires an additional join clause, minimizing the number of complex type columns also makes the query easier to read and maintain, relying more on dot notation to refer to the relevant fields rather than a sequence of join clauses. For example, here is a table with several complex type columns all at the top level and containing only scalar types. To retrieve every data item for the row requires a separate join for each ARRAY or MAP column. The fields of the STRUCT can be referenced using dot notation, but there is no real advantage to using the STRUCT at the top level rather than just making separate columns FIELD1 and FIELD2. CREATE TABLE complex_types_top_level ( id BIGINT, a1 ARRAY<INT>, a2 ARRAY<STRING>, s STRUCT<field1: INT, field2: STRING>, -- Numeric lookup key for a string value. m1 MAP<INT,STRING>, -- String lookup key for a numeric value. m2 MAP<STRING,INT> ) STORED AS PARQUET; describe complex_types_top_level; +------+-----------------+ | name | type | +------+-----------------+ | id | bigint | | a1 | array<int> | | a2 | array<string> | | s | struct< | | | field1:int, | | | field2:string | | | > | | m1 | map<int,string> | | m2 | map<string,int> | +------+-----------------+ select id, a1.item, a2.item, s.field1, s.field2, m1.key, m1.value, m2.key, m2.value from complex_types_top_level, complex_types_top_level.a1, complex_types_top_level.a2, complex_types_top_level.m1, complex_types_top_level.m2; For example, here is a table with columns containing an ARRAY of STRUCT, a MAP where each key value is a STRUCT, and a MAP where each key value is an ARRAY of STRUCT. CREATE TABLE nesting_demo ( user_id BIGINT, family_members ARRAY < STRUCT < name: STRING, email: STRING, date_joined: TIMESTAMP >>, foo map < STRING, STRUCT < f1: INT, f2: INT, f3: TIMESTAMP, f4: BOOLEAN >>, gameplay MAP < STRING , ARRAY < STRUCT < name: STRING, highest: BIGINT, lives_used: INT, total_spent: DECIMAL(16,2) >>> ) STORED AS PARQUET; The DESCRIBE statement rearranges the < and > separators and the field names within each STRUCT for easy readability: DESCRIBE nesting_demo; +----------------+-----------------------------+ | name | type | +----------------+-----------------------------+ | user_id | bigint | | family_members | array<struct< | | | name:string, | | | email:string, | | | date_joined:timestamp | | | >> | | foo | map<string,struct< | | | f1:int, | | | f2:int, | | | f3:timestamp, | | | f4:boolean | | | >> | | gameplay | map<string,array<struct< | | | name:string, | | | highest:bigint, | | | lives_used:int, | | | total_spent:decimal(16,2) | | | >>> | +----------------+-----------------------------+ To query the complex type columns, you use join notation to refer to the lowest-level scalar values. If the value is an ARRAY element, the fully qualified name includes the ITEM pseudocolumn. If the value is inside a MAP, the fully qualified name includes the KEY or VALUE pseudocolumn. Each reference to a different ARRAY or MAP (even if nested inside another complex type) requires an additional join clause. SELECT -- The lone scalar field doesn't require any dot notation or join clauses. user_id -- Retrieve the fields of a STRUCT inside an ARRAY. -- The FAMILY_MEMBERS name refers to the FAMILY_MEMBERS table alias defined later in the FROM clause. , family_members.item.name , family_members.item.email , family_members.item.date_joined -- Retrieve the KEY and VALUE fields of a MAP, with the value being a STRUCT consisting of more fields. -- The FOO name refers to the FOO table alias defined later in the FROM clause. , foo.key , foo.value.f1 , foo.value.f2 , foo.value.f3 , foo.value.f4 -- Retrieve the KEY fields of a MAP, and expand the VALUE part into ARRAY items consisting of STRUCT fields. -- The GAMEPLAY name refers to the GAMEPLAY table alias defined later in the FROM clause (referring to the MAP item). -- The GAME_N name refers to the GAME_N table alias defined later in the FROM clause (referring to the ARRAY -- inside the MAP item's VALUE part.) , gameplay.key , game_n.name , game_n.highest , game_n.lives_used , game_n.total_spent FROM nesting_demo , nesting_demo.family_members AS family_members , nesting_demo.foo AS foo , nesting_demo.gameplay AS gameplay , nesting_demo.gameplay.value AS game_n; Once you understand the notation to refer to a particular data item in the SELECT list, you can use the same qualified name to refer to that data item in other parts of the query, such as the WHERE clause, ORDER BY or GROUP BY clauses, or calls to built-in functions. For example, you might frequently retrieve the VALUE part of each MAP item in the SELECT list, while choosing the specific MAP items by running comparisons against the KEY part in the WHERE clause. Accessing Complex Type Data in Flattened Form Using Views The layout of complex and nested types is largely a physical consideration. The complex type columns reside in the same data files rather than in separate normalized tables, for your convenience in managing related data sets and performance in querying related data sets. You can use views to treat tables with complex types as if they were flattened. By putting the join logic and references to the complex type columns in the view definition, you can query the same tables using existing queries intended for tables containing only scalar columns. This technique also lets you use tables with complex types with BI tools that are not aware of the data types and query notation for accessing complex type columns. For example, the variation of the TPC-H schema containing complex types has a table REGION. This table has 5 rows, corresponding to 5 regions such as NORTH AMERICA and AFRICA. Each row has an ARRAY column, where each array item is a STRUCT containing details about a country in that region. DESCRIBE region; +-------------+-------------------------+ | name | type | +-------------+-------------------------+ | r_regionkey | smallint | | r_name | string | | r_comment | string | | r_nations | array<struct< | | | n_nationkey:smallint, | | | n_name:string, | | | n_comment:string | | | >> | +-------------+-------------------------+ The same data could be represented in traditional denormalized form, as a single table where the information about each region is repeated over and over, alongside the information about each country. The nested complex types let us avoid the repetition, while still keeping the data in a single table rather than normalizing across multiple tables. To use this table with a JDBC or ODBC application that expected scalar columns, we could create a view that represented the result set as a set of scalar columns (three columns from the original table, plus three more from the STRUCT fields of the array elements). In the following examples, any column with an R_* prefix is taken unchanged from the original table, while any column with an N_* prefix is extracted from the STRUCT inside the ARRAY. CREATE VIEW region_view AS SELECT r_regionkey, r_name, r_comment, array_field.item.n_nationkey AS n_nationkey, array_field.item.n_name AS n_name, array_field.n_comment AS n_comment FROM region, region.r_nations AS array_field; Then we point the application queries at the view rather than the original table. From the perspective of the view, there are 25 rows in the result set, one for each nation in each region, and queries can refer freely to fields related to the region or the nation. -- Retrieve info such as the nation name from the original R_NATIONS array elements. select n_name from region_view where r_name in ('EUROPE', 'ASIA'); +----------------+ | n_name | +----------------+ | UNITED KINGDOM | | RUSSIA | | ROMANIA | | GERMANY | | FRANCE | | VIETNAM | | CHINA | | JAPAN | | INDONESIA | | INDIA | +----------------+ -- UNITED STATES in AMERICA and UNITED KINGDOM in EUROPE. SELECT DISTINCT r_name FROM region_view WHERE n_name LIKE 'UNITED%'; +---------+ | r_name | +---------+ | AMERICA | | EUROPE | +---------+ -- For conciseness, we only list some view columns in the SELECT list. -- SELECT * would bring back all the data, unlike SELECT * -- queries on the original table with complex type columns. SELECT r_regionkey, r_name, n_nationkey, n_name FROM region_view LIMIT 7; +-------------+--------+-------------+----------------+ | r_regionkey | r_name | n_nationkey | n_name | +-------------+--------+-------------+----------------+ | 3 | EUROPE | 23 | UNITED KINGDOM | | 3 | EUROPE | 22 | RUSSIA | | 3 | EUROPE | 19 | ROMANIA | | 3 | EUROPE | 7 | GERMANY | | 3 | EUROPE | 6 | FRANCE | | 2 | ASIA | 21 | VIETNAM | | 2 | ASIA | 18 | CHINA | +-------------+--------+-------------+----------------+ Tutorials and Examples for Complex Types The following examples illustrate the query syntax for some common use cases involving complex type columns. Sample Schema and Data for Experimenting with Impala Complex Types The tables used for earlier examples of complex type syntax are trivial ones with no actual data. The more substantial examples of the complex type feature use these tables, adapted from the schema used for TPC-H testing: SHOW TABLES; +----------+ | name | +----------+ | customer | | part | | region | | supplier | +----------+ DESCRIBE customer; +--------------+------------------------------------+ | name | type | +--------------+------------------------------------+ | part; +---------------+---------------+ | name | type | +---------------+---------------+ | p_partkey | bigint | | p_name | string | | p_mfgr | string | | p_brand | string | | p_type | string | | p_size | int | | p_container | string | | p_retailprice | decimal(12,2) | | p_comment | string | +---------------+---------------+ DESCRIBE region; +-------------+--------------------------------------------------------------------+ | name | type | +-------------+--------------------------------------------------------------------+ | r_regionkey | smallint | | r_name | string | | r_comment | string | | r_nations | array<struct<n_nationkey:smallint,n_name:string,n_comment:string>> | +-------------+--------------------------------------------------------------------+ DESCRIBE supplier; +-------------+----------------------------------------------+ | name | type | +-------------+----------------------------------------------+ | s_suppkey | bigint | | s_name | string | | s_address | string | | s_nationkey | smallint | | s_phone | string | | s_acctbal | decimal(12,2) | | s_comment | string | | s_partsupps | array<struct<ps_partkey:bigint, | | | ps_availqty:int,ps_supplycost:decimal(12,2), | | | ps_comment:string>> | +-------------+----------------------------------------------+ The volume of data used in the following examples is: SELECT count(*) FROM customer; +----------+ | count(*) | +----------+ | 150000 | +----------+ SELECT count(*) FROM part; +----------+ | count(*) | +----------+ | 200000 | +----------+ SELECT count(*) FROM region; +----------+ | count(*) | +----------+ | 5 | +----------+ SELECT count(*) FROM supplier; +----------+ | count(*) | +----------+ | 10000 | +----------+ Constructing Parquet Files with Complex Columns Using Hive The following examples demonstrate the Hive syntax to transform flat data (tables with all scalar columns) into Parquet tables where Impala can query the complex type columns. Each example shows the full sequence of steps, including switching back and forth between Impala and Hive. Although the source table can use any file format, the destination table must use the Parquet file format. Create table an ARRAY column. Then Impala can run analytic queries on the Parquet table, using join notation to unpack the ARRAY column. /* Initial DDL and loading of flat, denormalized data happens in impala-shell */CREATE TABLE flat_array (country STRING, city STRING);INSERT INTO flat_array VALUES ( complex_array (country STRING, city ARRAY <STRING>) STORED AS PARQUET; /* Conversion to Parquet and complex and/or nested columns happens in Hive */ INSERT INTO complex_array SELECT country, collect_list(city) FROM flat_array GROUP BY country; Query ID = dev_20151108160808_84477ff2-82bd-4ba4-9a77-554fa7b8c0cb Total jobs = 1 Launching Job 1 out of 1 ... /* Back to impala-shell again for analytic queries */ REFRESH complex_array; SELECT country, city.item FROM complex_array, complex_array.city +---------+-------------+ | country | item | +---------+-------------+ | with STRUCT a STRUCT column with an ARRAY field. Then Impala can run analytic queries on the Parquet table, using join notation to unpack the ARRAY field from the STRUCT column. /* Initial DDL and loading of flat, denormalized data happens in impala-shell */ CREATE TABLE flat_struct_array (continent STRING, country STRING, city STRING); INSERT INTO flat_struct_array VALUES ('); CREATE TABLE complex_struct_array (continent STRING, country STRUCT <name: STRING, city: ARRAY <STRING> >) STORED AS PARQUET; /* Conversion to Parquet and complex and/or nested columns happens in Hive */ INSERT INTO complex_struct_array SELECT continent, named_struct('name', country, 'city', collect_list(city)) FROM flat_array_array GROUP BY continent, country; Query ID = dev_20151108163535_11a4fa53-0003-4638-97e6-ef13cdb8e09e Total jobs = 1 Launching Job 1 out of 1 ... /* Back to impala-shell again for analytic queries */ REFRESH complex_struct_array; SELECT t1.continent, t1.country.name, t2.item FROM complex_struct_array t1, t1.country.city t2 +---------------+--------------+-------------+ | continent | country.name | item | +---------------+--------------+-------------+ | | +---------------+--------------+-------------+ Flattening Normalized Tables into a Single Table with Complex Types One common use for complex types is to embed the contents of one table into another. The traditional technique of denormalizing results in a huge number of rows with some column values repeated over and over. With complex types, you can keep the same number of rows as in the original normalized table, and put all the associated data from the other table in a single new column. In this flattening scenario, you might frequently use a column that is an ARRAY consisting of STRUCT elements, where each field within the STRUCT corresponds to a column name from the table that you are combining. The following example shows a traditional normalized layout using two tables, and then an equivalent layout using complex types in a single table. /* Traditional relational design */ -- This table just stores numbers, allowing us to look up details about the employee -- and details about their vacation time using a three-table join query. CREATE table employee_vacations ( employee_id BIGINT, vacation_id BIGINT ) STORED AS PARQUET; -- Each kind of information to track gets its own "fact table". CREATE table vacation_details ( vacation_id BIGINT, vacation_start TIMESTAMP, duration INT ) STORED AS PARQUET; -- Any time we print a human-readable report, we join with this table to -- display info about employee #1234. CREATE TABLE employee_contact ( employee_id BIGINT, name STRING, address STRING, phone STRING, email STRING, address_type STRING /* 'home', 'work', 'remote', etc. */ ) STORED AS PARQUET; /* Equivalent flattened schema using complex types */ -- For analytic queries using complex types, we can bundle the dimension table -- and multiple fact tables into a single table. CREATE TABLE employee_vacations_nested_types ( -- We might still use the employee_id for other join queries. -- The table needs at least one scalar column to serve as an identifier -- for the complex type columns. employee_id BIGINT, -- Columns of the VACATION_DETAILS table are folded into a STRUCT. -- We drop the VACATION_ID column because Impala doesn't need -- synthetic IDs to join a complex type column. -- Each row from the VACATION_DETAILS table becomes an array element. vacation ARRAY < STRUCT < vacation_start: TIMESTAMP, duration: INT >>, -- The ADDRESS_TYPE column, with a small number of predefined values that are distinct -- for each employee, makes the EMPLOYEE_CONTACT table a good candidate to turn into a MAP, -- with each row represented as a STRUCT. The string value from ADDRESS_TYPE becomes the -- "key" (the anonymous first field) of the MAP. contact MAP < STRING, STRUCT < address: STRING, phone: STRING, email: STRING >> ) STORED AS PARQUET; Interchanging Complex Type Tables and Data Files with Hive and Other Components You can produce Parquet data files through several Hadoop components and APIs, as explained in Using Apache Parquet Data Files with CDH. If you have a Hive-created Parquet table that includes ARRAY, STRUCT, or MAP columns, Impala can query that same table in CDH 5.5 / Impala 2.3 and higher, subject to the usual restriction that all other columns are of data types supported by Impala, and also that the file type of the table must be Parquet. If you have a Parquet data file produced outside of Impala, Impala can automatically deduce the appropriate table structure using the syntax CREATE TABLE ... LIKE PARQUET 'hdfs_path_of_parquet_file'. In CDH 5.5 / Impala 2.3 and higher, this feature works for Parquet files that include ARRAY, STRUCT, or MAP types. /* In impala-shell, find the HDFS data directory of the original table. DESCRIBE FORMATTED tpch_nested_parquet.customer; ... | Location: | hdfs://localhost:20500/test-warehouse/tpch_nested_parquet.db/customer | NULL | ... # In the Unix shell, find the path of any Parquet data file in that HDFS directory. $ hdfs dfs -ls hdfs://localhost:20500/test-warehouse/tpch_nested_parquet.db/customer Found 4 items -rwxr-xr-x 3 dev supergroup 171298918 2015-09-22 23:30 hdfs://localhost:20500/blah/tpch_nested_parquet.db/customer/000000_0 ... /* Back in impala-shell, use the HDFS path in a CREATE TABLE LIKE PARQUET statement. */ CREATE TABLE customer_ctlp LIKE PARQUET 'hdfs://localhost:20500/blah/tpch_nested_parquet.db/customer/000000_0' STORED AS PARQUET; /* Confirm that old and new tables have the same column layout, including complex types. */ DESCRIBE tpch_nested_parquet.customer +--------------+------------------------------------+---------+ | name | type | comment | +--------------+------------------------------------+---------+ | customer_ctlp; +--------------+------------------------------------+-----------------------------+ | name | type | comment | +--------------+------------------------------------+-----------------------------+ | c_custkey | bigint | Inferred from Parquet file. | | c_name | string | Inferred from Parquet file. | | c_address | string | Inferred from Parquet file. | | c_nationkey | int | Inferred from Parquet file. | | c_phone | string | Inferred from Parquet file. | | c_acctbal | decimal(12,2) | Inferred from Parquet file. | | c_mktsegment | string | Inferred from Parquet file. | | c_comment | string | Inferred from Parquet file. | | c_orders | array<struct< | Inferred from Parquet file. | | | | | | | >> | | | | >> | | +--------------+------------------------------------+-----------------------------+
https://docs.cloudera.com/documentation/enterprise/6/6.1/topics/impala_complex_types.html
CC-MAIN-2020-05
refinedweb
10,521
50.67
C++ Get name of type in template I'm writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like: Error parsing example.txt. Value ("notaninteger")of [MySectiom]Key is not a valid int I can work out the file, section and key names from the arguments passed to the template function and member vars in the class, however I'm not sure how to get the name of the type the template function is trying to convert to. My current code looks like, with specialisations for just plain strings and such: template<typename T> T GetValue(const std::wstring §ion, const std::wstring &key) { std::map<std::wstring, std::wstring>::iterator it = map[section].find(key); if(it == map[section].end()) throw ItemDoesNotExist(file, section, key) else { try{return boost::lexical_cast<T>(it->second);} //needs to get the name from T somehow catch(...)throw ParseError(file, section, key, it->second, TypeName(T)); } } Id rather not have to make specific overloads for every type that the data files might use, since there are loads of them... Also I need a solution that does not incur any runtime overhead unless an exception occurs, i.e. a completely compile time solution is what I want since this code is called tons of times and load times are already getting somewhat long. EDIT: Ok this is the solution I came up with: I have a types.h containg the following #pragma once template<typename T> const wchar_t *GetTypeName(); #define DEFINE_TYPE_NAME(type, name) \ template<>const wchar_t *GetTypeName<type>(){return name;} Then I can use the DEFINE_TYPE_NAME macro to in cpp files for each type I need to deal with (eg in the cpp file that defined the type to start with). The linker is then able to find the appropirate template specialisation as long as it was defined somewhere, or throw a linker error otherwise so that I can add the type. Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like: template<typename T> struct TypeParseTraits; #define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \ { static const char* name; } ; const char* TypeParseTraits<X>::name = #X REGISTER_PARSE_TYPE(int); REGISTER_PARSE_TYPE(double); REGISTER_PARSE_TYPE(FooClass); // etc... And then use it like throw ParseError(TypeParseTraits<T>::name); EDIT: You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable. C, "C" is one of the most widely used programming languages of all time. Prof Brian Kernighan Duration: 8:26 Posted: 18 Aug 2015 This is a list of operators in the C and C++ programming languages.All the operators listed exist in C++; the fourth column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading. The solution is typeid(T).name() which returns std::type_info. Why C is so Influential - Computerphile, This course will give you a full introduction into all of the core concepts in the C programming Duration: 3:46:13 Posted: 15 Aug 2018 C programming 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. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity typeid(T).name() is implementation defined and doesn't guarantee human readable string. Reading cppreference.com : Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program. ... With compilers such as gcc and clang, the returned string can be piped through c++filt -t to be converted to human-readable form. But in some cases gcc doesn't return right string. For example on my machine I have gcc whith -std=c++11 and inside template function typeid(T).name() returns "j" for "unsigned int". It's so called mangled name. To get real type name, use abi::__cxa_demangle() function (gcc only): #include <string> #include <cstdlib> #include <cxxabi.h> template<typename T> std::string type_name() { int status; std::string tname = typeid(T).name(); char *demangled_name = abi::__cxa_demangle(tname.c_str(), NULL, NULL, &status); if(status == 0) { tname = demangled_name; std::free(demangled_name); } return tname; } "C" Programming Language: Brian Kernighan, C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone� C provides a compound assignment operator for each binary arithmetic and bitwise operation (i.e. each operation which accepts two operands). Each of the compound bitwise assignment operators perform the appropriate binary operation and store the result in the left operand. As mentioned by Bunkar typeid(T).name is implementation defined. To avoid this issue you can use Boost.TypeIndex library. For example: boost::typeindex::type_id<T>().pretty_name() // human readable C Programming Tutorial for Beginners, C is a powerful general-purpose programming language. Our C tutorials will guide you to learn C programming one step at a time with the help of examples. C or Do is the first note of the C major scale, the third note of the A minor scale (the relative minor of C major), and the fourth note (F, A, B, C) of the Guidonian hand, commonly pitched around 261.63 Hz. The answer of Logan Capaldo is correct but can be marginally simplified because it is unnecessary to specialize the class every time. One can write: // in header template<typename T> struct TypeParseTraits { static const char* name; }; // in c-file #define REGISTER_PARSE_TYPE(X) \ template <> const char* TypeParseTraits<X>::name = #X REGISTER_PARSE_TYPE(int); REGISTER_PARSE_TYPE(double); REGISTER_PARSE_TYPE(FooClass); // etc... This also allows you to put the REGISTER_PARSE_TYPE instructions in a C++ file... C Tutorial, C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of� Learn C# programming - for beginning developers, developers new to C#, and experienced C# / .NET developers Learn C Programming, learn-c.org is a free interactive C tutorial for people who want to learn C, fast. Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc. Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies. What is C?, C-SPAN.org gives you access to C-SPAN's daily coverage of Washington and more than 200,000 hours of extensively indexed and archived C-SPAN video. C Programming: Getting Started, Microsoft C++, C, and Assembler documentation. Learn how to use C++, C, and assembly language to develop applications, services, and tools for your platforms and devices. - not really relevant to your question, but you might want to use map.find(section) when accessing the section aswell, unless you intentionally want to create an empty section. - Note: This code will not compile if you forget to define REGISTER_PARSE_TYPE for a type that you use. I have used a similar trick before (in code without RTTI) and it has worked very well. - I had to move name outside of the struct in g++ 4.3.0 due to "error: invalid in-class initialization of static data member of non-integral type 'const char *'"; and, of course, the keyword 'struct' is needed between <> and TypeParseTraits and the definition should be terminated with a semicolon. - Well the leaving the semicolon out was intentional, to force you to use it at the end of the macro invocation, but thanks for the corrections. - I obtain the folllowing error: error: '#' is not followed by a macro parameter - @kratsg - that's because at the end '#x' should be '#X' (uppercase to match macro parameter) - I'll fix the answer. - Keep in mind that it's compliant to return the same string for every type (though I don't think any compiler would do that). - Or to return a different string for the same type on different executions... (again not that I think that any sane compiler would do that). - I'd just like to point out how ugly the given name can be: typeid(simd::double3x4).name() = "N4simd9double3x4E". typeid(simd::float4).name() = "Dv4_f"C++17, Xcode 10.1. - Indeed. typeid(T).name()is the canonical way to do this, but very few compilers return unmangled names; the only one I'm personally familiar with that does so is MSVC. Depending on the compiler used, there's also a chance that it may lose some type information on function types, but that's probably irrelevant in this case. - Isn't it memory leak to have freein if? - No, because the pointer points to nullptrif the status is not 0. - I'd like to add that it's probably best to check for gcc or clang's existence and if not default to not doing the demangling as shown here.
https://thetopsites.net/article/59522794.shtml
CC-MAIN-2021-25
refinedweb
1,570
53.21
Please welcome a new Early Access Preview build for WebStorm 2017.1 (171.2272.15)! You can download it here and install it side-by-side with your current stable WebStorm version, or if you have the previous EAP build, you should soon get a notification in the IDE about a patch update. Completion for dependencies in package.json Adding new project dependencies to package.json became easier: WebStorm now provides code completion for package names and shows info about the latest versions. Support for JavaScript Standard Style WebStorm now adds support for JavaScript Standard Style, a popular JavaScript code style. Now you can configure WebStorm code style options for JavaScript to follow the main rules Standard declares and they will be applied when you type the code or reformat it. For that go to Preferences | Editor | Code style | JavaScript and click Set from Predefined Style – Standard and the style will replace your current scheme. Since Standard is based on ESLint, you can use Standard via WebStorm’s ESLint integration. If you open a new project and Standard is listed in package.json, WebStorm will notice that and will enable linting with Standard automatically. WebStorm will also suggest to set Standard code style for formatting (also if you have ESLint with Standard plugin). You can also enable Standard in the ESLint Preferences (Languages & Frameworks | JavaScript | Code quality tools | ESLint): you need to select a path to Standard package installed globally or locally in the, is there any eta when this: will hit beta release? PS. this is something for what most devs using docker was waiting for.. This fix should be available in this Early access preview build. The stable release is planned for March or April. Please let us know if you experience any issues with that on Thanks! If used with the postcss plugin you cannot open TypeScript tsx files for example. Breaks the editor. We updated PostCSS plugin, please try to update in Preferences – Plugins. Please, please fix indentation in Angular 2 template strings. It’s annoying as hell having to manually enter tabs every time you edit a template string and using the fragment editor is even more annoying: Please, even VSCode has this working… We’re planning to work on it. Please follow the updates on Planning to work on it? Not even started and not even an ETA? I could understand it in 2015, when Angular 2 was still pretty new, but now we’re in 2017… This is so annoying I can’t stand it anymore. JFYI I personally know at least one developer who quitted Webstorm because of this. Guess what is he using now? VSCode. I tried really hard to push IJ and WS to our team last year. Now i start to regard the decision. Just take a look at this issue and how Jetbrains handled it, I will seriously try out VSCode tonight and push another tool change to our team…IJ might still have someplace for Java but Webstorm, maybe… I know, they are not that good handling bug reports… I still have dozens of them open. Keep in mind that VSCode lacks tons of features which Webstorm has, but I’m still giving it a chance because a bugged feature is no better than no feature at all. There are plenty of peoples evangelizing it at the moment, so who knows, maybe in the future… Fixed in EAP, many many thanks. Will there be support for nativescript cli? No, we don’t plan to support it out-of-the-box in WebStorm, but may be it will be implemented in the great NativeScript plugin. I would also recommend you to configure NativeScript CLI as an External tool. The configuration would be similar to this: Having the Google Code Style Guidelines as a preset would be also awesome. Please vote for this feature request: In MacOS in the terminal tab CTRL+C not working anymore. I can’t interrupt the process. After hitting CTRL+C it just inserts “new line” symbol in terminal. Thanks for letting us know. Seems to be this issue: Hope it will be fixed soon. Sorry for the inconvenience. After the installation is successful, the application cannot be opened What OS do you use? Have you installed WebStorm in a new folder or on-top of a previous installation? I have a problem, the standard don’t read config from package.json. Sometime, I want to ignore some file, or to format the .vue file. And the webstorm don’t work Please try WebStorm 2017.1.1 (now available as a Release candidate). This issues was solved in it. Hi, I think Webstorm’s language of “Specify the path to Standard package to use Standard Code Style” is incorrect/confusing? It should point to the eslint package that is installed during standard’s installation from npm as if I point it to node_modules/standard, there is an error as listed by the question on stackoverflow. thanks. actually, I apologize, the solution I listed above is if the user has a .eslint.rc in their project and webstorm, well eslint defaults to the nearest .eslint.rc. terribly sorry Hi Brian, the steps described in the blog post are correct – you need to specify the path to the Standard package. Some users have stumbled upon the issue similar to the one you’re referring to, but neither we nor the user were not able to reproduce it again. We have fixed some Standard-related issues in WebStorm 2017.1.2, please give it a try – it is now available as a Release candidate, will be released today or tomorrow. Hi Ekaterina, Apologies, Webstorm instructions are correct. I had an .eslint.rc in my project’s root from a previous project. Once I removed the legacy .eslint.rc, all was well. Thank you for the prompt reply. For anyone running into an issue with the new Standard Style support (Throwing Error: “ESLint initialization Error: Use of const in strict mode”): Make sure your node interpreter isn’t too old. I had a 0.10.x version in there and that caused Standard Style support to throw an error. Thanks for your comment! At the moment I’m having troubles with Standard Style support in conjunction with React. E.g. in a file defining a React component I need to import React from 'react', but Standard Style complains about: “‘React’ is defined but never used (no-unused-vars)”. The same goes for imports of other React components, let’s say import Button from './Button'which is then used in jsx syntax. Still Standard Style complains about the Button that is never used. I need to add, that when running Standard Style from the command line for the same file, there are no complaints (I used standard from my node_modules and it’s the same I pointed ESLint inside of Webstorm to)… How can this be resolved? Thanks for your comment. We have reproduced the problem and reported an issue that you can follow: Hope we’ll get it fixed very soon. Sorry for the inconvenience. I don’t understand why reformatting the code doesn’t follow the standard style. The code still keeps on complaining about things like react/jsx-tag-spacing? Please follow for updates
https://blog.jetbrains.com/webstorm/2017/01/webstorm-2017-1-eap-171-2272/
CC-MAIN-2019-35
refinedweb
1,218
73.47
connections SYNOPSIS #include <sys/socket.h> int listen(int socket, int backlog); DESCRIPTION argu- ment value of 0. A backlog argument of 0 may allow the socket to accept connections, in which case the length of the listen queue may be set to an implementa- tion-defined minimum value. The socket in use may require the process to have appropriate privi- leges to use the listen() function. RETURN VALUE Upon successful completions, listen() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error. ERRORS. EINVAL The socket has been shut down. ENOBUFS Insufficient resources are available in the system to complete the call. The following sections are informative. EXAMPLES None. APPLICATION USAGE None. RATIONALE None. FUTURE DIRECTIONS None. SEE ALSO .
http://www.linux-directory.com/man3/listen.shtml
crawl-003
refinedweb
125
50.73
Storing Secrets in Serverless Apps The general idea behind secrets is to store them outside of your codebase — don’t commit them to Git! And to make them available at runtime. There are many ways people tend to do this, some are less secure than others. This chapter is going to lay out the best practice for storing secrets and managing them across multiple environments. Store Secrets in AWS Parameter Store AWS Systems Manager Parameter Store (SSM) is an AWS service that lets you store configuration data and secrets as key-value pairs in a central place. The values can be stored as plain text or as encrypted data. When stored as encrypted data, the value is encrypted on write using your AWS KMS key, and decrypted on read. As an example, we are going to use SSM to store our Stripe secret key. Note that, Stripe gives us 2 keys: a live key and a test key. We are going to store: - The live key in the Production account’s SSM console. - The test key in the Development account’s SSM console. First go in to your Production account, and go to your Systems Manager console. Select Parameter Store from the left menu, and select Create parameter. Fill in: - Name: /stripeSecretKey/live - Description: Stripe secret key - live Select SecureString, and paste your live Stripe key in Value. Scroll to the bottom and hit Create parameter. The key is added. Then, switch to your Development account, and repeat the steps to add the test Stripe key with: - Name: /stripeSecretKey/test - Description: Stripe secret key - test Access SSM Parameter in Lambda Now to use our SSM parameters, we need to let Lambda function know which environment it is running in. We are going to pass the name of the stage to Lambda functions as environment variables. Update our serverless.yml. ... custom: ${file(../../serverless.common.yml):custom} provider: environment: stage: ${self:custom.stage} resourcesStage: ${self:custom.resourcesStage} notePurchasedTopicArn: Ref: NotePurchasedTopic iamRoleStatements: - ${file(../../serverless.common.yml):lambdaPolicyXRay} - Effect: Allow Action: - ssm:GetParameter Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/stripeSecretKey/*' ... We are granting Lambda functions permission to fetch and decrypt the SSM parameters. Next, we’ll add the parameter names in our config.js. const stage = process.env.stage; const adminPhoneNumber = "+14151234567"; const stageConfigs = { dev: { stripeKeyName: "/stripeSecretKey/test" }, prod: { stripeKeyName: "/stripeSecretKey/live" } }; const config = stageConfigs[stage] || stageConfigs.dev; export default { stage, adminPhoneNumber, ...config }; The above code reads the current stage from the environment variable process.env.stage, and selects the corresponding config. - If the stage is prod, it exports stageConfigs.prod. - If the stage is dev, it exports stageConfigs.dev. - And if stage is featureX, it falls back to the dev config and exports stageConfigs.dev. If you need a refresher on the structure of our config, refer to the Manage environment related config. Now we can access the SSM value in our Lambda function. import AWS from '../../libs/aws-sdk'; import config from "../../config"; // Load our secret key from SSM const ssm = new AWS.SSM(); const stripeSecretKeyPromise = ssm .getParameter({ Name: config.stripeKeyName, WithDecryption: true }) .promise(); export const handler = (event, context) => { ... // Charge via stripe const stripeSecretKey = await stripeSecretKeyPromise; const stripe = stripePackage(stripeSecretKey.Parameter.Value); ... }; By calling ssm.getParameter with WithDecryption: true, the value returned to you is decrypted and ready to be used. Note that, you want to decrypt your secrets outside your Lambda function handler. This is because you only need to do this once per Lambda function invocation. Your secrets will get decrypted on the first invocation and you’ll simply use the same value in subsequent invocations. So, in summary, you want to store your sensitive data in SSM. Store the SSM parameter name in your config. When the Lambda function runs, use the environment it’s running in to figure out which SSM parameter to use. Finally, decrypt the secret outside your Lambda handler function. Next, we’ll look at how we can setup our API Gateway custom domains to work across environments. For help and discussionComments on this chapter
https://serverless-stack.com/chapters/storing-secrets-in-serverless-apps.html
CC-MAIN-2021-04
refinedweb
674
59.8
The SV.STRBO.BOUND_COPY.OVERFLOW checker finds possible buffer overflows in bounded string copy operations strncpy, StrnCpy, safe_strcpy. When a buffer overflow happens during string copy operations, it overwrites adjacent memory. This leads to a violation of memory safety. To avoid such errors, destination buffer size should be properly calculated and the third parameter of bounded string copy functions should be less or equal to buffer size. 1 #include <string.h> 2 int main(int argc, char* argv[]){ 3 char foo[10]; 4 char bar[] = "this text is too long"; 5 strncpy(foo, bar, sizeof(bar)); 6 } Klocwork will report defect SV.STRBO.BOUND_COPY.OVERFLOW in line 5 because destination buffer size 10 is less than source buffer size 22. #include <string.h> int main(int argc, char* argv[]){ char foo[10]; char bar[] = "this text is too long"; strncpy(foo, bar, sizeof(foo)); } In this example, defect SV.STRBO.BOUND_COPY.OVERFLOW will not be reported because during the copy operation, source string will be trimmed to destination buffer size.
https://docs.roguewave.com/en/klocwork/current/sv.strbo.bound_copy.overflow
CC-MAIN-2019-18
refinedweb
170
54.42
Argument Passing in Ruby - Evaluation Strategies and Method Arguments - Argument Passing: Call-by-Value vs. Call-by-Reference - Language vs. Implementation - Call-by-Sharing - References A recurring discussion among Ruby programmers of all skill levels is the way that Ruby passes objects to methods. After a bit of time with Ruby, it becomes clear—sometimes painfully so—that when a method mutates its arguments, those changes are visible outside of the method. The following example (shown also in Figure 1) should trigger an unpleasant flashback to the point when you first realized this fact: def log_message (message) message << “at ” + Time.now.to_s $stdout.puts(message) end home = File.expand_path(“~”) log_message(home) # home is mutated. # This won't work as expected. Dir.entries(home) do |entry| # ... end The problem with this example code is obvious. The log_message method appends a string to its argument, which in turn affects the home variable as well. But this article isn't about the surprises encountered when objects are mutated; that's a topic I cover plenty of times in Effective Ruby: 48 Specific Ways to Write Better Ruby. [1] For the sake of our objective, let's figure out why it's even possible to modify a method's arguments in ways that are externally visible. - For convenience in following along with this discussion, download a zip file containing the complete source files for this article. Evaluation Strategies and Method Arguments Argument passing falls under the subject of expression evaluation. Most mainstream programming languages, but certainly not all, use eager evaluation. In the context of calling a method, this means that arguments are evaluated before a method's body begins executing. In Ruby it's fairly common to call methods and supply compound expressions instead of variable names. As an example, consider this call to the log_message method (Figure 2): log_message(“checking directory ” + dir) Prior to executing the log_message method, the Ruby interpreter will evaluate the expression given in the argument list. In this case, the expression creates a new string object that isn't bound to any variable. Then, just before the method executes, Ruby binds it to a local variable that is available inside the method body. This is the object of interest. Whether it's a complex expression or simply a variable name, we want to know how these values pass through the boundary between the caller's scope and the method's scope. To accomplish this task, we should nail down some terminology that will help us to distinguish between these two scopes. According to the Concise Encyclopedia of Computer Science, [2] when we define a method (using the def keyword) and name a method's arguments, those names are referred to as the method's formal arguments. In Ruby, formal arguments become local variables inside the body of a method. On the flip side, when we call a method, the values passed as arguments are known as a method's actual arguments. It's important to remember that in Ruby, values are always objects. Therefore, a method's actual arguments and its formal arguments are always objects. The confusing part is how those two are connected. “How do actual arguments get mapped into formal arguments?“ I'm glad you asked. Let's try to get to the bottom of this puzzle.
http://www.informit.com/articles/article.aspx?p=2301259&amp;seqNum=5
CC-MAIN-2017-09
refinedweb
552
55.64
Parent Directory | Revision Log Redirect council pages to wiki, bug 485448. Add missing log and summary for 20080515 meeting, bug 457000. Summary for 20130917 meeting. Log for 20130917 meeting. Add July 2013 summary Summary for 20130910 meeting. Log for 20130910 meeting. Summary for 20130813 meeting. Log for 20130813 meeting. add meeting log Meeting time is 19:00 UTC now. Add chairs. New council has been elected. Link to summary of the May meeting Log to June meeting Add meeting log from May meeting Summary for 20090122 meeting by betelgeuse, bug 457000. Summary for 20130409 meeting. Log for 20130409 meeting. Summary for 20130212 meeting, from grobian. Summary for 20130312 meeting. Log for 20130312 meeting. Add summary for 20090625 meeting, approved by council today. Alphabetic order. Add missing log for 20090122 meeting, thanks to dev-zero. Add missing log for 20090625 meeting. Add todays meeting log add 20130108 meeting's summary Add meeting log for todays meeting Add summary for 20121211 meeting Add today's meeting, and fill in meeting chairs for the rest of this period Add summary for 20121113 meeting Add 20121113 meeting log publish 20121009 summary add 20120911 meeting log Remove surplus item from table. Add summary for September meeting. Add IRC log for today's meeting. add meeting log for today's meeting Remove old voting logs. They are all available at the elections project pages. link latest meeting log and summary Fill in meeting chairs for as far known for this council 's term Update list of council members. Add summary and log from the last meeting Adding summary and log for today council's meeting. Added March 2012 summary Summary for April meeting. IRC log for April meeting. Adding IRC log for the March meeting Woops, forgot to add summary and logs. We didn't have any agenda items anyway. we meet at 20:00 UTC currently add 20120110's meeting log and summary Add missing '1' Add logs for December 16 meeting Switched the chairing of the January and May meetings by jmbsvicetto and grobian. Add summary for 20111108 meeting. Added 20111108 meeting information. add summary and logfile from yesterday's meeting Update index with council's last meeting. Update text about how meeting chairs get selected. Add table of meeting chairs for this council term. Update meeting day and slacker status Link to the log/summary. Added 20110715 council meeting summary and log. Update list of council members according to the council-201106 election result. Added log and summary for the 20110608 council meeting. Check in the summary for the 2011 May meeting. Added log for the council 20110510 meeting. Adding log and summary for the 20110408 council meeting. Update index with latest meeting/summary. Added summary and log for the 20110201 meeting. added 20110111 council meeting log and summary Adding self to council role Add halcy0ns slacker mark as required by council rules. Also fixes bug #350011. Added 20101218 meeting summary and updated index. Added 20101218 meeting log and updated index. added 20101130 council meeting log and summary 20101026 council meeting details and summary Removed double header in the meetings table. Added log and summary for the 20100927 council meeting. added log and summary for 2010-08-23 council meeting typo: 201000809 -> 20100809 added detailed information on meeting processes. bug #256453. added script that converts UTC time to local time with javascript. Add missing summary for meeting on 20091012. Fixes bug #256451. Add last meeting log + summary. add in summary links... surprised this isn't auto-generated... added log and summary for 2010-07-26 council meeting Dropped ulm from the AWOL column. Drop repeated header in the meeting logs table. Added log and summary for the 20100714 meeting. Updated the list of council members to reflect the result of the council-201006 election. Add raw log for June 14th council meeting Add raw log for May 17th council meeting Add raw log for April 19th council meeting Fixed link for meeting summary of 8 march 2010, again. Fixed link for meeting summary of 8 march 2010. Added meeting summary of 8 march 2010. Update current slacker status section Add raw log for March 8th council meeting Added summary of the council meeting of 20100208. Add raw log for February 8, 2010 meeting Added summary for 20100118 meeting. Add @self as council member, spotted when was looking for log from meeting :] Add raw log for January 18, 2010 meeting Added comments about when lu_zero received his slacker mark and lost his council seat. Add summary for 20091109 meeting. Add summary for December 7th meeting Removed lu_zero from the member list. Add entry for December 7th meeting log Add entry for November 9th meeting log Add election results from June 2009 Update meeting time to match reality - every fourth Monday, not every 3rd Monday of each month - at least until the reality is as such Add entry for October 12th meeting log Add summary for September\'s meeting. Add log from September 14 meeting, summary to be committed when approved. Fix participants list. Mark Luca Barbato as a slacker as he missed two meetings in a row. Add council log & summary from August 17 meeting. Forgot that lu_zero missed the 20090720 meeting. Added 20090720 log and summary. Updated meeting periodicity. Update council member list with the election results of 2009-06 Add 2008b election results. Add Council log and summary from meeting on June 11, 2009. Update list of members. Oops, Cardoe was present at 28 Jun's meeting. Fix. Add log and summary from meeting on 28 Jun 2009 Add Log and summary from meeting on May 14, 2009 Stop calling appeals process a draft; this is just documenting how it's been done, and it's been up here for a while. We also meet on 4th Thursdays. Add log and summary for meeting on April 23, 2009 Add log and summary for meeting on April 09, 2009 Add council log and summary from meeting on 03/26/09 Add summary and log for meeting on March 12, 2009 (#237381) First draft of appeals process. Put the council members to alphabetical order. halcy0n resigned from council and leio replaced him Add Council log and summary for meeting on February 26 2009 Add Council log and summary for meeting on December 11th, 2008 Add log and meeting summary for November 13, 2008 Add log and summary for 20090212. Replacing jokey by me correct the link to the 10/23/2008 meeting Add log and summary for 20081023 meeting. No slacker mark for lu_zero. He missed the meeting because of unexpected health issues. Add the last 2 months of meetings. Also fix a typo in my nick from a summary I didn't add. add Cardoe to council member list and replace flameeyes since flameeyes has retired and the council voted cardoe to take his seat during the Sept 11th 2008 meeting Add the summary/log from July 24th Add log and summary for 20080710 meeting. Add all the election results, graphs, etc. Update for 2008/2009 council members. Add log and summary for 20080612 meeting. linking nominees page from the main council page Add log and summary for 20080508 meeting. Add log and summary for 20080410 meeting. Add log and summary for 20080313 meeting. Add log and summary for 20080214 meeting. Add 20080110 meeting Added jokey. Removing uberlord from project pages as per #199318. Add 13 December meeting. Add 8 November meeting. Add 11 October meeting. fix meeting date as pointed out by tove add August 16th meeting and link in graphs for 2007 election Update on council elections Fix typo in jkt's commit. Note that the 2005 nominees listing included platforms. linking 2007 nominations Add the 2007/07/12 meeting logs and summary. #128615 #184875 Made XML valid to generate valid HTML from valid GuideXML Add 2007/06/14 summary. Add June 2007 stuff. Still needs a summary. -kloeri, +jaervosz archive May 10th meeting add 20070424 (multiple version suffixes) meeting logs April 12 2007 meeting Add resource link to the initial CoC document. Add summary and logs for the 20070315 special meeting about the CoC. UberLord showed up late to the March 2007 meeting add 20070308 meeting ... -Flameeyes +UberLord Remove 20070208 link to non-existant summary. update for todays meeting leave field empty rather than filling it with "none" for AWOL fix nicks fix links to jan 2007 meeting Document January 11 2007 meeting. document the november and december meetings add last meeting to the list update meeting times add summary for 20060914 Add meeting log for 14 September 2006 meeting. Fix typo in the index page. link in the ruby grapher scripts add some mailing list links fix copy & paste error for 2006-nominees list import 2006 results Add 20060817 meeting log - still needs a summary. add 2005 results add new council link in 2006 nominee list add item for July meeting fix the june date as pointed out by Ryan Hill june 16th meeting meeting give voting requirement its own bullet point slight tweak in voting timeline sentence fix link to council 2005 results restructure voting into bullet points, add some details about nominations, and clarify "eligible people" add previous nominees add a section on voting for the council alphabetize updates from april meeting fix date for next meeting meeting summary for the march meeting update for today's meeting update for jan meeting i can read a calendar, i swear ... update for december meeting update description of timing and Dec meeting date remove extraneous .txt add a link to the GLEP that formed the council add summary information add a bit more info/structure to the slacker table eat whitespace Updated for Nov meeting update with 20051013 log fix typo: meeting_logs -> meeting-logs Original page This form allows you to request diffs between any two revisions of this file. For each of the two "sides" of the diff, select a symbolic revision name using the selection box, or choose 'Use Text Field' and enter a numeric revision.
http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo/xml/htdocs/proj/en/council/index.xml?view=log
CC-MAIN-2014-52
refinedweb
1,669
66.54
Nov 06, 2013 07:39 AM|Ringoo|LINK Hi, I was taking a look at the classes in the System.Collections.Concurrent namespace. I was wondering if thread - safety is the only default feature provided with the classes in this namespace. Or is there anything in them that makes it possible for a developer to pick up different parts of them and process them in parallel. For instance, is there anything inherent about the ConcurrentDictionary<TKey, TValue> class that would make it easier for me to split a 1000 element instance of it into 10 parts and process each concurrently, in order to make processing faster? Please let me know. Ringoo System.Collections.Concurrent Nov 06, 2013 07:49 AM|Illeris|LINK Feature is perhaps not the best description for this. If it would not be thread-safe, it would simply not work in concurrent mode. Meaning that multiple operations in parallel in the same appdomain would cause issues, unless you write something around the collection classes in order to assure thread safety. For concurrent programming, you have the choice between multi-threading and the .NET parallel programming extensions (). Both have their advantages and disadvantages. For the example you give on splitting 1000 in parts of 10: do not assume it will go faster by default. Parallel execution on the same processor implies context switching. This also consumes resources. Apply this wisely ! System.Collections.Concurrent 1 reply Last post Nov 06, 2013 07:49 AM by Illeris
https://forums.asp.net/t/1948267.aspx
CC-MAIN-2019-39
refinedweb
247
56.86
Bugtraq mailing list archives ---------------[ MasterSecuritY <> ]--------------- ---------------[ Local root exploit in LBNL traceroute ]---------------- ----------[ By Michel "MaXX" Kaempf <maxx () mastersecurity fr> ]---------- --[ 0x00 - Table of contents ]------------------------------------------ 0x01 - Brief summary 0x02 - The problem 0x03 - Exploiting the problem 0x04 - The exploit 0x05 - Upgrading the exploit 0x06 - Fixes 0x07 - Credits 0x08 - References --[ 0x01 - Brief summary ]---------------------------------------------- Due to a wrong call to free(), LBNL (Lawrence Berkeley National Laboratory) traceroute can be exploited by a malicious local user in order to gain root access to the system. The vulnerability was discovered by Pekka Savola <pekkas () netcore fi>, first discussed by Chris Evans <chris () ferret lmh ox ac uk> on the security-audit[1] and bugtraq[2] lists, and finally exploited by Dvorak <dvorak () synnergy net> in his post to the bugtraq[3] list. I was working on the problem when Dvorak released his exploit to the bugtraq list. However, I decided to continue my own exploit, because I needed a simple and working exploit on both big and little endian architectures. --[ 0x02 - The problem ]------------------------------------------------ A vulnerable version of traceroute dies with a segmentation violation when running `traceroute -g 12 -g 42'. When looking closer at the traceroute sources, the guilty sequence appears to be: ... name = savestr("12"); ... free(name); ... name = savestr("42"); ... free(name); At this point, the segmentation fault occurs. The savestr() function is "a replacement for strdup() that cuts down on malloc() overhead". How does savestr() work internally, and why does the second call to free() end with a segmentation violation? When savestr("12") is called, a 1024 bytes buffer is allocated thanks to malloc(). The pointer returned by malloc() will be called p from now on. The "12" string is then stored at the beginning of this buffer, and the static pointer strptr is updated in order to point after this null terminated "12" string (i.e. strptr = p + strlen("12") + 1). savestr() finally returns the pointer p. When free() is called for the first time, the 1024 bytes buffer allocated thanks to malloc() and beginning at the pointer p is freed. When savestr("42") is called, the "42" string is stored in the previously freed 1024 bytes buffer, at the position described by the static pointer strptr (p + strlen("12") + 1). This is already a problem, but not an exploitable one. savestr() finally returns the pointer (p + strlen("12") + 1). When free() is called for the second time, it tries to free the buffer located at (p + strlen("12") + 1). Unfortunately, this pointer was not returned by malloc(), and that's why this call to free() dies with a segmentation fault. --[ 0x03 - Exploiting the problem ]------------------------------------- The second call to free() can be exploited. The malloc implementation used by most Linux systems is Doug Lea's malloc, and works as follows: - Free and allocated blocks of memory are described by "chunks", beginning at 8 bytes before the pointer returned to the user by malloc() or given by the user to free() (called mem in the picture below). - In the first 4 bytes of a chunk is stored the size of the previous chunk (called prev_size in the picture below), if allocated. - In the next 4 bytes is stored the size (in bytes) of the chunk itself (called size in the picture below), but the PREV_INUSE and IS_MMAPPED bits of this integer have special meanings. - Free chunks are stored in circular doubly-linked lists: the 4 bytes after size contain a forward pointer to the next chunk in the list (called fd in the picture below), and the next 4 bytes contain a back pointer to the previous chunk in the list (called bk in the picture below). +-----------+----------+----------+----------+-------------------------- | prev_size | size | fd | bk | ... +-----------+----------+----------+----------+-------------------------- ^ ^ chunk mem When running `traceroute -g 123 -g gateway host hell code', where gateway, host, hell and code are strings which will be described later, the second call to free(), discussed previously, will look like this: +-----------+----------+-----+-----+-----+------+----------------------- | prev_size | size | '1' | '2' | '3' | '\0' | ... +-----------+----------+-----+-----+-----+------+----------------------- ^ ^ ^ chunk p mem (the pointer given to free()) Fortunately, the four bytes before the pointer given to free() will in fact *not* be the four bytes of the null terminated string "123", but the binary IP address corresponding to gateway, because of a calloc() call in traceroute, between the second savestr() call and the second free() call. Nice. If this binary IP address is constructed so that the PREV_INUSE bit is set and the IS_MMAPPED bit is unset, the second call to free() will look like this: chunk = mem2chunk(mem); // equivalent to chunk = mem - 8, or chunk = p - 4 here if (chunk_is_mmapped(chunk)) { ... } // will not be executed since IS_MMAPPED is unset hd = chunk->size; sz = hd & ~PREV_INUSE; // PREV_INUSE is discarded when computing the real size of the chunk next = chunk_at_offset(chunk, sz); // equivalent to next = chunk + sz nextsz = chunksize(next); // equivalent to nextsz = next->size & ~(PREV_INUSE|IS_MMAPPED) if (!(hd & PREV_INUSE)) { ... } // will no be executed since PREV_INUSE is set if (!(inuse_bit_at_offset(next, nextsz))) { // equivalent to if (!( (next + nextsz)->size & PREV_INUSE )) { ... } // this block will be executed if the next chunk is built wisely... // *must* be executed, because it is where the exploit does the trick So, the next chunk has to be constructed wisely, and will be stored on the stack, thanks to the host argument given to traceroute. This host argument should also be padded in order to be aligned on the stack (processors like sparc always require alignment). The gateway argument should be chosen so that next points to the host argument on the stack, and so that PREV_INUSE is set and IS_MMAPPED is unset. Fortunately, if host is aligned on the stack, IS_MMAPPED will be unset, and PREV_INUSE can be set since free() discards this bit when computing the real size of the chunk. Finally, the hell and code arguments given to traceroute will contain the shellcode, and should be padded so that hell is aligned on the stack. Why was the shellcode separated into two parts? Well, read on :-) Now, how should the host argument be constructed, so that the block discussed previously will be executed? The host argument will look like this: AAAABBBBCCCCDDDDEEEEXXX BBBB will contain the prev_size of the next chunk, CCCC the size of the next chunk, DDDD the fd pointer and EEEE the bk pointer. XXX is used for padding, because if the argument following the host argument on the stack (hell) is 4 bytes aligned, host will also be 4 bytes aligned, thanks to this null terminated string "XXX". Finally, AAAA was added because these 4 bytes of the stack will be overwritten by free(). If CCCC (next->size) is equal to 0xffffffff, the call to inuse_bit_at_offset() discussed previously will be equivalent to (BBBB & PREV_INUSE). This test should fail, and that's why setting BBBB to (0xffffffff & ~PREV_INUSE) should do the trick. What else? Well, the DDDD and EEEE bytes, the fd and bk pointers... Once the inuse_bit_at_offset() test completed, free() runs the following macro: unlink(next, bck, fwd); Where unlink() looks like this: #define unlink(P, BK, FD) \ { \ BK = P->bk; \ FD = P->fd; \ FD->bk = BK; \ BK->fd = FD; \ } Wow, thanks to unlink(), a function pointer stored somewhere in the memory can be overwritten with a pointer to the shellcode... __free_hook is a nice one (thank you Solar Designer). After unlink(), the next call to free() should execute the shellcode and lead to root. The fd and bk pointers should be built carefully. The memory address given by ((unsigned int *)fd)[3] will be overwritten with the memory address given by bk, that's why setting fd to (&__free_hook - 12) and bk to the address of the hell argument on the stack is a good choice. But, because there is always a but, the memory address given by ((unsigned int *)bk)[2] (i.e. the bytes 8, 9, 10 and 11 of the shellcode) will also be overwritten. That's why the beginning of the shellcode should jump these 4 garbage bytes. This is easy on i386 architectures, where one byte can be used for the jump instruction, and one byte for the number of bytes to be jumped. On sparc processors, 4 bytes are needed for the jump instruction and the number of 4 bytes blocks to be jumped, and the next 4 bytes should describe a nop instruction, because of the sparc pipeline. But the number of 4 bytes blocks to be jumped will contain a null byte, and that's impossible: the shellcode is a string, and a null byte in a string corresponds to a string terminator. The solution? The following exploit divides the shellcode into two parts, hell and code, so that the null byte terminator of the hell string can be used as part of the sparc jump instruction. And for architectures where this null byte is not required, the jump instruction located in the hell argument will automagically skip the hell null byte terminator. --[ 0x04 - The exploit ]------------------------------------------------ /* * MasterSecuritY <> * * traceroot.c - Local root exploit in LBNL traceroute * Copyright (C) 2000 Michel "MaXX" Kaempf <maxx () mastersecurity fr> * * Updated versions of this exploit and the corresponding advisory will * be made <string.h> #include <unistd.h> #define PREV_INUSE 0x1 #define IS_MMAPPED 0x2 #define i386_linux \ /* setuid( 0 ); */ \ "\x31\xdb\x89\xd8\xb0\x17\xcd\x80" \ /* setgid( 0 ); */ \ "\x31\xdb\x89\xd8\xb0\x2e\xcd\x80" \ /* Aleph" #define sparc_linux \ /* setuid( 0 ); */ \ "\x90\x1a\x40\x09\x82\x10\x20\x17\x91\xd0\x20\x10" \ /* setgid( 0 ); */ \ "\x90\x1a\x40\x09\x82\x10\x20\x2e\x91\xd0\x20\x10" \ /* Aleph One :) */ \ "d0\x23\xbf\xf8\xc0\x23\xbf\xfc\x82\x10\x20\x3b\x91\xd0\x20\x10" struct arch { char * description; char * filename; unsigned int stack; char * hell; char * code; unsigned int p; unsigned int __free_hook; }; struct arch archlist[] = { { "Debian GNU/Linux 2.2 (traceroute 1.4a5-2) i386", "/usr/sbin/traceroute", 0xc0000000 - 4, "\xeb\x0aXXYYYYZZZ", i386_linux, 0x0804ce38, 0x400f1cd8 }, { "Debian GNU/Linux 2.2 (traceroute 1.4a5-2) sparc", "/usr/sbin/traceroute", 0xf0000000 - 8, "\x10\x80", "\x03\x01XXXYYYY" sparc_linux, 0x00025598, 0x70152c34 } }; void usage( char * string ) { int i; fprintf( stderr, "Usage: %s architecture\n", string ); fprintf( stderr, "Available architectures:\n" ); for ( i = 0; i < sizeof(archlist) / sizeof(struct arch); i++ ) { fprintf( stderr, "%i: %s\n", i, archlist[i].description ); } } int main( int argc, char * argv[] ) { char gateway[1337]; char host[1337]; char hell[1337]; char code[1337]; char * execve_argv[] = { NULL, "-g", "123", "-g", gateway, host, hell, code, NULL }; int i; struct arch * arch; unsigned int hellcode; unsigned int size; if ( argc != 2 ) { usage( argv[0] ); return( -1 ); } i = atoi( argv[1] ); if ( i < 0 || i >= sizeof(archlist) / sizeof(struct arch) ) { usage( argv[0] ); return( -1 ); } arch = &( archlist[i] ); execve_argv[0] = arch->filename; strcpy( code, arch->code ); strcpy( hell, arch->hell ); hellcode = arch->stack - (strlen(arch->filename) + 1) - (strlen(code) + 1) - (strlen(hell) + 1); for ( i = 0; i < hellcode - (hellcode & ~3); i++ ) { strcat( code, "X" ); } hellcode = hellcode & ~3; strcpy( host, "AAAABBBBCCCCDDDDEEEEXXX" ); ((unsigned int *)host)[1] = 0xffffffff & ~PREV_INUSE; ((unsigned int *)host)[2] = 0xffffffff; ((unsigned int *)host)[3] = arch->__free_hook - 12; ((unsigned int *)host)[4] = hellcode; size = (hellcode - (strlen(host) + 1) + 4) - (arch->p - 4); size = size | PREV_INUSE; sprintf( gateway, "0x%02x.0x%02x.0x%02x.0x%02x", ((unsigned char *)(&size))[0], ((unsigned char *)(&size))[1], ((unsigned char *)(&size))[2], ((unsigned char *)(&size))[3] ); execve( execve_argv[0], execve_argv, NULL ); return( -1 ); } --[ 0x05 - Upgrading the exploit ]-------------------------------------- The exploit was written to easily include new architectures and operating systems. In order to support new platforms, 7 different elements are needed: - description, a string describing the concerned platform. For the moment, only "Debian GNU/Linux 2.2 (traceroute 1.4a5-2) i386" and "Debian GNU/Linux 2.2 (traceroute 1.4a5-2) sparc" are supported. - filename, a string containing the full path where the traceroute binary can be found. On most systems, this will be "/usr/sbin/traceroute". - stack, the address where the first argument given to a program (the program name itself) can be found. On i386 architectures, this is 0xc0000000 - 4, on sparc architectures it is 0xf0000000 - 8. - hell and code, a special shellcode divided into two parts... see the discussion above. hell and code are already available for i386 and sparc processors. - p, the pointer returned to the savestr() function by the malloc(1024) call. On architectures where ltrace is available, this pointer can be easily obtained: % cp /usr/sbin/traceroute /tmp % ltrace /tmp/traceroute -g 12 -g 42 2>&1 | grep 'malloc(1024)' malloc(1024) = 0x0804ce38 On architectures were ltrace is not available (like sparc), the whole thing is trickier: download the traceroute sources, and add the following line in savestr.c, after the malloc(1024) call: fprintf( stderr, "debug: strptr == %p;\n", strptr ); Now, compile traceroute, and run it through strace: % strace ./traceroute -g 12 -g 42 Compute the difference between the pointer returned by the debug message and the pointer returned by brk(0). Now run the real traceroute through strace: % cp /usr/sbin/traceroute /tmp % strace /tmp/traceroot -g 12 -g 42 2>&1 | grep 'brk(0)' brk(0) = 0x22418 Now add the difference computed before to this pointer, and yes, the resulting pointer is p. - __free_hook, the memory address were the __free_hook function pointer is stored. Use GDB in order to find out the value of this last element: % cp /usr/sbin/traceroute /tmp % gdb /tmp/traceroute (gdb) break exit (gdb) run (gdb) p &__free_hook It is as simple as that. Feel free to send support for new architectures so that it can be included in the official version of the exploit, available at: --[ 0x06 - Fixes ]------------------------------------------------------ Every vendor should already have released a patched version of traceroute since the vulnerability was published and exploited about a month ago. But anyway, a fixed version of traceroute is available at: --[ 0x07 - Credits ]---------------------------------------------------- Without Pekka Savola, Chris Evans, Dvorak and Solar Designer, there would be no exploit :-) Without VIA, there would be no big endian exploit. Thank you very much. --[ 0x08 - References ]------------------------------------------------- [1] [2] [3] -- Michel "MaXX" Kaempf By Date By Thread
http://seclists.org/bugtraq/2000/Nov/86
CC-MAIN-2014-35
refinedweb
2,305
65.76
Amazon's API presents two different methods of interaction: REST (Representational State Transfer) and SOAP (Simple Object Access Protocol). The majority of the examples within this chapter utilize the SOAP method; I will, however, initially present an interaction using REST for completeness. I have selected SOAP for use within the chapter because of the relatively clean level of abstraction that can be obtained by using a SOAP class such as NuSOAP, and to offer a counterpoint to Amazon's own examples, which are almost exclusively REST. This chapter covers a few common methods of interacting with Amazon's API; a full listing of available interfaces is presented in Appendix C. You can register for the Amazon API by visiting the root page (.[com/jp/ca/co.uk/ , and so on]) for the desired version of Amazon. Scroll to the bottom of the page and click the Join Associates link. This will bring you to the previously unseen Make Money tab. From there, click the Web Services link underneath the tab bar, and then click Register for AWS on the left side. This will provide you with a developer tag, which will allow you to begin running queries against the API; however, you can't earn any referral fees yet. In order to earn any referral fees, you need to register as an Associate. To register as an Associate, return to the Make Money tab, select the Associates subtab, and click the Join Now button on the left. Registering as an Amazon Associate will provide you with an associate id. This id will be passed with your requests , and the resulting URLs will have that id coded in, to allow Amazon to track which customers you send its way. The Google API was quite restrictive in the number of queries you could run per day — only 1,000 (which is really only like 40 requests per hour ). However, the Amazon API is much more giving, allowing one request per second . This likely stems from the fact that results presented with the Google API represent a loss in revenue (because API results do not include advertisements, one of Google's primary revenue streams), whereas results presented from Amazon's API represent potential revenue for Amazon and you . Amazon allows a tremendous variety of different requests to be run against its service. Items can be searched for by a multitude of criteria (keyword being only one of them), shopping carts can be created and loaded to the brim (50 unique items), and Amazon's lists can be accessed. All of this gives you a variety of ways to determine which products to display to your visitor, and a variety of ways to make revenue from those referrals. Developer tag in hand, you are now ready to start working with Amazon's API. The big choice that you're going to need to make early on is whether you want to work with it via its REST interface or the SOAP interface. Both provide similar functionality; the difference is going to be how you access it. While researching this book, I encountered countless examples utilizing the REST interface, and very few demonstrating the SOAP interface. To get the most out of this chapter, I've decided to take the opposite stance — this chapter concentrates on SOAP with only a brief introduction to REST. Performing any API call over REST, especially during testing, should be quite easy. First, create a simple web form pointing to the appropriate URL, and set the form to use the GET method. Create hidden form variables for any required elements, and use a text box for any user -specified elements. For example, using the following page and entering a search for paul reinheimer will constitute a valid, and useful, REST request: <html> <head> <title>Rest Sample</title> </head> <body> <form method="get" action=" http:// webservices .amazon.com/onca/xml "> <input type="hidden" name ="t" value="preinheimerco-20"> <input type="hidden" name="Service" value="AWSECommerceService"> <input type="hidden" name="SubscriptionId"value="1PHH5VTRY7D300H7JTR2"> <input type="hidden" name="Operation" value="ItemSearch"> <input type="hidden" name="SearchIndex" value="Books"> <input type="text" name="Keywords" value="Books"> <input type="submit" name="submit" value="post"> </form> </body> </html> Most of the parameters there are self-explanatory, but a few could do with some explanation. The parameter named t with a value of preinheimerco-20 contains my associate ID (from joining the Amazon Associates program), which will allow the API to encode resultant URLs with my ID for revenue tracking. The SubscriptionID and value represent my developer key , necessary for all requests . Operation indicates what type of request I am performing this time — an ItemSearch — and SearchIndex indicates that I want to search only Amazon's book inventory this time. Finally, the text input field allows users to enter their own search Keywords . The result from Amazon is quite verbose, but still readable. First some basic information about the request is returned, followed by the actual result items. Each item contains an ASIN (Amazon Standard Identification Number), the URL for the item, a title, and other basic information. In the following request, the authors of the book are returned. <?xml version="1.0" encoding="UTF-8"?> <ItemSearchResponse xmlns=" "> <OperationRequest> <HTTPHeaders> <Header Name="UserAgent" Value="Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"></Header> </HTTPHeaders> <RequestId>0JQ4GT363KKWN5RBNS6X</RequestId> <Arguments> <Argument Name="Service" Value="AWSECommerceService"></Argument> <Argument Name="submit" Value="post"></Argument> <Argument Name="SearchIndex" Value="Books"></Argument> <Argument Name="t" Value="preinheimerco-20"></Argument> <Argument Name="SubscriptionId" Value="1PHH5VTRY7D300H7JTR2"></Argument> <Argument Name="Keywords" Value="paul reinheimer"></Argument> <Argument Name="Operation" Value="ItemSearch"></Argument> </Arguments> <RequestProcessingTime>0.0342471599578857</RequestProcessingTime> </OperationRequest> <Items> <Request> <IsValid>True</IsValid> <ItemSearchRequest> <Keywords>paul reinheimer</Keywords> <SearchIndex>Books</SearchIndex> </ItemSearchRequest> </Request> <TotalResults>1</TotalResults> <TotalPages>1</TotalPages> <Item> <ASIN>0764589547</ASIN> <DetailPageURL> exec /obidos/redirect?tag=ws%26link_code=xm2 %26camp=2025%26creative=165953%26path= ASIN=0764589547%2526location=/o/ASIN/0764589547%25253FSubscriptionId=1PHH5VTRY7 D300H7JTR2</DetailPageURL> <ItemAttributes> <Author>Paul Reinheimer</Author> <Author>Chris Shiflett</Author> <ProductGroup>Book</ProductGroup> <Title>Professional Web APIs with PHP: eBay, Google, Paypal, Amazon, FedEx plus Web Feeds</Title> </ItemAttributes> </Item> </Items> </ItemSearchResponse> This request only returned a single result ( item ). Had there been more results, the item tag would have repeated. As you can see, the elements required to perform a transaction using REST are relatively straightforward. It would have been trivial to retrieve the result document with file_get_contents() (or any of a number of similar constructs) and parse the XML with a tool like SimpleXML or MiniXML. You would then be able to present results to the user in an attractive manner. Alternatively, you could use an XSLT stylesheet to directly translate the result set into a user-accessible document. The remainder of this chapter concentrates on the SOAP interface to the Amazon API. The REST services are quite well documented, and there is an abundance of sample code already available. My hope is that by providing samples for SOAP, which presently seem to be lacking, you will be better able to use the API in whatever manner you wish. Amazon breaks the mold set by most major APIs in presenting access to its database through both SOAP and REST. Both request types allow access to essentially the same internal functions, the key difference being the structure of the request. When exploring complicated APIs, it is often very useful to be presented with an easy-to-read list of available queries. To that end I would recommend taking a look at the Generic Soap Client available at http:// soapclient .com/SoapTest.html . Give it the URL to any .wsdl file, and it will display the different available requests and the parameters for each request. It also goes the additional step of allowing you to actually make the query, in which case it will display either the request or response depending on your selection. Performing the same search as used in the REST request using SOAP requires a slightly different approach: <?php require('../lib/ nusoap .php'); $client = new soapclient(" ", true); The NuSOAP libraries are included and the $client object is created. The .wsdl file here is for the U.S. version of the API. Different .wsdl documents are used for the regional sites. $query = array( 'keyword' => 'paul reinheimer', 'page' => 1, 'mode' => 'books', 'tag' => 'preinheimerco-20', 'type' => 'lite', 'devtag' => '1PHH5VTRY7D300H7JTR2' ); The query itself is generated. The same search is being performed as in the REST request. Notice the additional element type , set to lite . The same request performed with the heavy tag instead of the lite tag is presented shortly. $namespace = ' '; $action = ' '; $method = "KeywordSearchRequest"; $result = $client->call($method, array('KeywordSearchRequest' => $query), $namespace, $action); print_r($result); ?> Finally the namespace, action, and method are defined and the query is run against the API server. The results are printed, and shown here:] => [Availability] => This item is currently not available. ) ) ) The results returned are very similar to what you saw with the REST request. Note that the SOAP request isn't prepended with your original request. Using the previous code, but replacing the lite type tag with heavy , gives the following:] => [BrowseList] => Array ( [0] => Array ( [BrowseName] => Computer Programming ) [1] => Array ( [BrowseName] => Computers / Programming / General ) ) [Media] => Paperback [Isbn] => 0764589547 [Availability] => This item is currently not available. ) ) ) More information is returned, such as the ISBN and Amazon's categorization of the item. The information returned in this request is rather slim because the book hasn't been released yet. When available, a heavy request will include information like similar products, user comments, and an array of applicable browse listings. Presenting the results from a given search in a usable manner isn't much more difficult. The query against the API will be performed as before (though with different criteria), but this time, rather than using print_r() to view the results, the results will be iterated through, and outputted with accompanying HTML: <?php require('../lib/nusoap.php'); $client = new soapclient("", true); $params = array( 'keyword' => 'elements of style', 'page' => 1, 'mode' => 'books', 'tag' => 'preinheimerco-20', 'type' => 'heavy', 'devtag' => '1PHH5VTRY7D300H7JTR2' ); $namespace = ''; $action = ''; $"; echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>"; echo "Author(s): " . $authorList . "<br>"; echo "List Price: " . $price; echo "<hr>"; } ?> Here a basic foreach() loop iterates through each of the result items, and variables are created for each of the desired result elements. This is done mainly for clarity and compatibility with the size of this printed page; generally I would use something more like this: echo "<a href=\"{$item['Url']}\" title=\"Learn More at Amazon.com\">{$item['ProductName']}<a><br>"; This is a little harder to read, but it saves on a variable assignment. The implode() function is very useful here, quickly turning the array of authors into a comma-delimited string. The output of this function shows the results of a search for "elements of style," shown in Figure 7-1. Figure 7-1 Previous examples worked well and began to explore some of the functionality that the Amazon API presents ; however, they did not include any error checking, and used hard-coded search terms and criteria. As already mentioned, it is always best not to trust any external content just in case — you never know what you are going to get. Accordingly, the following program allows an end user to search for products. Functionally, the program will have three main components : presenting the search form and validating passed data, performing the query, and presenting the results. Different product types contain different information — books have authors, movies have stars, and music has artists . As such, results will be passed to one of three different functions, one each for the different search types presented. function displayBook($resultItems) { foreach ($resultItems AS $item) { $title = $item['ProductName']; $url = $item['Url']; $image = $item['ImageUrlSmall']; $authorList = implode($item['Authors'], ", "); $price = $item['ListPrice']; if ($url != "") echo "<img src=\"$image\" align=\"left\">"; echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>"; echo "Author(s): " . $authorList . "<br>"; echo "List Price: " . $price; echo "<hr>"; } } The displayBook() function is identical (except for the function wrapping) to the code shown in the previous example. function displayDVD($resultItems) { foreach ($resultItems AS $item) { $title = $item['ProductName']; $url = $item['Url']; $image = $item['ImageUrlSmall']; $stars = @implode($item['Starring'], ", "); $price = $item['ListPrice']; if ($url != "") echo "<img src=\"$image\" align=\"left\">"; echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>"; if ($stars != "") echo "Starring: " . $stars . "<br>"; echo "List Price: " . $price . "<br><br>"; echo "<hr>"; } } For DVDs, the Starring value is imploded to be displayed. function displayCD($resultItems) { foreach ($resultItems AS $item) { $title = $item['ProductName']; $url = $item['Url']; $image = $item['ImageUrlSmall']; $artists = implode($item['Artists'], ", "); $price = $item['ListPrice']; if ($url != "") echo "<img src=\"$image\" align=\"left\">"; echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>"; echo "Artist(s): " . $artists . "<br>"; echo "List Price: " . $price; echo "<hr>"; } } For CDs, the artist's value is again imploded for display. Although the differences presented here are not too significant, using different functions for different object types does allow a lot of flexibility. Displaying Director in the DVD function would be trivial, as would choosing to display the label for music or the publisher for books. It's important not to feel constrained to displaying the data common across all types when working with the API, because there is such a great variety. That being said, further examples in this chapter concentrate on books; the code for other result types tends to be repetitive. function runSearchQuery($client, $keywords, $page, $mode, $type = 'lite') { $params = array( 'keyword' => $keywords, 'page' => $page, 'mode' => $mode, 'tag' => 'preinheimerco-20', 'type' => $type, 'devtag' => '1PHH5VTRY7D300H7JTR2' ); $namespace = ' '; $action = ' '; $method = "KeywordSearchRequest"; $result = $client->call($method, array('KeywordSearchRequest' => $params), $namespace, $action); return $result; } Running the query against the Amazon API uses code very similar to the previous example. The hardcoded variables for keyword, page, mode, and type have been replaced with variables. The encapsulation of this code into its own function should help keep things clear, and will save on overhead later. Finally, here is the body of the code itself: <html> <head> <title>Amazon.com Search Interface</title> </head> <body> <form action="./soap.search.php" method="get"> <input type="text" name="query"> <input type="hidden" name="page" value="1"> <select name="mode"> Here a basic form is started to allow users to enter their search criteria. The page variable is used to allow users to navigate through multiple pages of search results. <?php $modes = array(); $modes[] = "books"; $modes[] = "dvd"; $modes[] = "cd"; foreach ($modes as $mode) { echo "<option value=\"$mode\">$mode</option>"; } ?> </select> <input type="submit"> </form> An array is created to contain each type of request the program is capable of performing. Structuring your code in this manner allows you to add other search types easily later on, and will come in handy when it comes time to validate the user's input. <?php if (!isset($_GET['query'])) { exit; }else { $query = $_GET['query']; } If a query has not been received, there is no point in continuing. This is most likely the case when a user visits the page for the first time. if (in_array($_GET['mode'], $modes)) { $mode = $_GET['mode']; }else { echo "Invalid mode selected was " . $_GET['mode']; exit; } Here the array originally used to populate the select box is used to validate the data. Looking at the form, it may seem impossible to receive any other value, but remember that the request is passed in the address bar, and requests can be created by other parties manually. if (is_numeric($_GET['page'])) { $page = $_GET['page']; }else { echo "Invalid page requested , was: " . $_GET['page']; exit; } Finally, the page variable is populated if the passed variable is numeric. require('../lib/nusoap.php'); $client = new soapclient(" ", true); $error = $client->getError(); if ($error) { echo 'Error creating search client, please try again later'; // It would be a great idea to email $error to an administrator exit; } The NuSOAP library is included into the program at this point rather than earlier to save on overhead when it isn't needed (which is the case for the first request). The SOAP client is created, and is checked for errors. If an error is encountered at this point, it is likely that the .wsdl file was either inaccessible or invalid. It would be a great idea to do something with errors like this when you encounter them. $result = runSearchQuery($client, $query, $page, $mode, 'heavy'); $error = $client->getError(); if ($client->fault $error) { echo "I wasn't able to retrieve your search results, please try again later"; //It would be a great idea to email $client->fault to an admin exit; } Next the query is run, and again errors are checked for. A client fault is different from an error, so both are checked for at this point. Again, don't just check for errors, do something about them. $resultItems = $result['Details']; switch ($mode) { case "dvd": displayDVD($resultItems); break; case "books": displayBook($resultItems); break; case "cd": displayCD($resultItems); break; } if ($result['TotalPages'] > $page) { $page++; echo "<a href=\"soap.search.php?query=$query&mode=$mode&page=$page\">Next 10 Results</a>"; } Finally, the resultItems variable is created to contain all of the result items, and the appropriate display function is called. If the current page is less than the total number of pages available (as indicated by Amazon), it displays a link to the next page. And that's it; users can now perform searches for books, DVDs, or CDs, page through the results, and click on a link to be taken directly to that item on Amazon. Hopefully they make a purchase, because the inclusion of my tag with the query will ensure I make a percentage of any referred sale! A search for a DVD is shown in Figure 7-2, and a search for a music CD is shown in Figure 7-3. Figure 7-2 Figure 7-3 In a previous example I searched for my name, which managed to return exactly what I was looking for in that case. However, that search included both the title of books and the author when examining records, which may have undesired results. For example, a search for "Winston Churchill" will result in books by and about him. In order to perform a search specifically by author, a separate function is called. This function performs in a similar manner to the earlier search example. However, the main difference is the fact that it calls AuthorSearchRequest rather than KeywordSearchRequest : function runAuthorSearchQuery($client, $author, $page, $mode, $type = 'lite') { $params = array( 'author' => $author, 'page' => $page, 'mode' => $mode, 'tag' => 'preinheimerco-20', 'type' => $type, 'devtag' => '1PHH5VTRY7D300H7JTR2' ); $namespace = ' '; $action = ' '; $method = "AuthorSearchRequest"; $result = $client->call($method, array('AuthorSearchRequest' => $params), $namespace, $action); return $result; } As mentioned, this function is quite similar to the earlier keyword search function. The two differences are the call to AuthorSearchRequest rather than KeywordSearchRequest , and the keyword parameter is replaced with author . <?php if (!isset($_GET['author'])) { echo "no author"; exit; }else { $author = $_GET['author']; } if (is_numeric($_GET['page'])) { $page = $_GET['page']; }else { $page = 1; } require('../lib/nusoap.php'); $client = new soapclient("", true); $result = runAuthorSearchQuery($client, $author, $page, 'books', 'heavy'); $error = $client->getError(); if ($error) { echo "<pre>"; print_r($error); echo "</pre>"; exit; } $resultItems = $result['Details']; displayBook($resultItems); if ($result['TotalPages'] > $page) { $page++; echo "<a href=\"soap.author.php?author=$author&page=$page\">Next 10 Results</a>"; } Much of the code here is identical to the last example. $_GET['AUTHOR'] is confirmed to exist rather than the query used in the last example. A change is also made to the handling of the page variable. This page will be linked to in future examples, and it will be easier not to require the page variable set in the URL. Figure 7-4 shows a search for "Dan Brown." Figure 7-4 Using Amazon's search function returns information on a large set of items. However, frequently you will only need the information for one specific product, or only want to display a single product to the end user. You can retrieve that information using the API's AsinSearchRequest method. Conceptually, this script isn't too different from earlier examples, though a few extra functions have been created to make the page more interactive. function runASINQuery($client, $asin, $type = 'heavy') { $params = array( 'asin' => $asin, 'type' => $type, 'tag' => 'preinheimerco-20', 'devtag' => '1PHH5VTRY7D300H7JTR2' ); $namespace = ''; $action = ''; $method = "AsinSearchRequest"; $result = $client->call($method, array('AsinSearchRequest' => $params), $namespace, $action); return $result; } Here the actual call to the API is made. Notice the lack of parameters used previously, such as mode, which are irrelevant because the ASIN points to a specific item within Amazon's catalog. All previous query functions defaulted to requesting the lite result set; this one defaults to heavy . Because only a single item is being displayed, you can make use of the additional data returned. This will require you to implement a few more functions as follows : function getAuthorList($authors) { $$item</a>, "; } return $authorList; } This is the first function used to aid in the display of data. Here the list of authors of the book is parsed, and each author is presented as a link. This links to the previous script, so users can find books from the same author quickly. Note the use of urlencode() ; this is important because author names will frequently contain spaces, which should be encoded before being presented in a link. function getCategoryList($browseList) { $categoryList = ""; foreach ($browseList as $item) { $categoryList .= $item['BrowseName'] . ", "; } return $categoryList; } You will also present a list of categories to which the book belongs. This information is nested twice, so a foreach() loop is used rather than a simple implode() call. Finally, here is the main portion of the code: <?php if (!isset($_GET['asin'])) { exit; }else { $asin = $_GET['asin']; } require('../lib/nusoap.php'); $client = new soapclient("", true); $result = runASINQuery($client, $asin, 'heavy'); $error = $client->getError(); if ($error) { echo "<pre>"; print_r($error); echo "</pre>"; exit; } $result = $result['Details']['0']; As usual, the passed parameter is checked first, before any other files are included. Results to an ASIN query are presented in the same manner as search results, within Details , then an array is presented (which has a single element). To make accessing that data easier, the $result variable is set to that smaller scope. $image = $result['ImageUrlMedium']; $url = $result['Url']; $productName = $result['ProductName']; $authors = getAuthorList($result['Authors']); $listPrice = $result['ListPrice']; $amazonPrice = $result['OurPrice']; $categories = getCategoryList($result['BrowseList']); $availability = $result['Availability']; $rating = $result['Reviews']['AvgCustomerRating']; echo "<img src=\"$image\" align=\"left\">"; echo "<b>Title</b>: <a href=\"$url\" title=\"Buy at Amazon!\">$productName</a><br>"; echo "<b>Authors</b>: $authors<br>"; echo "<b>List Price</b>: $listPrice, <b>Amazon's Price</b>: $amazonPrice<br>"; if ($categories) echo "<b>Categories</b>: $categories<br>"; echo "<b>Availability</b>: $availability<br>"; echo "<b>Average Customer Rating</b>: $rating<br><br>"; $customerReviews = $result['Reviews']['CustomerReviews']; foreach ($customerReviews AS $review) { echo "<b>Rating</b>: {$review['Rating']}<br>"; echo "<b>Summary</b>: {$review['Summary']}<br>"; echo "<b>Comment</b>: {$review['Comment']}<br><br>"; } Finally, the results are echo'd to the end user. Notice that the medium- sized image was used in this case, rather than the small image used in search results. Both the list price and Amazon's price are displayed. Also notice that a full category listing, linked author names, and a listing of customer reviews are also provided. Figure 7-5 shows detailed information on "The Elements of Style." Figure 7-5 This details page works best when linked to from other result pages. For example, change the destination in both the Keyword search and Author search programs to point to this page. Users will then see a larger cover image and more detailed pricing information. Amazon offers a wide selection and competitive pricing, but you may encounter products priced a little higher than you would like. Both businesses and individuals take a keen interest in pricing, and may want to be informed if the price on any particular item they are interested in changes. With the code presented here, you can save those products and have your script periodically check for lowered prices. require('../common_db.php'); require('../lib/nusoap.php'); $client = new soapclient(" ", true); $query = "SELECT * FROM `07_amazon_monitor_price_list`"; $results = getAssoc($query); foreach($results AS $item) { $result = runASINQuery($client, $item['asin']); $result = $result['Details']['0']; $listPrice = $result['ListPrice']; $amazonPrice = $result['OurPrice']; $query = "INSERT INTO 07_amazon_monitor_price_results (`asin`, `listPrice`, `amazonPrice`, `timestamp`) VALUES ('{$item['asin']}', '$listPrice', '$amazonPrice', null)"; insertQuery($query); } I have removed the error checking to keep this example light, but the concept should be clear. A list of desired ASINs to watch is retrieved from the database, each item is checked in turn , and both its list price and Amazon's price are recorded, along with the timestamp. What you do with this information is entirely up to you. You could graph prices of books over time, send a message when the price drops , or anything else, for that matter. The two tables used are shown here: CREATE TABLE `07_amazon_monitor_price_results` ( `asin` varchar(10) NOT NULL default '', `listPrice` varchar(10) NOT NULL default '0', `amazonPrice` varchar(10) NOT NULL default '0', `timestamp` timestamp(14) NOT NULL ) TYPE=MyISAM; CREATE TABLE `07_amazon_monitor_price_list` ( `asin` varchar(10) NOT NULL default '', PRIMARY KEY (`asin`) ) TYPE=MyISAM; INSERT INTO `07_amazon_monitor_price_list` VALUES ('059600656X'); INSERT INTO `07_amazon_monitor_price_list` VALUES ('0672324547'); INSERT INTO `07_amazon_monitor_price_list` VALUES ('0764589547'); INSERT INTO `07_amazon_monitor_price_list` VALUES ('1565926811'); In both tables, a length of 10 is specified for the length of the ASIN — ASINs are always 10 characters long. Another useful piece of information Amazon makes available is the sales rank for all its products. This is of particular interest if you (for example) wrote a book and are curious as to how it is performing. This code fits into the same framework as the previous example. $query = "SELECT * FROM `07_amazon_monitor_rank_list`"; $results = getAssoc($query); foreach($results AS $item) { $result = runASINQuery($client, $item['asin']); $result = $result['Details']['0']; $salesRank = $result['SalesRank']; $query = "INSERT INTO 07_amazon_monitor_rank_results (`asin`, `rank`, `timestamp`) VALUES ('{$item['asin']}', '$salesRank', null)"; insertQuery($query); } Again, all of the error checking code has been removed to save on space. The two tables used are shown here: CREATE TABLE `07_amazon_monitor_rank_results` ( `asin` varchar(10) NOT NULL default '', `rank` int(11) NOT NULL default '0', `timestamp` timestamp(14) NOT NULL ) TYPE=MyISAM;\ CREATE TABLE `07_amazon_monitor_rank_list` ( `asin` varchar(10) NOT NULL default '', PRIMARY KEY (`asin`) ) TYPE=MyISAM; INSERT INTO `07_amazon_monitor_rank_list` VALUES ('059600656X'); INSERT INTO `07_amazon_monitor_rank_list` VALUES ('0672324547'); INSERT INTO `07_amazon_monitor_rank_list` VALUES ('0764589547'); INSERT INTO `07_amazon_monitor_rank_list` VALUES ('1565926811'); Using the information gleaned in this example, as well as the sales data obtained from the previous example, can yield interesting information. Does the sales rank increase when price drops, how does the sales rank change as time passes since the book's release increases , and so on.
http://flylib.com/books/en/4.404.1.58/1/
CC-MAIN-2013-20
refinedweb
4,445
51.28
Request and response objects¶ Quick overview¶ Dj objects¶ Attributes¶ All attributes should be considered read-only, unless stated otherwise below. session is a notable exception. - HttpRequest.body¶ - Changed in Django 1.4. Before Django 1.4, HttpRequest.body was named HttpRequest.raw_post_data. domain. Example: "/music/bands/the_beatles/" - HttpRequest.path_info¶/". - HttpRequest.method¶ A string representing the HTTP method used in the request. This is guaranteed to be uppercase. Example: if request.method == 'GET': do_something() elif request.method == 'POST': do_something_else() - HttpRequest.encoding¶. - HttpRequest.GET¶ A dictionary-like object containing all given HTTP GET parameters. See the QueryDict documentation below. - HttpRequest.POST¶ A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.Changed in Django 1.5: Before Django 1.5, HttpRequest.POST contained non-form data. It’s possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use if request.POST to check for use of the POST method; instead, use if request.method == "POST" (see above). Note: POST does not include file-upload information. See FILES. - HttpRequest dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: - CONTENT_LENGTH – the length of the request body (as a string). - CONTENT_TYPE – the MIME type of the request body. - "POST". -. - HttpRequest.user¶ An object of type AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of django.contrib.auth.models.AnonymousUser. You can tell them apart with is_authenticated(), like so: if request.user.is_authenticated(): # Do something for logged-in users. else: # Do something for anonymous users. user is only available if your Django installation has the AuthenticationMiddleware activated. For more, see User authentication in Django. - HttpRequest.session¶ A readable-and-writable, dictionary-like object that represents the current session. This is only available if your Django installation has session support activated. See the session documentation for full details. - HttpRequest.urlconf¶. - HttpRequest.resolver_match¶ - New in Django 1.5.. - HttpRequest.get_full_path()¶ Returns the path, plus an appended query string, if applicable. Example: "/music/bands/the_beatles/?print=true" - HttpRequest.build_absolute_uri(location)¶. Example: "" - New in Django 1.4.(. - HttpRequest.__iter__()¶ Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with iterative parser without constructing a whole XML tree in memory. Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree: import xml.etree.ElementTree as ET for element in ET.iterparse(request): process(element)ructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python’s standard KeyError, so you can stick to catching KeyError.) - QueryDict.__setitem__(key,, default)¶ Uses the same logic as __getitem__() above, with a hook for returning a default value if the key doesn’t exist. - QueryDict.setdefault(key, default)¶ Just like the standard dictionary setdefault() method, except it uses __setitem__() internally. - QueryDict.update(other_dict)¶ Takes either a QueryDict or standard dictionary. Just like the standard dictionary update() method, except it appends to the current dictionary items rather than replacing them. For example: >>> q = QueryDict('a=1') >>>.iteritems()¶ Just like the standard dictionary iteritems() method. Like QueryDict.items() this uses the same last-value logic as QueryDict.__getitem__(). - QueryDict.iterlists()¶ Like QueryDict.iteritems() except it includes all values, as a list, for each member of the dictionary. - QueryDict.values()¶ Just like the standard dictionary values() method, except this uses the same last-value logic as __getitem__(). For example: >>> q = QueryDict('a=1&a=2&a=3') >>> q.values() , default)¶ Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn’t exist and no default value was provided. It’s guaranteed to return a list of some sort unless the default value was no list.Changed in Django 1.4: The default parameter was added. - QueryDict.setlistdefault(key, default_list)¶ Just like setdefault, except it takes a list of values instead of a single value. - QueryDict.lists()¶ Like items(), except it includes all values, as a list, for each member of the dictionary. For example: >>> q = QueryDict('a=1&a=2&a=3') >>> q.lists() [ - New in Django 1.4./' HttpResponse objects¶ In contrast to HttpRequest objects, which are created automatically by Django, HttpResponse objects are your responsibility. Each view you write is responsible for instantiating, populating and returning an HttpResponse. The HttpResponse class lives in the django.http module. Usage¶ Passing strings¶ Typical usage is to pass the contents of the page, as a string, to the HttpResponse constructor: >>>. If you use this technique, the iterator should return strings. Passing an iterator as content to HttpResponse creates a streaming response if (and only if) no middleware accesses the HttpResponse.content attribute before the response is returned. This technique is fragile and was deprecated in Django 1.5. If you need the response to be streamed from the iterator to the client, you should use the StreamingHttpResponse class instead. As of Django 1.7, when HttpResponse is instantiated with an iterator, it will consume it immediately, store the response content as a string, and discard the iterator. You can now use HttpResponse as a file-like object even if it was instantiated with an iterator. Django will consume and save the content of the iterator on first access. string representing the content, encoded from a Unicode object if necessary. - HttpResponse.status_code¶ The HTTP Status code for the response. Methods¶ - HttpResponse.__init__(content='', content_type=None, status=200”. Historically, this parameter was called mimetype (now deprecated). status is the HTTP Status code for the response. - Cookie.Morsel client side script accessing the protected cookie data. - New in Django 1.4.. - HttpResponse.write(content)¶ This method makes an HttpResponse instance a file-like object. - HttpResponse.flush()¶ This method makes an HttpResponse instance a file-like object. - HttpResponse.tell()¶ This method makes an HttpResponse instance a file-like object. HttpResponse subclasses¶ Django includes a number of HttpResponse subclasses that handle different types of HTTP responses. Like HttpResponse, these subclasses live in django.http. - class HttpResponseRedirect¶ The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. '') or an absolute path with no domain (e.g. '/search/'). See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302. - class HttpResponsePermanentRedirect¶ Like HttpResponseRedirect, but it returns a permanent redirect (HTTP status code 301) instead of a “found” redirect (status code 302). - class HttpResponseNotModified¶ The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304). - class HttpResponseBadRequest¶ Acts just like HttpResponse but uses a 400 status code. - class HttpResponseNotFound¶ Acts just like HttpResponse but uses a 404 status code. - class HttpResponseForbidden¶ Acts just like HttpResponse but uses a 403 status code. - class HttpResponseNotAllowed¶ Like HttpResponse, but uses a 405 status code.. StreamingHttpResponse objects and keep a database connection idle in transaction stringswares can’t function normally. For example the ETag and Content- Length headers can’t be generated for streaming responses. Attributes¶ - HttpResponse.status_code The HTTP Status code for the response. - HttpResponse.streaming This is always True.
https://docs.djangoproject.com/en/1.5/ref/request-response/
CC-MAIN-2015-40
refinedweb
1,284
52.26
06 April 2011 05:04 [Source: ICIS news] By Serena Seng ?xml:namespace> On 1 April, 80/20 blend soap noodle prices slipped $10/tonne (€7/tonne) week on week to $1,240-1,290/tonne FOB (free on board) SE (southeast) Supply of crude palm oil (CPO), crude palm kernel oil (CPKO), palm stearin and crude coconut oil (CNO) – the raw materials for the production of soap noodles – will be seasonally strong in April, auguring further declines in feedstock prices in the weeks ahead, industry sources said. This will offset any price boost from the start of the traditional peak demand season for soap noodles from April to June, they said. “We have seen more buying activity starting last week and expect more in the coming weeks,” said an Indonesian soap noodle producer. Soap noodles are used as the main ingredient in the production of soap bars. “[But] Prices are unlikely to increase as raw material costs look likely to be low. The upcoming April harvest would add more CPO supply into the market,” said a palm oil trader said. A China-based soap noodle buyer said prices may remain at current levels or even fall. “I doubt prices will increase as most sellers will want to close as much deals as possible during these upcoming three months,” the buyer said. Sharp falls in values of major feedstocks saw soap noodle prices shedding $140-160/tonne from 25 February to 1 April, according to ICIS data. CPO prices slipped 2.2% from 25 February to Malaysian ringgit (M$) 3,430/tonne ($1,132/tonne) on 5 April, while CPKO slumped 19.1% over the same period to $1,763/tonne, while CNO fell 7.24% to $2,050/tonne CIF (cost, insurance and freight) Rotterdam, according to data from Bursa Malaysia. ($1 = €0.70 / $1 = M$3.03)
http://www.icis.com/Articles/2011/04/06/9449835/asia-soap-noodles-may-stay-soft-as-feedstock-costs-fall.html
CC-MAIN-2014-42
refinedweb
309
69.21
45543/enough-only-create-checksum-zip-package-instead-of-each-file Please go through this code. This should ...READ MORE from xml.dom import minidom import pandas as pd mydoc ...READ MORE Hi@Shubham, It may possible. When you saved your ML ...READ MORE Good question - Considering that you are ...READ MORE Python doesn't know what $FILEDIR is. Try an absolute path ...READ MORE key is just a variable name. for key ...READ MORE I figured out that pypyodbc only works ...READ MORE suppose you have a string with a ...READ MORE my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE In Python 2, use urllib2 which comes ...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/45543/enough-only-create-checksum-zip-package-instead-of-each-file
CC-MAIN-2021-49
refinedweb
143
79.67
Man Page Manual Section... (3) - page: getgrent_r NAMEgetgrent_r, fgetgrent_r - get group file entry reentrantly SYNOPSIS #include <grp.h> int getgrent_r(struct group *gbuf, char *buf, size_t buflen, struct group **gbufp); int fgetgrent_r(FILE *fp, struct group *gbuf, char *buf, size_t buflen, struct group **gbufp); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): getgrent_r(): _GNU_SOURCE fgetgrent_r(): _SVID_SOURCE DESCRIPTIONThe the stream fp. The group structure is defined in <grp.h> as follows: struct group { char *gr_name; /* group name */ char *gr_passwd; /* group password */ gid_t gr_gid; /* group ID */ char **gr_mem; /* group members */ }; TheOn success, these functions return 0 and *gbufp is a pointer to the struct group. On error, these functions return an error value and *g); NOTESThe function getgrent_r() is not really reentrant since it shares the reading position in the stream with all other threads. EXAMPLE #define _GNU_SOURCE #include <grp.h> #include <stdio.h> #include <stdlib.h> #define BUFLEN 4096 int main(void) { struct group grp, *grpp; char buf[BUFLEN]; int i; setgrent(); while (1) { i = getgrent_r(&grp, buf, BUFLEN, &grpp); if (i) break; printf("%s (%d):", grpp->gr_name, grpp->gr_gid); for (i = 0; ; i++) { if (grpp->gr_mem[i] == NULL) break; printf(" %s", grpp->gr_mem[i]); } printf("\n"); } endgrent(); exit(EXIT_SUCCESS); } SEE ALSOfgetgrent(3), getgrent(3), getgrgid(3), getgrnam(3), putgrent(3), group
http://linux.co.uk/documentation/man-pages/subroutines-3/man-page/?section=3&page=getgrent_r
CC-MAIN-2013-48
refinedweb
212
52.49
How do you copy and paste a test case that is a long array? There is no way to expand or highlight an input that runs off the end of the screen. You used to be able to click the input to expand it, but that no longer works. I think for me it still works, but sadly not as conveniently as until recently. It used to be a single click selecting the whole input. Now I need to double- or triple-click and drag. @StefanPochmann Really it still works for you? I can't seem to highlight the entire array pass the ellipses. I've looked in the HTML source and the whole array is not even loaded in the page sometimes. @StefanPochmann I've been going through some older problems that I never did. In particular I was working on #135 Candy. My code is as follows: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 N = len(ratings) dp = [1]*N def helper(i): if i == N-1: return dp[N-1] if ratings[i] < ratings[i+1]: dp[i+1] = dp[i] + 1 helper(i+1) elif ratings[i] > ratings[i+1]: dp[i] = max(dp[i], helper(i+1) + 1) else: dp[i+1] = dp[i] helper(i+1) return dp[i] helper(0) return sum(dp) OJ tells me that I have a Runtime Error, but it doesn't give any line number where the code breaks. I'm sure I'm just doing something stupid, but I can't debug since I can't highlight the entire test case. @david120 Ok, I just tried that. In the Edge browser, triple-click did select the whole array (about 39000 bytes, ending in ,4099,8]) and ctrl-C and ctrl-V got the whole thing. Right-clicking and using "Inspect Element" also showed me the whole data. In Chrome, both ways are cut off after 10000 bytes (ending in ,6774,5297…). So way more than what's shown on the page, but not everything. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/88387/how-do-you-highlight-a-long-test-case
CC-MAIN-2018-13
refinedweb
361
80.11
As a musician who has amassed a collection of musical instruments and noise boxes, the humble Arduino is the perfect tool to create a custom MIDI controller. Whilst the Raspberry Pi may have taken the crown for Internet of Things (IoT) projects, a simple Arduino Uno (what are the different types of Arduino? ) has more than enough power for this project. First time using an Arduino? No worries, we’ve got a complete to read through before you tackle this project. What is MIDI? MIDI stands for Musical Instrument Digital Interface. It outlines a standard way for musical devices to communicate with each other. If you own an electronic keyboard you probably have a MIDI interface. Whilst there are a few technical details involved in the implementation of MIDI, it’s important to remember that MIDI is not audio! MIDI data is a simple set of instructions (one instruction is called a “message”) that another device may implement to make different sounds or control parameters. MIDI supports 16 channels. This means that each cable can support 16 different devices communicating independently with each other. Devices are connected using a 5-pin DIN cable. DIN stands for “German Institute for Standardization”, and is simply a cable with five pins inside the connector. USB is often used in place of 5-pin DIN, or a USB-MIDI interface can be used. Control Change and Program Change There are two main types of MIDI message: Control Change, and Program Change. Control Change (CC) messages contain a controller number and a value between 0 and 127. CC messages are often used to change settings such as volume or pitch. Devices that accept MIDI should come with a manual explaining what channels and messages are setup by default, and how to change them (known as MIDI mapping). Program Change (PC) messages are simpler than CC messages. PC messages consist of a single number, and are used to change the preset or patch on a device. PC messages are sometimes known as “Patch Change”. Similar to CC messages, manufacturers should provide a document outlining what presets are changed by a particular message. What You Will Need - Arduino - 5-pin DIN female socket - 2 x 220 ohm resistors - 2 x 10k ohm resistors - 2 x momentary switches - Hook-up wires - Breadboard - MIDI cable - MIDI device or USB interface Build Plan This project will be quite simple. You can of course add more buttons or hardware to suit your needs. Almost any Arduino will be suitable — only three pins are needed for this example. This project consists of two buttons to control the program, a MIDI port to send the data, and a device to receive the messages. This circuit has been built on a breadboard here, however it is possible to transfer it to a project box and soldered connectors for a robust solution. Circuit Assembly MIDI Connection Wire up your MIDI socket as follows: - MIDI pin 5 to Arduino Transmit (TX) 1 via a 220 ohm resistor - MIDI pin 4 to Arduino +5V via a 220 ohm resistor - MIDI pin 2 to Arduino ground Button Connection The buttons work by changing the resistance the Arduino “sees”. The Arduino pin goes through the switch straight to ground (LOW) via a 10k ohm resistor (a “pull down” resistor, ensuring the value stays low). When the button is pressed, the value seen by the circuit changes to +5v without a resistor (HIGH). The Arduino can detect this change using the digitalRead(pin) command. Connect the buttons to pins 6 and 7 on the Arduino digital input/output (I/O). Connect both buttons: - Left side of button to +5V - Right side of button to Arduino Ground via a 10k ohm resistor - Right side of button to Arduino pin (6 or 7) MIDI Testing Now that all the hardware is finished, it’s time to test it. You will need a USB-MIDI interface (many audio interfaces can do this) and a MIDI cable. The MIDI port wired up on the breadboard is sending data, so it is the output. Your computer is receiving the data, therefore it is the input. This project uses the excellent Arduino MIDI Library v4.2 by Forty Seven Effects. Once you have installed the Library, you can include it in your code by going to Sketch > Include Library > MIDI. You’ll also need a program to monitor the incoming MIDI data: - MIDI Monitor for OS X - MIDI-OX for Windows - KMidimon for Linux Connect the Arduino... Read More to your computer and upload the following test code (don’t forget to select the correct board and port from the Tools > Board and Tools > Port menus). #include <midi.h> #include <midi_defs.h> #include <midi_message.h> #include <midi_namespace.h> #include <midi_settings.h> MIDI_CREATE_INSTANCE(HardwareSerial,Serial, midiOut); // create a MIDI object called midiOut void setup() { Serial.begin(31250); // setup serial for MIDI } void loop() { midiOut.sendControlChange(56,127,1); // send a MIDI CC -- 56 = note, 127 = velocity, 1 = channel delay(1000); // wait 1 second midiOut.sendProgramChange(12,1); // send a MIDI PC -- 12 = value, 1 = channel delay(1000); // wait 1 second } This code will send a CC message, wait 1 second, send a PC message then wait 1 second indefinitely. If everything is working correctly you should see a message appear in your MIDI monitor. If nothing happens, don’t panic! Try troubleshooting: - Ensure all the connections are correct - Check the MIDI port is wired correctly – there should be 2 spare pins on the outside edges - Double-check the circuit is correct - Verify the circuit is connected to a USB-MIDI interface with a MIDI cable - Check your MIDI cable is connected to the input on your USB-MIDI interface - Make sure the Arduino has power - Install the correct driver for your USB-MIDI interface If you are still having problems it might be worth checking your breadboard. Cheap boards can sometimes be very inconsistent and low-quality — it happened to me whilst working on this project. Button Testing Now it’s time to test the buttons are working correctly. Upload the following test code. MIDI does not need to be connected to test this part. const int buttonOne = 6; // assign button pin to variable const int buttonTwo = 7; // assign button pin to variable void setup() { Serial.begin(9600); // setup serial for text pinMode(buttonOne,INPUT); // setup button as input pinMode(buttonTwo,INPUT); // setup button as input } void loop() { if(digitalRead(buttonOne) == HIGH) { // check button state delay(10); // software de-bounce if(digitalRead(buttonOne) == HIGH) { // check button state again Serial.println("Button One Works!"); // log result delay(250); } } if(digitalRead(buttonTwo) == HIGH) { // check button state delay(10); // software de-bounce if(digitalRead(buttonTwo) == HIGH) { // check button state again Serial.println("Button Two Works!"); // log result delay(250); } } } Run this code (but keep the USB cable connected) and open the Serial Monitor (Top Right > Serial Monitor). When you press a button you should see “Button One Works!” or “Button Two Works!” depending on the button you pressed. There is one important note to take-away from this example – the software de-bounce. This is a simple 10 millisecond (ms) delay between checking the button and then checking the button again. This increases the accuracy of the button press and helps prevent noise triggering the Arduino. You do not have to do this, although it is recommended. Creating the Controller Now that everything is wired and working, it’s time to assemble the full controller. This example will send a different CC message for each button that is pressed. I’m using this to control Ableton Live 9.6 on OS X. The code is similar to both the testing samples above. #include <MIDI.h> #include <midi_Defs.h> #include <midi_Message.h> #include <midi_Namespace.h> #include <midi_Settings.h> const int buttonOne = 6; // assign button pin to variable const int buttonTwo = 7; // assign button pin to variable MIDI_CREATE_INSTANCE(HardwareSerial,Serial, midiOut); // create a MIDI object called midiOut void setup() { pinMode(buttonOne,INPUT); // setup button as input pinMode(buttonTwo,INPUT); // setup button as input Serial.begin(31250); // setup MIDI output } void loop() { if(digitalRead(buttonOne) == HIGH) { // check button state delay(10); // software de-bounce if(digitalRead(buttonOne) == HIGH) { // check button state again midiOut.sendControlChange(56,127,1); // send a MIDI CC -- 56 = note, 127 = velocity, 1 = channel delay(250); } } if(digitalRead(buttonTwo) == HIGH) { // check button state delay(10); // software de-bounce if(digitalRead(buttonTwo) == HIGH) { // check button state again midiOut.sendControlChange(42,127,1); // send a MIDI CC -- 42 = note, 127 = velocity, 1 = channel delay(250); } } } Note — you will not be able to use Serial.println() with MIDI output. If you wanted to send a PC message instead of a CC simply replace: midiOut.sendControlChange(42,127,1); With: midiOut.sendProgramChange(value, channel); In Action Below is a demonstration as a controller for Ableton Live (Best DJ software for every budget ). The top right shows the audio meters, and the top middle shows the incoming midi messages (via MIDI Monitor on OS X). Have you Made a MIDI Controller? There are a lot of practical uses for a custom MIDI controller. You could build a vast foot-controlled unit, or a sleek studio controller. Have you made a custom MIDI controller? Let me know in the comments, I’d love to see them! Image Credit: Keith Gentry via Shutterstock.com HI Can You Help me to write a SKETCH to ARDUINO MEGA 2560 ? I'd like to build MIDI CONTROLLER with 10 Potentiometers & 20 or 32 Buttons Thanks for any help Wow, that's a lot of I/O! Have a lot at this tutorial for an example of using multiple buttons: Thanks for that great write up. So easy to follow. With my new Arduino I was sending midi commands within minutes! Awesome job. Very handy. I just bought my first Arduino starter kit, it should be arriving any day now. I want to be able to make a piezo mic converter to midi. This tutorial explains how to achieve the "hard & soft" data from the piezo elements. Any idea on how to convert this to midi? This is the only reason i bought the kit. Basically i just want to be able to be able to make an instrument from everything on the fly and record drums from samples in a daw with a human feel. Checkout this post by James Bruce -- should be a good starting point! This looks great. I have seen videos of additional voice recognition modules being used with an Arduino to turn LED's on and off by saying things like "green", "red" etc. Do you think it would be possible to have the Arduino send a specific MIDI message when a certain voice command is received? That sounds possible. You would need to modify the code so that rather than turning on or off an LED, you send a midi command, something like this (pseudo code): voiceCommand = listenToPerson(); if(voiceCommand == 'keyboard') { sendMidi(); } else { sendSomeOtherMidi(); } I'd love to see the finished result! I used your sketch to make a 3 button controller to sendRealTime messages to my SonicCell. Works great! Thanks! Hey Mark, sounds great! Got a picture? Here ya go! The finished product. Thanks to you! Looks amazing!
http://www.makeuseof.com/tag/make-midi-controller-arduino/
CC-MAIN-2017-26
refinedweb
1,874
64.81
# $Id: UserAdmin.pm,v 1.1.1.1 2004/06/28 19:24:27 veselosky Exp $ package CGI::Builder::Auth::UserAdmin; use CGI::Builder::Auth::AdminBase (); use Carp (); use strict; use vars qw($VERSION @ISA); @ISA = qw(CGI::Builder::Auth::AdminBase); $VERSION = 1.51; sub delete { my($self, $user) = @_; my $rc = 1; delete($self->{'_HASH'}{$user}); $self->{'_HASH'}{$user} and $rc = 0; $rc; } sub suspend { my($self, $user) = @_; $self->{'_HASH'}->{$user} = "!".$self->{'_HASH'}->{$user} if $self->{'_HASH'}->{$user} !~ m/^!/; return 0 unless $self->{'_HASH'}->{$user} =~ m/^!/; return 1; } sub unsuspend { my($self, $user) = @_; $self->{'_HASH'}->{$user} =~ s/^!//; return 0 unless $self->{'_HASH'}->{$user} !~ m/^!/; return 1; } sub list { keys %{$_[0]->{'_HASH'}}; } sub exists { my($self, $name) = @_; return 0 unless defined $self->{'_HASH'}{$name}; return $self->{'_HASH'}{$name}; } sub db { my($self, $file) = @_; my $old = $self->{'DB'}; return $old unless $file; if($self->{'_HASH'}) { $self->DESTROY; } $self->{'DB'} = $file; #return unless $self->{NAME}; $self->lock || Carp::croak(); $self->_tie('_HASH', $self->{DB}); $old; } sub group { my($self) = shift; $self->load('CGI::Builder::Auth::GroupAdmin'); my %attr = %{$self}; foreach(qw(DB _HASH)) { delete $attr{$_}; #just incase, everything else should be OK } return new CGI::Builder::Auth::GroupAdmin (%attr, @_); } sub update { my($self, $username, $passwd, @fields) = @_; return (0, "User '$username' does not exist") unless $self->exists($username); my ($old_encr, $bool); if (!defined $passwd) { $bool = 1; $passwd = $self->password($username); $old_encr = $self->{ENCRYPT}; $self->{ENCRYPT} = 'none'; } $self->delete($username); $self->add($username, $passwd, @fields); $self->{ENCRYPT} = $old_encr if $bool; 1; } sub convert { my($self) = shift; my $class = $self->baseclass(2); #hmm my $new = $class->new(@_); foreach($self->list) { $new->add($_, $self->password($_), 1); } $new; } sub password { my $self = shift; my $val = $self->exists(@_); my($x,$y,$z) = split(':',$val); return defined($z) ? join(':',$x,$y,$z) : join(':',$x,$y) if $self->{ENCRYPT} eq 'MD5'; return $x; } # from Apache's dbmmanage: # if $newstyle is 1, then use new style salt (starts with '_' and contains # four bytes of iteration count and four bytes of salt). Otherwise, just use # the traditional two-byte salt. # see the man page on your system to decide if you have a newer crypt() lib. # I believe that 4.4BSD derived systems do (at least BSD/OS 2.0 does). # The new style crypt() allows up to 20 characters of the password to be # significant rather than only 8. #my %NewStyle = map $_,1, qw(bsd/os-2.0); sub encrypt { my($self) = shift; my $newstyle = defined $_[1]; # || defined $NewStyle{ join("-",@Config{qw(osname osvers)}) }; my($passwd) = ""; my($scheme) = $self->{ENCRYPT} || "crypt"; # not quite sure where we're at risk here... # $_[0] =~ /^[^<>;|]+$/ or Carp::croak("Bad password name"); $_[0] = $&; if($scheme eq "crypt") { $passwd = crypt($_[0], salt($newstyle)); } elsif ($scheme eq "MD5") { #I know, this isn't really "encryption", #since you can't decrypt it, oh well... unless (defined $self->{'_MD5'}) { require Digest::MD5; $self->{'_MD5'} = new Digest::MD5; } my($username,$realm,$pass) = split(":", $_[0]); $self->{'_MD5'}->add(join(":", $username, $realm, $pass)); $passwd = join(":", $realm, $self->{'_MD5'}->hexdigest()); $self->{'_MD5'}->reset; } elsif ($scheme eq "SHA") { require Digest::SHA1; $passwd = '{SHA}' . Digest::SHA1::sha1_base64(shift) .'='; } elsif ($scheme eq 'none') { return $_[0]; } else { Carp::croak("unknown encryption method '$_'"); } return $passwd; } sub salt { my($newstyle) = @_; return defined($newstyle) && $newstyle ? join('', "_", randchar(1), "a..", randchar(4)) : randchar(2); } my(@saltset) = (qw(. /), 0..9, "A".."Z", "a".."z"); sub randchar { local($^W) = 0; #we get a bogus warning here my($count) = @_; my $str = ""; $str .= $saltset[rand(@saltset)] while $count--; $str; } sub DESTROY { } #These should work fine with the _generic classes my %Support = (apache => [qw(DBM Text SQL)], ncsa => [qw(DBM Text)], ); CGI::Builder::Auth::UserAdmin->support(%Support); 1; __END__ =head1 NAME CGI::Builder::Auth::UserAdmin - Management of HTTP server user databases =head1 SYNOPSIS use CGI::Builder::Auth::UserAdmin (); =head1 DESCRIPTION. =head1 METHODS =over 4 =item new () Here's where we find out what's different about your server. Some examples: @DBM = (DBType => 'DBM', DB => '.ht who's mSQL database is named 'www', with a schema that the Apache server (extention) understands. Full list of constructor attributes: Note: Attribute names are case-insensitive B<DBType> - The type of database, one of 'DBM', 'Text', or 'SQL' (Default is 'DBM') B<DB> - The database name (Default is '.htpasswd' for DBM & Text databases) B<Server> - HTTP server name (Default is the generic class, that works with NCSA, Apache and possibly others) Note: run 'perl t/support.t matrix' to see what support is currently availible B<Encrypt> - One of 'crypt', 'MD5', or 'none' (no encryption. Defaults to 'crypt' B<Locking> - Boolean, Lock Text and DBM files (Default is true) B<Path> - Relative DB files are resolved to this value (Default is '.') B<Debug> - Boolean, Turn on debug mode B<Flags> - The read, write and create flags. There are four modes: B<rwc> - the default, open for reading, writing and creating. B<rw> - open for reading and writing. B<r> - open for reading only. B<w> - open for writing only. Specific to DBM files: B<DBMF> - The DBM file implementation to use (Default is 'NDBM') B<Mode> - The file creation mode, defaults to '0644' Specific to DBI: We talk to an SQL server via Tim Bunce's DBI interface. For more info see: B<Host> - Server hostname B<Port> - Server port B<User> - Database login name B<Auth> - Database login password B<Driver> - Driver for DBI (Default is 'mSQL') B<UserTable> - Table with field names below B<NameField> - Field for the name (Default is 'user') B<PasswordField> - Field for the password (Default is 'password') From here on out, things should look the same for everyone. =item add($username,$password,[@fields]) =item add($username,$password,\%fields) Add a user. Fails if $username exists in the database if($user->add('dougm', 'secret')) { print "You have the power!\n"; } You may need to pass additional fields, such as the user's real name. This depends on your server of course. $user->add('JoeUser', 'try2guess', '', 'Joseph A. User'); You can also pass a set of field name/value pairs in the form of a hash ref. Example $user->add('JoeUser','try2guess','', {'Name'=>'Joseph A. User','Credit_limit'=>2000}); =item delete($username) Delete a user if($user->delete('dougm')) { print "He's gone\n"; } =item suspend($username) Suspend a user if($user->suspend('dougm')) { print "Account suspended\n"; } =item unsuspend($username) Unsuspend a suspended user if($user->unsuspend('dougm')) { print "Account restored to normal\n"; } =item exists($username) True if $username is found in the database if($user->exists('dougm')) { die "oh no!"; } =item password() Returns the encrypted password for a user $passwd = $user->password("dougm"); Useful for copying users to another database. =item fetch($username,@fields) Fetch a list of field values from the indicated user. Field names may be provided as a list or as an array reference. The return value is a reference to a hash containing the field/value pairs. =item list() Returns a list of usernames in the current database @users = $user->list =item update($username,$password) =item update($username,$password,\%fields) B<SQL only> Update $username with a new $password if($user->update('dougm', 'idunno')) { print "Updated\n"; } With SQL servers, you can update other fields in the table by passing a hash reference: $user->update('dougm','idunno',{'credit_limit'=>1000}); An undefined value in the password field will leave the field unchanged. =item group() Short cut for creating an CGI::Builder::Auth::GroupAdmin object. All applicable attributes are inherited, but can be overridden. $group = $user->group(NAME => 'www-group'); (See CGI::Builder::Auth::GroupAdmin) =item convert(@Attributes) Convert a database. $dbmuser = $user->convert(@Apache); =item lock([$timeout]) =item unlock() These methods give you control of the locking mechanism. $user = new CGI::Builder::Auth::UserAdmin (Locking => 0); #turn off auto-locking $user->lock; #lock the object's database $user->add($username,$passwd); #write while file is locked $user->unlock; release the lock =item db($dbname); Select a different database. $olddb = $user->db($newdb); print "Now we're reading and writing '$newdb', done with '$olddb'n\"; =item flags([$flags]) Get or set read, write, create flags. =item commit Commit changes to disk (for Text files). =back =head1 Message Digest User Databases Currently, you can store user info in a format for servers who support Message Digest Authentication. Here's an example: $user = new CGI::Builder::Auth::UserAdmin (DB => '.htdigest', Encrypt => 'MD5'); ($username,$realm,$password) = ('JoeUser', 'SomePlace', '14me'); #The checksum contains more info that just a password $user->add($username, "$username:$realm:$password"); $user->update($username, "$username:$realm:newone"); $info = $user->password($username); ($realm, $checksum) = split(":", $info); $user->delete($username); See <URL:> for NCSA's implementation. So, it's a little more work, but don't worry, a nicer interface is on the way. =head1 SEE ALSO CGI::Builder::Auth::GroupAdmin(3), CGI::Builder::Auth::Authen(3) =head1 AUTHOR Doug MacEachern <dougm@osf.org> Copyright (c) 1996, Doug MacEachern This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
https://metacpan.org/dist/CGI-Builder-Auth/source/lib/CGI/Builder/Auth/UserAdmin.pm
CC-MAIN-2022-05
refinedweb
1,509
52.6
When doing TDD, or testing in general, on Android there's a lot of time you'll encounter an exception like the following java.lang.RuntimeException: Method {{METHOD}} in {{FQD.CLASS}} not mocked. See for details. This is just saying that a call into the Android system components has happened. There's a gradle flag that's shown at the link in the exception message; android { // ... testOptions { unitTests.returnDefaultValues = true } } which will prevent the exception. I have VERY STRONG reservations about this. Doing this allows some code paths to get by. It'll start to mask the actual problem though. You'll start to get NullPointerExceptions; because the default for a lot of things is null which then a method is called on... and BAM! NPE. This is bad; it inhibits further testing around that code flow. It's a hack to allow bad design. I like to get the explicit not mocked exception as it's very clear what's breaking and where. It's the first call into the Android system. The fix to this is to "wrap" the calls to the OS in a class that can be toggled during tests. I also have one in VBM in Android in the series of posts using the DateUtils. This approach; I feel; works for any boundary. While I'm against methods explicitly for test code in the deployed code - Boundaries are an exception. Being able to test is more important than preventing test only code in deployable code. AlertDialog I've done this before with the AlertDialog and have a couple ways around this. Array Store The first; that I used in an experiment project before is to create a class with an array of AlertDialogs. Something like (won't compile; consider it psuedo-java) public class AlertDialogFactory{ public final static void SOME_DIALOG = 0; /* package */ final static HashMap<AlertDialog> Dialogs = ...; public static AlertDialog factory(final int dialog){ if(Dialogs.get(dialog) == null){ Dialogs.put(dialog, new AlertDialog.Builder()......); } return Dialogs.get(dialog); } Then from the test; just shove a fake/mock value into the HashMap and when the code calls in; it'll return the faked object. This fake will then be called and methods controlled. What I don't like about the Array-Store mechanism is that it removes ALL of the AlertDialog building into a single class. That's not ideal. It becomes a god class for AlertDialogs. It breaks encapsulation, simple design, and single responsibility. That class then changes for as many reasons as alert dialogs. Program to the interface The next is using an interface - SHOCKER! I've got together an interface wrapping the functionality of a Dialog. I've adapted this from a github project. My version follows pretty close? public abstract class DialogBuilder<T extends Dialog> { public abstract DialogBuilder setTitle(int titleId); public abstract T show(); ... } Inside this I've created slug-implementations public abstract class DialogBuilder<T extends Dialog> { /* package */ static final DialogBuilder V7 = new DialogBuilder<android.support.v7.app.AlertDialog>() { private android.support.v7.app.AlertDialog.Builder builder; @Override public DialogBuilder init(Context context) { builder = new android.support.v7.app.AlertDialog.Builder(context); return this; } } Additional implementations can exist; like the non-support library version. Once the implementation(s) are in place; we wrap the DialogBuilder to set and utilize a specific dialog builder. This follows a pattern I set in place in the Android Logger for switching between using the android.util.Log and System.out. The AlertDialogBuilder is what will be utilized in code instead of the AlertDialog$Builder public class AlertDialogBuilder<T extends Dialog> extends DialogBuilder<T> { private static DialogBuilder ActiveDialogBuilder = DialogBuilder.V7; /* package */ static void setActiveDialogBuilder(final DialogBuilder dialogBuilder){ ActiveDialogBuilder = dialogBuilder; } ... } setActiveDialogBuilder allows configuration of what implementation to use... also known as, "Makes it testable". While I loathe code specific for tests; there are two aspects in play here. It's a boundary. We play different at boundaries. We need a way to fake it. It's not a TEST ONLY method. It's a way to configure the class. I've seen a method in production code (on a singleton, so there's some questionable decisions happening) that was getInstanceForTest... That's code in production for test. Now that we have a way to configure how AlertDialogs are constructed; we can extend DialogBuilder in our Unit Tests. I have a FakeDialogBuilder that I can use in a test like public void someTest(){ final FakeDialogBuilder fakeDialogBuilder = new FakeDialogBuilder(); AlertDialogBuilderAccess.setActiveDialogBuilder(fakeDialogBuilder); } This approach can be used to either test the AlertDialog was constructed and called correctly; or to beable to pass by a cosntruction/use of a dialog. Though; the second seems like it shouldn't happen. But sometimes as you refactor technical debt; you'll need to bypass initially. This works - I'm using it in my HackerNews App(LINK) and it looks super promising for flexibility in UI testing. Downside at the time of writing; the base is from somewhere else - No tests. TIME TO TEST THIGNS! The test writing will be part of the HackerNews app. I'm glad to find a clean and flexibile solution to working with AlertDialogs in Android.
https://quinngil.com/2017/03/26/testing-android-alert-dialog/
CC-MAIN-2020-29
refinedweb
859
59.7
So far, we have learned the basics of Rust syntax, developed a custom Kubernetes controller, and integrated with the front-end with Wasm. I've been using the JVM for two decades now, mainly in Java. The JVM is a fantastic piece of technology. IMHO, its most significant benefit is its ability to adapt the native code to the current workload; if the workload changes and the native code is not optimal, it will recompile the bytecode accordingly. On the other side,. While GC algorithms have improved over time, GC itself is still a big complex machine. Fine-tuning GC is complex and depends heavily on the context. What worked yesterday might not work today. All in all, configuring the JVM for the best handling of GC in your context is like magic. As the ecosystem around the JVM is well developed, it makes sense to develop applications using the JVM and delegate the parts that require predictability to Rust. Existing alternatives for JVM-Rust integration During the research for this post, I found quite a couple of approaches for JVM-Rust integration: Asmble: Asmble is a compiler that compiles WebAssembly code to JVM bytecode. It also contains an interpreter and utilities for working with WASM code from the command line and from JVM languages. -- Asmble is released under the MIT License but is not actively maintained (the last commit is from 2 years ago). GraalVM: GraalVM is a high-performance JDK distribution designed to accelerate the execution of applications written in Java and other JVM languages along with support for JavaScript, Ruby, Python, and a number of other popular languages. GraalVM’s polyglot capabilities make it possible to mix multiple programming languages in a single application while eliminating foreign language call costs. -- GraalVM allows to run LLVM bitcode. Rust can compile to LLVM. Hence, GraalVM can run your Rust-generated LLVM code along with your Java/Scala/Kotlin/Groovy-generated bytecode. jni crate: This crate provides a (mostly) safe way to implement methods in Java using the JNI. Because who wants to actually write Java? -- JNI has been the way to integrate C/C++ with Java in the past. While it's not the most glamorous approach, it requires no specific platform and is stable. For this reason, I'll describe it in detail in the next section. Integrating Java and Rust via JNI From a bird's eye view, integrating Java and Rust requires the following steps: - Create the "skeleton" methods in Java - Generate the C headers file from them - Implement them in Rust - Compile Rust to generate a system library - Load the library from the Java program - Call the methods defined in the first step. At this point, the library contains the implementation, and the integration is done. Old-timers will have realized those are the same steps as when you need to integrate with C or C++. It's because they also can generate a system library. Let's have a look at each step in detail. Java skeleton methods We first need to create the Java skeleton methods. In Java, we learn that methods need to have a body unless they are abstract. Alternatively, they can be native: a native method delegates its implementation to a library. public native int doubleRust(int input); Next, we need to generate the corresponding C header file. To automate generation, we can leverage the Maven compiler plugin: <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <compilerArgs> <arg>-h</arg> <!--1--> <arg>target/headers</arg> <!--2--> </compilerArgs> </configuration> </plugin> - Generate header files... - ...in this location The generated header of the above Java snippet should be the following: #include <jni.h> #ifndef _Included_ch_frankel_blog_rust_Main #define _Included_ch_frankel_blog_rust_Main #ifdef __cplusplus extern "C" { #endif /* * Class: ch_frankel_blog_rust_Main * Method: doubleRust * Signature: (I)I */ JNIEXPORT jint JNICALL Java_ch_frankel_blog_rust_Main_doubleRust (JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif Rust implementation Now, we can start the Rust implementation. Let's create a new project: cargo new lib-rust [package] name = "dummymath" version = "0.1.0" authors = ["Nicolas Frankel <nicolas@frankel.ch>"] edition = "2018" [dependencies] jni = "0.19.0" // 1 [lib] crate_type = ["cdylib"] // 2 - Use the jnicrate - Generate a system library. Several crate types are available: cdylibis for dynamic system libraries that you can load from other languages. You can check all other available types in the documentation. Here's an abridged of the API offered by the crate: The API maps one-to-one to the generated C code. We can use it accordingly: #[no_mangle] pub extern "system" fn Java_ch_frankel_blog_rust_Main_doubleRust(_env: JNIEnv, _obj: JObject, x: jint) -> jint { x * 2 } A lot happens in the above code. Let's detail it. - The no_manglemacro tells the compiler to keep the same function signature in the compiled code. It's crucial as the JVM will use this signature. - Most of the times, we use externin Rust functions to delegate the implementations to other languages: this is known as FFI. It's the same as we did in Java with native. However, Rust also uses externfor the opposite, i.e., to make functions callable from other languages. - The signature itself should precisely mimic the code in the C header, hence the funny-looking name - Finally, xis a jint, an alias for i32. For the record, here's how Java primitives map to Rust types: We can now build the project: cargo build The build produces a system-dependent library. For example, on OSX, the artifact has a dylib extension; on Linux, it will have a so one, etc. Use the library on the Java side The final part is to use the generated library on the Java side. It requires first to load it. Two methods are available for this purpose, System.load(filename) and System.loadLibrary(libname). load() requires the absolute path to the library, including its extension, e.g., /path/to/lib.so. For applications that need to work across systems, that's unpractical. loadLibrary() allows you to only pass the library's name - without extension. Beware that libraries are loaded in the location indicated by the java.library.path System property. public class Main { static { System.loadLibrary("dummymath"); } } Note that on Mac OS, the lib prefix is not part of the library's name. Working with objects The above code is pretty simple: it involves a pure function, which depends only on its input parameter(s) by definition. Suppose we want to have something a bit more involved. We come up with a new method that multiplies the argument with another one from the object's state: public class Main { private int state; public Main(int state) { this.state = state; } public static void main(String[] args) { try { var arg1 = Integer.parseInt(args[1]); var arg2 = Integer.parseInt(args[2]); var result = new Main(arg1).timesRust(arg2); // 1 System.out.println(arg1 + "x" + arg2 + " = " + result); } catch (NumberFormatException e) { throw new IllegalArgumentException("Arguments must be ints"); } } public native int timesRust(int input); } - Should compute arg1 * arg2 The native method looks precisely the same as above, but its name. Hence, the generated C header also looks the same. The magic needs to happen on the Rust side. In the pure function, we didn't use the JNIEnv and JObject parameters: JObject represents the Java object, i.e., Main and JNIEnv allows accessing its data (or behavior). #[no_mangle] pub extern "system" fn Java_ch_frankel_blog_rust_Main_timesRust(env: JNIEnv, obj: JObject, x: jint) -> jint { // 1 let state = env.get_field(obj, "state", "I"); // 2 state.unwrap().i().unwrap() * x // 3 } - Same as above - Pass the object's reference, the field's name in Java and its type. The type refers to the correct JVM type signature, e.g. "I"for int. stateis a Result<JValue>. We need to unwrap it to a JValue, and then "cast" it to a Result<jint>via i() Conclusion In this post, we have seen how to call Rust from Java. It involves flagging methods to be delegated as native, generating the C header file, and using the jni crate. We have only scraped the surface with simple examples: yet, we've laid the road to more complex usages. The complete source code for this post can be found on Github: To go further: Originally published at A Java Geek on July 18th, 2021 Top comments (0)
https://dev.to/nfrankel/rust-and-the-jvm-1jbg
CC-MAIN-2022-40
refinedweb
1,374
56.66
setsockopt fails with EOPNOTSUPP When trying to run the LoRa ABP example code (from) on a LOPY, the following line: s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) fails with EOPNOTSUPP. From the console, this happens: Connecting to a Pycom device... Connected >>> s2=socket.socket(socket.AF_LORA,socket.SOCK_RAW) >>> s2.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 95] EOPNOTSUPP >>> os.uname() (sysname='LoPy', nodename='LoPy', release='1.6.7.b1', version='v1.8.6-493-g99ac80fe on 2017-03-03', machine='LoPy with ESP32', lorawan='1.0.0') Any ideas? - ksamuelson last edited by This post is deleted! @jmarcelino Thanks for the quick reply. Yes, I'm in US915, and setting it to 3 does solve the issue. Now to figure out how to view what I'm sending from the LoPy to the mLinux Conduit gateway... :-/ - jmarcelino last edited by SO_DR (datarate) 5 is only available in LoRa 868Mhz (EU868). Are you in a different region? For US915 it should be 3. I'm experiencing the same problem. Was there ever any resolution to this based on the OP? Use spaces in your keys Hi @bbfnq! Apologies, I've been travelling without access to a LoPy the last couple of days - I did try it on the weekend at a hackathon I was at and there didn't seem to be any problems - I'll have a go at it when I'm back at the office tomorrow! @bucknall Hi - just wondered if you had had any success looking at this? Is there any more information I might provide to help? The code is exactly as in the example (except that the keys are different).('26011769'.replace(' ','')))[0] nwk_swkey = binascii.unhexlify('E44A1E59045F3CDD81A2606491F626D1'.replace(' ','')) app_swkey = binascii.unhexlify('85FFDD197900F1AD6D86F3E7DD9F46FC'.replace(' ','')) # non-blocking s.setblocking(False) # send some data s.send(bytes([0x01, 0x02, 0x03])) # get any data received... data = s.recv(64) print(data) from machine import UART import os uart = UART(0, 115200) os.dupterm(uart) Running the code (either by resetting the PyCom, or by pressing the Run button in Pymakr) results in the following at the console: Traceback (most recent call last): File "main.py", line 21, in <module> OSError: [Errno 95] EOPNOTSUPP Also from the console: >>> os.uname() (sysname='LoPy', nodename='LoPy', release='1.6.7.b1', version='v1.8.6-493-g99ac80fe on 2017-03-03', machine='LoPy with ESP32', lorawan='1.0.0') We have 2 LoPy boards and the problem occurs with both. Thanks. Hi @bbfnq I'm trying to recreate what's happening with your code, are you running anything in your main.py script? Thanks!
https://forum.pycom.io/topic/848/setsockopt-fails-with-eopnotsupp
CC-MAIN-2018-39
refinedweb
444
68.77
A lightweight and relaxed game engine for Python. Project description Pylash Engine Latest Version: 2.0.0 Pylash is a modern and cross-platform 2D game engine written in Python. With modern and practical interfaces provided by pylash, you can create games in an easy and relaxed way. License Why Pylash - Cross-platform. Leveraging compatibility of the underlying engine PySide2, pylash supports many mainstream platforms including Ubuntu, macOS and Windows. - Easy-to-use APIs. Pylash adopts ActionScript-like interface designs to raise the efficiency of game developing. - Lightweight. Pylash does not come with piles of third-party tools and frameworks. - Comprehensiveness. Pylash is a universal framework and provides various object-oriented interfaces including display of images, text and vector graphics, collision detection, tween animation, multimedia, etc. Installation $ pip install pylash-engine Hello World Program Create a Python file and open it with your favorite text editor. Type in the code below: from pylash.core import init, addChild from pylash.display import TextField def main(): txt = TextField() txt.text = "Hello World" txt.size = 40 txt.x = txt.y = 100 addChild(txt) init(30, "Hello World", 400, 300, main) Run the Python file and you will get a window with a "Hello World" text. Contributing This project is hosted on Github. Issue reports and pull requests are welcome. In addition, you can drop me an email if you have any question or suggestion. - My email: wangyuehao1999@gmail.com Example Screenshots - Find Character - Get Fruits - Tower Defense Changelog for 2.0.0 - Port base engine from PyQt4 to PySide2. - Removed modules: text, system, net. - Renamed modules: utils=> core. - Added loadersmodule, providing various loaders for different resource types. - Moved TextFieldclass and related classes to displaymodule. - Enhanced LineEditclass: added focus-in event and focus-out event. - Substitute Phonon with QtMultimedia as multimedia engine. - Added Videoclass in mediamodule for displaying videos. - Improved event system. Listener will not receive an event dispatcher as the parameter anymore. - Added more demo. - Added docstring for coremodule. 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/pylash-engine/
CC-MAIN-2020-10
refinedweb
353
53.47
The noexcept operator is used to determine whether a function can throw. Let's start with a simple example: #include <iostream>#include <stdexcept>void foo(){ std::cout << "The answer is: 42\n";}int main(void){ std::cout << std::boolalpha; std::cout << "could foo throw: " << !noexcept(foo()) << '\n'; return 0;} This results in the following: As shown in the preceding example, we defined a foo() function that outputs to stdout. We don't actually execute foo() but, instead, we use the noexcept operator to check to see whether the foo() function could throw. As you can see, the answer is yes; this function can throw. This is because ...
https://www.oreilly.com/library/view/advanced-c-programming/9781838559915/359f47f9-4e1d-4b31-9e7f-6d2a80f58b08.xhtml
CC-MAIN-2021-43
refinedweb
107
63.9
What is Workbox Background Sync? When you send data to a web server, sometimes the requests will fail. It may be because the user has lost connectivity, or it may be because the server is down; in either case you often want to try sending the requests again later. The new BackgroundSync API is an ideal solution to this problem. When a service worker detects that a network request has failed, it can register to receive a sync event, which gets delivered when the browser thinks connectivity has returned. Note that the sync event can be delivered even if the user has left the application, making it much more effective than the traditional method of retrying failed requests. Workbox Background Sync is designed to make it easier to use the BackgroundSync API and integrate its usage with other Workbox modules. It also implements a fallback strategy for browsers that don't yet implement BackgroundSync. Browsers that support the BackgroundSync API will automatically replay failed requests on your behalf at an interval managed by the browser, likely using exponential backoff between replay attempts. In browsers that don't natively support the BackgroundSync API, Workbox Background Sync will automatically attempt a replay whenever your service worker starts up. Basic Usage The easiest way to use Background Sync is to use the Plugin that will automatically Queue up failed requests and retry them when future sync events are fired. import {BackgroundSyncPlugin} from 'workbox-background-sync'; import {registerRoute} from 'workbox-routing'; import {NetworkOnly} from 'workbox-strategies'; const bgSyncPlugin = new BackgroundSyncPlugin('myQueueName', { maxRetentionTime: 24 * 60 // Retry for max of 24 Hours (specified in minutes) }); registerRoute( /\/api\/.*\/*.json/, new NetworkOnly({ plugins: [bgSyncPlugin] }), 'POST' ); Advanced Usage Workbox Background Sync also provides a Queue class, which you can instantiate and add failed requests to. The failed requests are stored in IndexedDB and are retried when the browser thinks connectivity is restored (i.e. when it receives the sync event). Creating a Queue To create a Workbox Background Sync Queue you need to construct it with a queue name (which must be unique to your origin): import {Queue} from 'workbox-background-sync'; const queue = new Queue('myQueueName'); The queue name is used as part of the tag name that gets register()-ed by the global SyncManager. It's also used as the Object Store name for the IndexedDB database. Adding a request to the Queue Once you've created your Queue instance, you can add failed requests to it. You add failed request by invoking the .pushRequest() method. For example, the following code catches any requests that fail and adds them to the queue: import {Queue} from 'workbox-background-sync'; const queue = new Queue('myQueueName'); self.addEventListener('fetch', (event) => { // Clone the request to ensure it's safe to read when // adding to the Queue. const promiseChain = fetch(event.request.clone()).catch((err) => { return queue.pushRequest({request: event.request}); }); event.waitUntil(promiseChain); }); Once added to the queue, the request is automatically retried when the service worker receives the sync event (which happens when the browser thinks connectivity is restored). Browsers that don't support the BackgroundSync API will retry the queue every time the service worker is started up. This requires the page controlling the service worker to be running, so it won't be quite as effective. Testing Workbox Background Sync Sadly, testing BackgroundSync is somewhat unintuitive and difficult for a number of reasons. The best approach to test your implementation is to do the following: - Load up a page and register your service worker. - Turn off your computer's network or turn off your web server. - ⚠️ DO NOT USE CHROME DEVTOOLS OFFLINE ⚠️ The offline checkbox in DevTools only affects requests from the page. Service Worker requests will continue to go through. - Make network requests that should be queued with Workbox Background Sync. - You can check the requests have been queued by looking in Chrome DevTools > Application > IndexedDB > workbox-background-sync > requests - Now turn on your network or web server. Force an early syncevent by going to Chrome DevTools > Application > Service Workers, entering the tag name of workbox-background-sync:<your queue name>where <your queue name>should be the name of the queue you set, and then clicking the 'Sync' button. You should see network requests go through for the failed requests and the IndexedDB data should now be empty since the requests have been successfully replayed.
https://developers.google.com/web/tools/workbox/modules/workbox-background-sync?hl=zh-cn
CC-MAIN-2021-10
refinedweb
729
51.48
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. On Wed, 2004-01-28 at 03:46, Paolo Carlini wrote: > Hi, > > this is the idea implemented! Honestly, I'm very happy with it: now all > the "magic numbers" are only in one place (instead of three!), and the > encapsulation is much better. > > I have tested the patch on x86-linux, I would like to do some additional > tests and, if everything goes well, commit to mainline (only, of course!) > very soon. I noticed this in the patch: *************** namespace std *** 157,165 **** const size_type __dnew = static_cast<size_type>(std::distance(__beg, __end)); Is it really intended, or would you rather use difference_type on the lhs of the assignment? -- -Dhruv Matani.
http://gcc.gnu.org/ml/libstdc++/2004-01/msg00298.html
crawl-001
refinedweb
126
63.59
You can integrate custom code written in C or C++ with Stateflow® charts in Simulink® models. By sharing data and functions between your custom code and your Stateflow chart, you can augment the capabilities of Stateflow and leverage the software to take advantage of your preexisting code. Stateflow charts call custom code functions by using the same syntax as other reusable functions: return_val = function_name(arg1,arg2,...) Do not share fixed-point data between your custom code and your Stateflow chart. To choose the right procedure for simulation, click the highlighted block that best describes your goal. This example shows how to use custom C code to define constants that apply to all charts in your model. The model contains a Stateflow® chart with an input, which you can set to 0 or 1 by toggling the manual switch in the model during simulation. The chart contains two states A and B. In this example, you define two constants named TRUE and FALSE to guard the transitions between the states in the chart, instead of using the values 1 and 0. These custom definitions improve the readability of your chart actions. TRUE and FALSE are not Stateflow data objects. To enter the custom code that defines the two constants: Open the Model Configuration Parameters dialog box. Select the Simulation Target pane. In the Header file subpane, enter #define and #include statements. For instance, in this example, you define the global constants with this code: #define TRUE 1 #define FALSE 0 Because the two custom definitions appear at the top of the generated machine header file sf_custom_code_global_constants_sfun.h, you can use TRUE and FALSE in all charts that belong to this model. This example show how to use custom C code to define constants, variables, and functions that apply to all charts in your model. The model contains a Stateflow chart with an input signal from a Sine Wave block. The chart contains two states A and B, and three data objects: input_data, local_data, and out_data. The chart accesses a custom variable named my_global and calls a custom function named my_function. To configure the model to access the custom code: Open the Model Configuration Parameters dialog box. Select the Simulation Target pane. In the Header file subpane, enter #define and #include statements. When you include a custom header file, you must enclose the file name in double quotes. In the Include directories subpane, enter the name of the folder that contains your custom code files. To access custom code files in a subfolder of the model folder, use a relative path name of the form .\subfolder_name. In the Source files subpane, enter the name of the source file that contains your custom code. To access a source file that resides in a subfolder of the model folder, use a relative path name of the form .\subfolder_name\source_file.c. In this example, the custom code defines three constants, a variable, and a function by using these configurations: The Header file subpane contains this statement: #include "sf_custom_code_constants_vars_fcns_hdr.h" The Include directories subpane contains a single period ( .) to indicate that all of the custom code files reside in the same folder as the model. The Source file subpane contains this file name: sf_custom_code_constants_vars_fcns_src.c The custom header file sf_custom_code_constants_vars_fcns_hdr.h contains the definitions of three constants: #define TRUE 1 #define FALSE 0 #define MAYBE 2 The header file also contains declarations for the variable my_global and the function my_function: extern int myglobal; extern int my_function(int var1, double var2); The custom source file sf_custom_code_constants_vars_fcns_src.c is compiled in conjunction with the Stateflow generated code into a single S-function MEX file. Because the custom definitions appear at the top of the generated machine header file sf_custom_code_constants_vars_fcns_sfun.h, you can access them in all charts that belong to this model.
https://uk.mathworks.com/help/stateflow/ug/share-data-using-custom-c-code.html
CC-MAIN-2019-47
refinedweb
634
54.42
> Date: Wed, 4 Jan 2006 14:51:45 -0500 > Cc: address@hidden, address@hidden > From: "Paul D. Smith" <address@hidden> > > The shell (at least in UNIX) is only used in the slow path. The fast > path does a direct exec() (or CreateProcess() in Windows?) I'm assuming > that direct invocation preserves pipes. > > I just mean that there are other requirements on the operating system > itself, such as proper support for pipes, signal handling, etc. > > But I think the only requirements on the shell are that it not interfere > with the pipes that the parent make passes to its child makes. > > ez> Anyway, if file handle inheritance is the only requirement on > ez> Posix systems that allows -jN, then the proposed patch does > ez> nothing in this area on Windows. I guess it is dealing with some > ez> Windows-specific aspect of Make, perhaps the invocation via batch > ez> files. > > Yes, that might be an issue. I looked at this, and I see no problem to enable -jN on Windows even if a Unixy shell is not available. The suggested patches are attached below; besides removing the forceful limitation to -j1, they also modify job.c to avoid a small window of possible race condition between creating a temporary batch file and using it to write the batch script into it. I tested the (MinGW build of) ported Make thus patched using the tests in the `parallelism' script from the test suite. To test them with cmd.exe, I needed to replace ";" with "&&" in multi-line commands of the Makefiles, because that is how cmd.exe supports several commands on the same line. With this change, all the tests but one passed on Windows with cmd.exe and produced the expected results. To be on the safe side, I also ran Make with --debug=j and looked at the output: I didn't notice anything that would indicate some kind of trouble. The only test that didn't work as the test suite expected was the one that first recurses. It didn't work for both flavors of the shell, so the problem is not related to the shell. Here's the Makefile it creates for the Unixy shell: recurse: ; @$(MAKE) --no-print-directory -f tmp.mkf INC=yes all all: 1 2; @echo success INC = no ifeq ($(INC),yes) -include 1.inc 2.inc endif 1.inc: ; @echo ONE.inc; sleep 2; echo TWO.inc; echo '1: ; @echo ONE; sleep 2; echo TWO' > $@ 2.inc: ; @sleep 1; echo THREE.inc; echo '2: ; @sleep 1; echo THREE' > $@ The required output, when Make is invoked with -j4, is: ONE.inc THREE.inc TWO.inc ONE THREE TWO success What I get instead (no matter what shell I use) is this: THREE.inc ONE.inc TWO.inc ONE TWO THREE success I think this might be related to the fact that the Windows port does not support MAKE_JOBSERVER. Paul, could that be the reason? is this test supposed to work without the job server? Something else possibly related is this: I added to the Makefile a command to print the value of MAKEFLAGS. On a GNU/Linux machine, the value I get is: --no-print-directory - --jobserver-fds=3,4 -j - -- INC=yes However, on Windows, I get this instead: --no-print-directory -- INC=yes Note the absence of -j. If I add "-j" to the Make invocation command in the `recurse' target, the test succeeds, i.e. it produces the expected results, both with sh.exe and with cmd.exe! In addition, if I add "-j4" instead of "-j", the sub-Make receives "-j 1", which surprised me. Is all this expected when MAKE_JOBSERVER is not supported, or is this due to bug(s) that I need to look for? Finally, here are the patches to allow -jN without a Unixy shell; I hope it's not too late to include them in the coming release: 2006-01-14 Eli Zaretskii <address@hidden> *. --- main.c~1 2005-12-17 14:31:39.375000000 +0200 +++ main.c 2006-01-14 13:44:27.843750000 +0200 @@ -1595,12 +1595,6 @@ main (int argc, char **argv, char **envp /* look one last time after reading all Makefiles */ if (no_default_sh_exe) no_default_sh_exe = !find_and_set_default_shell(NULL); - - if (no_default_sh_exe && job_slots != 1) { - error (NILF, _("Do not specify -j or --jobs if sh.exe is not available.")); - error (NILF, _("Resetting make for single job mode.")); - job_slots = 1; - } #endif /* WINDOWS32 */ #if defined (__MSDOS__) || defined (__EMX__) --- job.c~1 2005-12-17 14:34:20.796875000 +0200 +++ job.c 2006-01-14 14:00:00.921875000 +0200 @@ -242,11 +242,12 @@ w32_kill(int pid, int sig) return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1); } -/* This function creates a temporary file name with the given extension - * the unixy param controls both the extension and the path separator - * return an xmalloc'ed string of a newly created temp file or die. */ +/* This function creates a temporary file name with an extension specified + * by the unixy arg. + * Return an xmalloc'ed string of a newly created temp file and its + * file descriptor, or die. */ static char * -create_batch_filename(char const *base, int unixy) +create_batch_file (char const *base, int unixy, int *fd) { const char *const ext = unixy ? "sh" : "bat"; const char *error = NULL; @@ -304,7 +305,7 @@ create_batch_filename(char const *base, const unsigned final_size = path_size + size + 1; char *const path = (char *) xmalloc (final_size); memcpy (path, temp_path, final_size); - CloseHandle (h); + *fd = _open_osfhandle ((long)h, 0); if (unixy) { char *p; @@ -317,6 +318,7 @@ create_batch_filename(char const *base, } } + *fd = -1; if (error == NULL) error = _("Cannot create a temporary file\n"); fatal (NILF, error); @@ -2755,19 +2757,21 @@ construct_command_argv_internal (char *l command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these cases, run commands via a script file. */ if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) { + int temp_fd; FILE* batch = NULL; int id = GetCurrentProcessId(); PATH_VAR(fbuf); /* create a file name */ sprintf(fbuf, "make%d", id); - *batch_filename_ptr = create_batch_filename (fbuf, unixy_shell); + *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd); DB (DB_JOBS, (_("Creating temporary batch file %s\n"), *batch_filename_ptr)); - /* create batch file to execute command */ - batch = fopen (*batch_filename_ptr, "w"); + /* Create a FILE object for the batch file, and write to it the + commands to be executed. */ + batch = _fdopen (temp_fd, "w"); if (!unixy_shell) fputs ("@echo off\n", batch); fputs (command_ptr, batch); --- README.W32~ 2005-12-13 18:47:25.000000000 +0200 +++ README.W32 2006-01-14 18:08:44.875000000 +0200 @@ -90,14 +90,11 @@ To work around this difficulty, this version of make supports a batch mode. When BATCH_MODE_ONLY_SHELL is defined at compile time, make forces all command lines to be executed via script - files instead of by command line. In this mode you must have a - working sh.exe in order to use parallel builds (-j). + files instead of by command line. A native Windows32 system with no Bourne shell will also run in batch mode. All command lines will be put into batch files - and executed via $(COMSPEC) (%COMSPEC%). Note that parallel - builds (-j) require a working Bourne shell; they will not work - with COM. + and executed via $(COMSPEC) (%COMSPEC%). GNU make and Cygnus GNU Windows32 tools: --- NEWS~ 2005-12-17 19:36:03.234375000 +0200 +++ NEWS 2006-01-14 18:10:40.609375000 +0200 @@ -106,6 +106,10 @@ the DOS command interpreter in batch mode even if a UNIX-like shell could be found on the system. +* Parallel builds (-jN) no longer require a working Bourne shell on + MS-Windows. They work even with the stock Windows shells, such as + cmd.exe and command.com. + * Updated to autoconf 2.59, automake 1.9.5, and gettext 0.14.1. Users should not be impacted.
http://lists.gnu.org/archive/html/make-w32/2006-01/msg00045.html
CC-MAIN-2013-48
refinedweb
1,271
75.3
flutter_staggered_grid_view A Flutter staggered grid view which supports multiple columns with rows of varying sizes. Features - Configurable cross-axis count or max cross-axis extent like the GridView - Tiles can have a fixed main-axis extent, or a multiple of the cell's length. - Configurable main-axis and cross-axis margins between tiles. - SliverStaggeredGrid for using in a CustomScrollView. - Staggered and Spannable grid layouts. - Tiles can fit the content in the main axis. Getting started In the pubspec.yaml of your flutter project, add the following dependency: dependencies: ... flutter_staggered_grid_view: "^0.2.7" In your library add the following import: import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; For help getting started with Flutter, view the online documentation. Example new StaggeredGridView.countBuilder( crossAxisCount: 4, itemCount: 8, itemBuilder: (BuildContext context, int index) => new Container( color: Colors.green, child: new Center( child: new CircleAvatar( backgroundColor: Colors.white, child: new Text('$index'), ), )), staggeredTileBuilder: (int index) => new StaggeredTile.count(2, index.isEven ? 2 : 1), mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, ) You can find more examples in the Example project. Constructors The StaggeredGridView follow the same constructors convention than the GridView. There are two more constructors: countBuilder and extentBuilder. These constructors allow you to define a builder for the layout and a builder for the children. Tiles A StaggeredGridView needs to know how to display each tile, and what widget is associated with a tile. A tile needs to have a fixed number of cell to occupy in the cross axis. For the extent in the main axis you have 3 options: - You want a fixed number of cells => use StaggeredTile.count. - You want a fixed extent => use StaggeredTile.extent. - You want a variable extent, defined by the content of the tile itself => use StaggeredTile.fit. new feature, please send a pull request.
https://pub.dev/documentation/flutter_staggered_grid_view/latest/
CC-MAIN-2019-30
refinedweb
294
52.46
This document contains information for an outdated version and may not be maintained any more. If some of your projects still use this version, consider upgrading as soon as possible. CSS # Introduction ## SilverStripe strives to keep out of a template designer's way as much as possible - this also extends to how you want to write your CSS. Adding CSS to your template ## You are free to add <style> and <link> tags to your template (typically themes/yourtheme/templates/Page.ss). SilverStripe provides a management layer for javascript and CSS files on top of that with the Requirements class, by adding some simple PHP calls to your controller or template. Some files are automatically included, depending on what functionality you are using (e.g. SilverStripe forms automatically include framework/css/Form.css). In your controller (e.g. mysite/code/Page.php): class Page_Controller { public function init() { // either specify the css file manually Requirements::css("mymodule/css/my.css", "screen,projection"); // or mention the css filename and SilverStripe will get the file from the current theme and add it to the template Requirements::themedCSS('print', 'print'); } } Or in your template (e.g. themes/yourtheme/templates/Page.ss): <% require css(mymodule/css/my.css) %> Management through the Requirements class has the advantage that modules can include their own CSS files without modifying your template. On the other hand, you as a template developer can "block" or change certain CSS files that are included from thirdparty code. WYSIWYG editor: typography.css and editor.css This stylesheet is used to "namespace" rules which just apply in a rendered site and the WYSIWYG-editor of the CMS. This is needed to get custom styles in the editor without affecting the remaining CMS-styles. An example of a good location to use class="typography" is the container element to your WYSIWYG-editor field. The $Content WYSIWYG editor field already comes with SilverStripe out-of-the-box: <!-- This is a good way, you're only applying` `<div id="LeftContent">` `<p>`We have a lot of content to go here.`</p>` `</div>` `<div id="Content" class="typography">` $Content `</div>` `</div>` The typography.css file should contain only styling for these elements (related to the WYSIWYG editor): - Headers (h1 - h6) - Text (p, blockquote, pre) - Lists (ul, li) - CSS alignment (img.left, .left, .right etc) - Tables - Miscellaneous (hr etc) The advantages are that it's fully styled, as a default starting point which you can easily tweak. It also doesn't affect the CMS styling at all (except for the WYSIWYG), which is what we want. It's also separated from the rest of the layout. If you wanted to change typography only, for where you usually edit the content you don't need to go wading through other CSS files related to the actual layout. To get these styles working in the CMS. Eg you use a font you want in the CMS area you need to create an editor.css file. Then with this file you can define styles for the CMS or just import the styles from typography. Unlike typography.css, editor.css is NOT included in the front end site. So this is themes/your_theme/css/editor.css /* Import the common styles from typography like link colors. */ @import 'typography.css'; /* We want the backend editor to have a bigger font as well though */ .typography * { font-size: 200% } See typography for more information. Related ## - javascript - "Compass" module: Allows writing CSS in SASS/LESS syntax, with better code management through mixins, includes and variables - Reference: CMS Architecture - Howto: Extend the CMS Interface
https://docs.silverstripe.org/en/3.0/topics/css
CC-MAIN-2016-40
refinedweb
594
56.05
This notebook demonstrates how regression models for nested data can be estimated using GEE. The data are from a study of GCSE (General Certificate of Seconday Education) exam scores in the UK. We know the school in which each student is enrolled. In addition, the schools are clustered into "local educational areas" (LEA). Thus we have two nested levels of clustering (schools within LEA's). The top level (LEA) can be handled by treating it as the GEE group. The inner level (school) can be handled using a nested dependence structure. All of the models here use a linear link and a Gaussian model for the data. The data are available from: Here are all the libraries that we will need: import numpy as np import pandas as pd import statsmodels.api as sm The data file has no column labels, so we attach them manually. data = pd.read_csv("a-level-chemistry.txt", header=None, sep=' ') data.columns = ["Board", "A-Score", "Gtot", "Gnum", "Gender", "Age", "Inst_Type", "LEA", "Institute", "Student"] The GCSE has several components, and not all students take all of the components. The variable 'Gtot' in the data set is the sum of exam scores over all the components taken by a given student. We divide the score sum by the number of components taken, in order to obtain a mean score that is not inflated just because a student takes more exams. data["GCSE"] = data["Gtot"] / data["Gnum"] Our primary focus here is on the nested dependence structure. For comparison, we will also consider a single-level dependence structure determined only by the school. Since the school codes are recycled across the LEA's, we need to create a new variable that combines the two codes. data["School"] = [str(x) + str(y) for x,y in zip(data["LEA"], data["Institute"])] us = set(data["School"]) us = {x: k for k,x in enumerate(list(us))} data["School"] = [us[x] for x in data["School"]] These are all the variables in the analysis. qdata = data[["GCSE", "Gender", "Age", "LEA", "Institute", "School"]] qdata = np.asarray(qdata) family = sm.families.Gaussian() The initial model considers only the school effect, and does not account for the fact that the schools are nested in LEA's. ex = sm.cov_struct.Exchangeable() model1 = sm.GEE.from_formula("GCSE ~ Age + Gender", "LEA", data=data, family=family, cov_struct=ex) result1 = model1.fit() print result1.summary() GEE Regression Results =================================================================================== Dep. Variable: GCSE No. Observations: 31022 Model: GEE No. clusters: 131 Method: Generalized Min. cluster size: 10 Estimating Equations Max. cluster size: 969 Family: Gaussian Mean cluster size: 236.8 Dependence structure: Exchangeable Num. iterations: 10 Date: Sun, 19 Oct 2014 Scale: 0.738 Covariance type: robust Time: 00:24:19 ============================================================================== coef std err z P>|z| [95.0% Conf. Int.] ------------------------------------------------------------------------------ Intercept 6.0896 0.022 271.745 0.000 6.046 6.134 Age 0.0134 0.001 9.927 0.000 0.011 0.016 Gender 0.3258 0.013 25.641 0.000 0.301 0.351 ============================================================================== Skew: -0.5403 Kurtosis: 0.4449 Centered skew: -0.5121 Centered kurtosis: 0.4452 ============================================================================== The dependence among subjects within a school is fairly weak: print ex.summary() The correlation between two observations in the same cluster is 0.039 Next we fit the model using the nested dependence structure. Since the iterations are somewhat slow, we limit the number of iterations. This may result in a warning message. ne = sm.cov_struct.Nested() model2 = sm.GEE.from_formula("GCSE ~ Age + Gender", "LEA", data=data, family=family, cov_struct=ne, dep_data=data["Institute"]) result2 = model2.fit() #maxiter=10) print result2.summary() GEE Regression Results =================================================================================== Dep. Variable: GCSE No. Observations: 31022 Model: GEE No. clusters: 131 Method: Generalized Min. cluster size: 10 Estimating Equations Max. cluster size: 969 Family: Gaussian Mean cluster size: 236.8 Dependence structure: Nested Num. iterations: 11 Date: Sun, 19 Oct 2014 Scale: 0.758 Covariance type: robust Time: 00:24:42 ============================================================================== coef std err z P>|z| [95.0% Conf. Int.] ------------------------------------------------------------------------------ Intercept 5.9790 0.020 294.902 0.000 5.939 6.019 Age 0.0129 0.001 10.587 0.000 0.010 0.015 Gender 0.3699 0.012 31.882 0.000 0.347 0.393 ============================================================================== Skew: -0.5306 Kurtosis: 0.4397 Centered skew: -0.5020 Centered kurtosis: 0.4395 ============================================================================== The nested dependence structure captures more of the dependence in the data compared to the exchangeable dependence structure. Component 1 is the variation among LEA's. It is fairly weak, suggesting that the schools within a LEA are fairly heterogeneous. The variance among schools within an LEA is stronger, suggesting that students within a school share similar characteristics. Variation among students (residual variance in the table below) is the greatest contributor to the overall variance. print ne.summary() Variance estimates ------------------ Component 1: 0.043 Component 2: 0.176 Residual: 0.539
http://nbviewer.jupyter.org/urls/umich.box.com/shared/static/wt4jlup9nwbt2d69xvm6.ipynb
CC-MAIN-2018-05
refinedweb
805
61.53
Based”)); Namoskar!!! Join the conversationAdd Comment Thats probably my biggest complaint with The XLINQ API. There’s no way to specify a default namespace, so you always end up having to prepend the namespace on every thing you do. Terribly annoying. VB "solved" this by adding some language specific directives (gross). This should just be something easily configurable in the API. If you have a lot of children, you will see a lot of code like (which is very awkward) new XElement(ns+"child") which hints we might need a new way to create XElement that takes a namespace or we could set up a default namespace somewhere @Anonymous, That’s true I am trying to find it out… Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by the I wanted to know how to query an element with prefix
https://blogs.msdn.microsoft.com/wriju/2008/03/21/linq-to-xml-working-with-prefixes/
CC-MAIN-2018-30
refinedweb
148
64.24
For my testing I used: private static final String SKU_PRO = "android.test.purchased"; "com.example.buttonclick" "com.myname.myapp" "com.myname.myapp.purchasedpro" From developer docs: Product ID Product IDs are unique across an app's namespace. A product ID must start with a lowercase letter or a number and must be composed of only lowercase letters (a-z), numbers (0-9), underscores (_), and periods (.). The product ID android.test is reserved, as are all product IDs that start with android.test. Note: Be sure to plan your product ID namespace carefully. You cannot modify an item's product ID after the item is created, and you cannot reuse a product ID within an app.
https://codedump.io/share/YXqO1c7L7wAH/1/android-naming-a-sku
CC-MAIN-2017-04
refinedweb
116
56.86
hurry.raphael 1.4.3.2 hurry.resource style resources for Raphael. hurry.raphael Introduction This library packages Raphael for hurry.resource. It is aware of Raphael's structure and different modes (normal, minified). How to use? You can import Raphael from hurry.raphael and .need it where you want these resources to be included on a page: from hurry import raphael .. in your page or widget rendering code, somewhere .. raphael.need() This requires integration between your web framework and hurry.resource, and making sure that the original resources (shipped in the raphael-build directory in hurry.raphael).raphael before release This section is only relevant to release managers of hurry.raphael. When releasing hurry.raphael, an extra step should be taken. Follow the regular package release instructions, but before egg generation (python setup.py register sdist upload) first execute bin/raphaelprepare. This will download the Raphael library and place it in the egg. (The version number is currently hardcoded in the hurry.raphael.prepare module). CHANGES 1.4.3.2 (2010-10-20) - support hurry.resource 0.10 1.4.3.1 (2010-06-24) - Using Raphael-1.4.3. Download - Author: Jeroen Michiel - Package Index Owner: jmichiel - DOAP record: hurry.raphael-1.4.3.2.xml
http://pypi.python.org/pypi/hurry.raphael/1.4.3.2
crawl-003
refinedweb
208
62.54
CodePlexProject Hosting for Open Source Software I'm writing an action for rule that send an message between user , it is similary to Orchard.Email module Here is my SendMessageActions.cs public interface IActionProvider : IEventHandler { void Describe(dynamic describe); } public class SendMessageActions : IActionProvider { .............. } I also wrote a form file SendMessageForms.cs . When I run the solution , it takes me to Directory Listing pages () , when I try go to or any page, it gave an error about the resource can not be found. And when I delete the implementation IActionProvider from class SendMessageActions, everything works fine, but of course no new action for me in action list I have tried to figure out this for a couple of hours but the problem still resists. Anyone have a solution for this ? Thanks Problem solved , just deleted declaration of my service in SendMessageActions constructor Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://orchard.codeplex.com/discussions/351278
CC-MAIN-2017-09
refinedweb
177
64.1
#include <NCollection_SparseArray.hxx> Dynamically resizable sparse array of objects This class is similar to NCollection_Vector: it works like virtually unlimited array of items accessible by index; however unlike simple Vector it distinguishes items that have been set from the ones that have not been set explicitly. This class can be also seen as equivalence of NCollection_DataMap<Standard_Integer,TheItemType> with the only one practical difference: it can be much less memory-expensive if items are small (e.g. Integer or Handle). The index starts from 0, i.e. should be non-negative. Memory is allocated when item is set by SetValue(). Iterator returns only defined items; the item can be tested for being defined by IsSet(), and undefined by UnsetValue(). The attempt to access the item that has not been set will result in OutOfRange exception in Debug mode; in Release mode this will either return null-filled object or cause access violation. Constructor; accepts size of blocks. Destructor. Explicit assignment operator. Set a value as explicit method. Modification access to the item. Modification access to the item. Exchange the data of two arrays; can be used primarily to move contents of theOther into the new array in a fast way (without creation of duplicated data) Returns number of items in the array. Direct const access to the item. Returns True if the item is defined. Returns True if array is empty. Const access to the item - operator() Access to the item - operator() Set a value at specified index method. Remove the item from array. Direct const access to the item.
https://www.opencascade.com/doc/occt-7.2.0/refman/html/class_n_collection___sparse_array.html
CC-MAIN-2020-05
refinedweb
260
50.23
Post your coolest Arduino tricks that you ever made or try. I wrote an arduino sketch that lets my arduino collect dust in my drawer. >>51456577 I wrote one that makes blink a led every 2 seconds, I applied to Harvard but they were afraid that I would bomb the campus >>51456597 Lol I tried to use one to make a pipboy local mapping function with a ping sensor. >implying anyone on /g/ actually creates anything instead of just consuming >>51456769 you should post the code for 'proof' >>51456830# import time module import time # import gpio module import RPi.GPIO as GPIO # start time variable alpha = 0 # stop time variable beta = 0 # total time variable gamma = 0 # while loop control failsafe variable delta = 0 # distance in centimeters distCM = 0 # distance in inches distIN = 0 # set up gpio pin 11 as output to parallax ping GPIO.setup(11, GPIO.OUT) # be sure there is no signal to parallax ping: pin 11, 0 = False GPIO.output(11, 0) # send parallax ping a high signal: pin 11, 1 = True GPIO.output(11, 1) # set up gpio pin 11 as input from parallax ping GPIO.setup(11, GPIO.IN) GPIO.input(11) # while gpio is false(0) while GPIO.input(11) == 0 and delta < 20: delta = delta + 1 print "A", delta else: # start time alpha = time.time() delta = 0 # while gpio is true(1) and delta loop control failsafe is less than 20 while GPIO.input(11) == 1 and delta < 20: # add one to delta as while loop failsafe delta = delta + 1 print "B", delta else: # stop time beta = time.time() # calculate total time gamma = beta - alpha # print parallax ping value print gamma # Alucard print "What!" # calculate centimeters from time traveled distCM = (34480 * gamma) / 2 # print distance in centimeters print "%.1f" % distCM, "centimeters" # calculate inches from centimeters distIN = distCM / 2.54 # print distance in inches print "%.1f" % distIN, "inches" >>51456843 fake >>51456905 It was a Raspberry Pi with a Ping sensor connected to it. The product failed when the Pi I realized couldn't handle the proper timing. It also had an arduino temp sensor I was working on. I programmed one to control LED lights on my stairs wirelessly when it senses movement.
https://4archive.org/board/g/thread/51456520/your-best-arduino-tricks
CC-MAIN-2018-34
refinedweb
370
70.73
Tamiat CMSTamiat CMS Tamiat headless CMS Made with ❤︎ by Mahmoud Nouman and contributors Support our development with What It Looks LikeWhat It Looks Like Getting StartedGetting Started To get started with Tamiat CMS, you have two options: - Making Tamiat your starting point. - Integrating Tamiat into an existing project. Making Tamiat Your Starting PointMaking Tamiat Your Starting Point - Clone the CMS repository and install the dependencies. # clone the repo git clone # install the dependencies npm install # or yarn - Go to then login with your google account. - then add your project following the steps in the image. - Go to Authentication section and set up your sign-in method after that you will find "add user" Button is active you can now add your Email and Password. you will need them later to login in tamiat. - You now see your UID copy it. now Rename database.rules.json.tmpfile in root folder to database.rules.json then add your UID in here... "rules": { ".write": "auth.uid === 'kkw4UkvxU8UmIDuMInYTh*****'", Navigate to /src/admin/firebase_configand rename config.js.tmpto config.js then get your project configurations from WEB SETUP (in Authentication section of firebase console) and paste them in config.jsfile by replacing the existing ones. Now make these two steps to add storage and Realtime database Run the firebase initcommand (if you haven't installed firebase yet, do so by npm install -g firebase-tools), select your firebase project from the list, use the default database rules already present database.rules.json, choose distas your public directory and configure the project as a single-page app. you can follow this steps here - Make sure .firebasercis created in your project root directory and the file contains the project id of firebase project you created earlier - Now you should first create the dist folder by making npm run buildor yarn buildthen firebase deployto deploy the security rules you just entered. every time you make changes in the code you should to make this steps again - Run the local dev server with npm run devor yarn dev. - Access the admin interface by navigating to localhost:8080/admin. - (Optional) Navigate to Database menu from sidebar to add demo contents from tamiat.config.json - Enjoy! Integrating Tamiat Into an Existing ProjectIntegrating Tamiat Into an Existing Project - Create a new vue.js project based on webpack template. vue init webpack my-project # install webpack template dependencies npm install - Install the required dependencies by Tamiat. cd my-project # install development dependencies npm install node-sass sass-loader --save-dev # install production dependencies npm install moment vue-router bulma firebase vuefire font-awesome vue-quill-editor - In main.jsfile, import the external stylesheets and the necessary plugins and activate them. import router from './router' import VueFire from 'vuefire' import VueQuillEditor from 'vue-quill-editor' // import external stylesheets import fontAwesome from '../node_modules/font-awesome/css/font-awesome.css' import bulma from '../node_modules/bulma/css/bulma.css' Vue.use(VueFire) // activate vuefire plugin Vue.use(VueQuillEditor) // activate vue-quill-editor Remember, don't forget to add the routerproperty to the vue instance. new Vue({ el: '#app', router, // this property should be added to the vue instance template: '<App/>', components: { App } }) - Clean up your App.vuefile by deleting the extra content and making it similar to that: <template> <div id="app"> <router-view></router-view> </div> </template> - Now, open the Tamiat CMS repo and copy the following folders and files: Folders to be copied:Folders to be copied: Once this is done, you can just follow the same instructions of the first option above starting from step 2. Enjoy! FeaturesFeatures RoutingRouting In Tamiat CMS, there are reserved routes that are built in the CMS itself as well as dynamic routes that you can create yourself. What benefit it offersWhat benefit it offers With dynamic routes you are in complete control and have the total freedom about the presentation of your content. You can associate the content that you want with the template that you want and give them the url that you want. How to create a dynamic routeHow to create a dynamic route In order to create a dynamic route you have to go to the Routing section in Tamiat admin area. On the right side, you can see the reserved routes in the CMS (you can not create dynamic routes with these paths). On the left side you see the form that you need to fill in to create a new dynamic route. This form consists of 4 inputs: - The route path - The route template - The route content type - The route content The only required fields in the form are path & template. The other fileds: Content type & Content are optional since some templates are static and don't accept any dynamic content to show. This type of templates shows static content instead (like the default After you fill in the form and click the add button, the dynamic route will be created and added to the Dynamic routes on the right hand side. There, you can test it by clicking on the path link that will open the new route in a new browser tab. After the creation of the new route, you will have options to edit all it's components (path, template, content type & content) in addition to completely deleting it. You just need to hove over the created route to see those control buttons. In order to create a route that lists content of a certain type and has the ability to display instances of it dynamically two dynamic routes need to be created (one that uses a template that displays a list of all instances and one that uses a template that can fetch only a certain instance based on route params) What about creating new templatesWhat about creating new templates Creating new templates is very easy. All you have to do is: - Create a new MyTemplate.vuefile in /src/app/templatesfolder. <template> <div class="template"> <h1>Hello, I am a new template</h1> </div> </template> - Add some info about the new template to /src/app/templates/templates.jsonas in the following snippet of code: [ ... { "filename": "MyTemplate", // the name of the file you created without ".vue" extension "displayName": "My New Template" // The name you want your template to be called in the Routing page } ... ] Static vs dynamic templatesStatic vs dynamic templates Static templates are templates that contains only hard coded content. They can not be used to show dynamic content (ex: the AboutUs default template). here is the minimal code for a static template: <template> <div class="template"> <h1>Hello, I am a static template</h1> </div> </template> On the other side, dynamic templates are used to show dynamic content in a given layout defined by the template (ex: the BlogPost default template) Here is the minimal code for a dynamic template: <template> <div class="template"> <h1>{{content.title}}</h1> </div> </template> <script> import LoadContent from './LoadContent' export default { mixins: [LoadContent] } </script> The vue mixin LoadContent will expose your content as a data object called content. There, you can access all the fields of the content you assigned to that route. Field templatesField templates In order to give users more control over their content we have introduced Field templates. Found in the src/app/fieldTemplates folder, a field template will allow users to customize each and every field in their content as much as they wish without creating a single, large template file that is hard to manage and navigate. Just like content templates, field templates can be static and dynamic but for the most part they are envisoned for implementing dynamic content. Every field template has at least one prop: - field_class - prop that contains a class/classes tah the user wants to use on their field in some manor that requires the class to be passed dynamically - content prop - prop whose name will vary from field to field. This prop contains all data that the component will use and is usualy exposed to the template through a computed property. Here is an example of a template using their content prop and field_class prop: <template> <p :{{content}}</p> </template> <script> export default { props: { body: '', field_class:'' }, computed: { content: function() { return this.body } } } </script> <style lang="scss"> // here you can add custom styles for your field </style> Content types/Contents/FieldsContent types/Contents/Fields First, we have to understand the basic concepts and the DB structure. - Content type - type from which we create specific contents - every content type has it's own name, icon, path, fieldsand data(Contents) - Content - actual contents created as datain Content types - Fields - used as properties for Contents and can be created as one of the available input types ( textarea, textbox, integer, boolean, url, richtextbox, input) Why do we need this?Why do we need this? This way, everything we create is custom made. We don't have any restrictions in sense of how our content should be named, what properties(inputs) should it have, on what path should our contents be, etc. _ For users who have used previous version of Tamiat CMS __ For users who have used previous version of Tamiat CMS _ In order for this new feature to work, you have to do the following: - Delete everything from DB except media, navand settings - Go to the Databasesection in Tamiat admin area and add Demo Contentand Demo Fields - After this, you have successfully added the demo data and initialized the DB. Now you can continue on working with contents and fields. How to create Content types and Fields?How to create Content types and Fields? In order to create content types and fields we have to go to the Content section in Tamiat admin area. Content typesContent types CreateCreate To be able to create new content type we have to define the name and select one or more fields from available fields list. On the right side we have a list of available fields. Those are the fields that are currently available in the DB. By checking a field from that list, we decide to include it in the creation of content type. If we want some fields to be shown later in the UI, we have to check a field from Fields list (only textbox type fields are available). Also, we can reorder fields so that they are stored in the DB as we want. Edit/ Lets look at the right section. By selecting a content type from dropdown menu, section on the left is populated with data of selected content type. From that point, we can choose to edit or to delete it. FieldsFields CreateCreate By clicking on Add new field button, this block is displayed. Field name and field type are mandatory, but multi value isn't. Edit/ Next to every fields name in the available fields list, we have two icons - delete and edit. The same block is displayed just now it's populated with selected fields data. We created a new content type, what now?We created a new content type, what now? After successfull creation, content types are displayed in the dropdown menu Content in Tamiat admin area. By clicking on a specific content type, this page is displayed: From this point, we can Create (Save/Publish), Edit, Delete, Bulk delete, Select, Filter and Sort contents. Those contents will be displayed later in the app. In the picture above we can see that we have newly created content type, ex. Posts, which has an actual data that is displayed in the table. Notice that only author and title fields are displayed - because those are the fields we previously marked to be shown in content list when we were creating content type. It is omportant to note that in order to be able to mark a field to be visible in the content list we must make sure that when creating or editing that field we set the Listable checkbox to true like shown below. It is important to note that in order to be able to mark a field to be visible in the content list we must make sure that when creating or editing that field we set the Listable checkbox to true like shown below. This setting lets Tamiat know that this field can be made listable in any content type that uses it. This will make a small checkbox appear next to a field that was selected as part of a content type you are creating/editing. If the checkbox is present it means that we have successfully defined that field as listable. If the checkbox is checked that means that the field will be visible in contents list for this specific content type. Notice how the img field has a checkbox but it is not checked, that means that the img field has been globally defined as listable when it was created or edited, but for this specific content type this field will not be listed, since in this instance we do not want that. However, if you decide you want the img field to be listable in another content type the checkbox will always be present, since whether a field is listable or not for a content type is stored within that content types section in the database and will never interfere with the global definition of a field or how it is set in another content type.
https://reposhub.com/vuejs/projects-using-vuejs/tamiat-tamiat.html
CC-MAIN-2021-21
refinedweb
2,225
58.92
current position:Home>[Python data acquisition] page image crawling and saving [Python data acquisition] page image crawling and saving 2022-01-30 19:32:32 【liedmirror】 Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities Preface In this article , Will pass through requests and urllib.request library , Get some url All the pictures in , It can be applied to all pages through static rendering . Ideas obtain html Construct a get_html function , Input url And the request method , return html Text : def get_html(url: str, request_type: str) -> str: """ obtain html :param url: Access address :param request_type: Request mode : urllib.request or urllib.request Or corresponding cache :return: html """ if request_type == "urllib.request": # urllib.request return urllib.request.urlopen(url).read().decode("utf-8") elif request_type == "requests": # requests response = requests.get(url) return response.text else: # Read cache file with open(f'./.cache/{request_type}.html', 'r', encoding='utf-8') as f: return f.read() Copy code Resolution images Using regular matching , Will all Inside the label src extracted : imgList = re.findall(r'<img.*?src="(.*?)"', html, re.S) Copy code Be careful : Here you need to set and use re.S Method pattern , Otherwise, for cross line images , Will not be able to identify extraction . pictures saving The content of the file is the requested picture url Return content , Use with open Create file management objects , And set the mode to wb( Binary write mode ): resp = requests.get(img_url) with open(f'./download/{img.split("/")[-1]}', 'wb') as f: f.write(resp.content) Copy code Use string segmentation from url Extract the name of the file ( Make sure the suffix is correct ): img.split("/")[-1] # Or to "." Segmentation , Extract only the suffix , Label and name the file by yourself . Copy code Finally using f.write(resp.content) Saving can be realized . def get_imgs(html:str, download=True) -> None: """ Get all picture addresses , Optional download :param html: Input html :param download: Download or not :return: None """ imgList = re.findall(r'<img.*?src="(.*?)"', html, re.S) print(imgList) print(f' share {len(imgList)} A picture ') if download: for i, img in enumerate(imgList): img_url = "" + img print(f" Saving the {i + 1} A picture route :{img_url}") resp = requests.get(img_url) with open(f'./download/{img.split("/")[-1]}', 'wb') as f: f.write(resp.content) Copy code Running results Saved pictures : author[liedmirror]
https://en.pythonmana.com/2022/01/202201301932302775.html
CC-MAIN-2022-27
refinedweb
395
50.53
="main"></div> // App const App = React.createClass({ render() { return ( <div> <Header /> <IconUmbrella /> </div> ) } }); // Header const Header = React.createClass({ render() { return ( <h3>Hello, world!</h3> ) } }); // Icon const IconUmbrella = React.createClass({ render() { return ( <svg className="umbrella" xmlns="" width="32" height="32" viewBox="0 0 32 32" aria- <title id="title">Umbrella</title> <path d="M27 14h5c0-1.105-1.119-2-2.5-2s-2.5 0.895-2.5 2v0zM27 14c0-1.105-1.119-2-2.5-2s-2.5 0.895-2.5 2c0-1.105-1.119-2-2.5-2s-2.5 0.895-2.5 2v0 14c0 1.112-0.895 2-2 2-1.112 0-2-0.896-2-2.001v-1.494c0-0.291 0.224-0.505 0.5-0.505 0.268 0 0.5 0.226 0.5 0.505v1.505c0 0.547 0.444 0.991 1 0.991 0.552 0 1-0.451 1-0.991v-14.009c0-1.105-1.119-2-2.5-2s-2.5 0.895-2.5 2c0-1.105-1.119-2-2.5-2s-2.5 0.895-2.5 2c0-1.105-1.119-2-2.5-2s-2.5 0.895-2.5 2c0-5.415 6.671-9.825 15-9.995v-1.506c0-0.283 0.224-0.499 0.5-0.499 0.268 0 0.5 0.224 0.5 0.499v1.506c8.329 0.17 15 4.58 15 9.995h-5z"/> </svg> ) } }); ReactDOM.render(<App/>, document.querySelector("#main")); Also see: Tab Triggers
https://codepen.io/sdras/pen/a9879fa911eef0af31089f6ccf7c367c/
CC-MAIN-2020-34
refinedweb
260
65.28
Windows NT in a Nutshell A Desktop Quick Reference for System Administration Sample Chapter 5: RAS and DUNThe documented along with examples of their usage. RAS ProtocolsA). PPTPNT 4.0 also supports the Point-to-Point Tunneling Protocol (PPTP). This allows the creation of Virtual Private Networks (VPN) using the Internet. PPTP creates a virtual "tunnel" between your computer and a remote NT server (or communications server that understands PPTP). This tunnel is encrypted, enabling you to send sensitive data over the Internet. The main reasons to use PPTP are security and lowering remote access costs. PPTP may save you money if you are able to use the Internet to connect remote sites instead of private leased lines. RAS ComponentsYou may be confused by how the different components of RAS are named and administered. Previous to NT 4.0, RAS referred to both the client and server side of a connection. Typically, the client side is doing the dialing, and the server side is receiving calls. In NT 4.0, the client side of RAS is called Dial-Up Networking (DUN), which is buried in the Programs-Accessories menu. DUN looks similar to the Windows 95 implementation but is different in operation and configuration. The server side, the Remote Access Service, is administered by the Remote Access Admin tool and the Services-Remote Access Service-Properties menu of the Network control panel. This book uses the term RAS to describe the entire Remote Access functionality, and DUN for the client side of RAS. Installing RASTo install RAS under NT Server or Workstation, use the Services-Add button of the Network control panel and select Remote Access Service. Dial-Up Networking will prompt you to install it the first time you try to run it unless it is already installed. To install the Point-to-Point Tunneling Protocol (PPTP), use the Protocols-Add button of the Network control panel. Installing PPTP also installs RAS if it is not already installed. Overview of a RAS sessionTo illustrate how the DUN side of RAS works, let us assume you are a typical NT user who wants to log in to the Internet using your local ISP. To initiate the connection: - Start Dial-Up Networking. - Select an entry name from the scroll list. - Click on the Dial button. - Enter username and password into the dialog box. - After this point, the local computer should log onto the remote RAS server and start the network connection (see Figure 5-1). There are several processes needed for a successful start of the DUN session. The first is authentication, the process of proving to the remote site that you are a legitimate user. The second is configuring the network, which usually involves getting network information from the remote site to configure the local computer. PPP AuthenticationIf you are using PPP, you should be able to use PPP authentication protocols to authenticate your RAS connection to the remote device. An authentication protocol is a set of standards for exchanging logon name and password information between the two network devices. The most common PPP authentication protocols are the Password Authentication Protocol (PAP) and the Challenge Handshake Authentication Protocol (CHAP). PAP is a simple protocol that sends your username and password to the remote system. The exchange of passwords between client and server are in clear text and could be snooped by a third party listening in on the connection. CHAP is more secure in that the password information is encrypted before it is sent over the PPP connection. Shiva PAP (SPAP), a Shiva-specific version of PAP, improves on PAP by encrypting the password before sending it to the remote system. Microsoft has its own version of CHAP that encrypts the password using a different scheme. This is called MS-CHAP and is generally available only for Microsoft products. If you do not control both ends of your RAS connection, ask the person in charge of the remote end what PPP authentication protocols are supported. The PPP client and PPP server negotiate to find a common authentication protocol. You can limit the choices in order to enhance security. The choice of PPP authentication protocol is made in the DUN Security tab, as shown in Table 5-1. Authentication Using ScriptingIf you are using SLIP or are logging in to a remote device which does not support a PPP authentication protocol, you are going to need a script to provide the authentication information. A script fools a remote computer or device into thinking that you are typing in a username, password, or other logon information, while it is actually done by your computer. Scripting automates the logon procedure and makes it possible for your computer to reconnect a failed connection without user intervention; or, it can even establish connections via the at command scheduler service. Normally, getting DUN to log in to a Microsoft RAS server is simple and pretty much works out of the box. Configuration is done by clicking on a few checkboxes and typing in names and phone numbers for the remote sites. The situation becomes more complicated if you are trying to use a non-Microsoft product on one side of the connection. For example, most Internet Service Providers (ISPs) are not using Microsoft NT RAS servers to provide dial-up connectivity for their customers. They typically use specialized "comm-servers" that run vendor-specific and proprietary operating systems. Some of these comm-servers are starting to support RAS, but there are still a huge number that offer generic PPP dial-up support. Some of these authenticate PPP users by using a UNIX-like login and password prompts. For example:Login: <username> Password: <password> #$$(&*%@)wS@# <ppp session starts>These prompts were originally intended to be used by humans who were logging in to character-based terminal sessions. Then programs such as UNIX UUCP (UNIX-to-UNIX Copy) started to use the same authentication mechanism to login, but did so by pretending to be a human user and entering the username and password via a program. As the login/password prompts varied among different systems and vendors, a scripting "language" was used to describe the different login/password procedures for each remote computer. In UUCP terminology, the scripting functionality is called a chat script. Chat scripts are similar in function to macros or scripts that terminal emulators or Comm programs provide to automate the login to a BBS or other remote computer system. Microsoft supports two different scripting languages in NT 4.0. The first consists of the SWITCH.INF-style scripts that appeared in NT 3.5x. The second is the Windows 95-style scripts contained in files with the .SCP extension. If you have existing scripts from NT 3.51 or Windows 95, you should not need to modify them for NT 4.0. If you are writing a script from scratch on 4.0, it is probably better to use the Windows 95-style .SCP scripting language, as it has many more features. For example, the SWITCH.INF language has no time-out functionality, so it will wait forever if something goes wrong. The .SCP scripting language also has more traditional program-flow structures that should be familiar to even the casual programmer. If you are logging in to an ISP or company remote-access facility, chances are that someone else has already written a script in one of the languages that you can use. If you are setting up Dial-Up Networking to log in to a non-Microsoft PPP server for the first time, it is worth seeing if the Microsoft-supplied Generic Login script will work without any further customization. It should handle the most common login name and password prompts. Note that it is possible to hardcode your username and password into the scripts themselves. This would eliminate having to type the information each time you use DUN, but your account would be wide open to anyone who gains access to the script files. Configuring the NetworkYour computer has to obtain several pieces of information before it can start communicating via TCP/IP with other computers. This information includes an IP address for the client side of the connection, a list of DNS servers, and possibly a list of WINS servers. PPP has the ability to obtain an IP address from a PPP server and give it to the dial-in client, but getting DNS and WINS server information to the client requires functionality external to PPP. IP addresses are usually handed out dynamically by the device you are calling. This means that your IP address (and possibly the TCP/IP hostname) could be different each time you dial in. The IP addresses can come either from a pool of addresses handed out by the remote PPP device or via DHCP. In order to look up hostnames on the Internet (such as when using a web browser) you also need the address of one or more DNS servers. Some communications servers (including NT RAS) supply this automatically to the dial-in clients via DHCP, and others require you to type the information into DUN using the Server-TCP/IP tab. If you want to browse the remote network you are dialing into using Microsoft networking, you need a WINS server IP address in the Server-TCP/IP tab. You can either type one in or have it supplied by DHCP. Debugging PPPWhen a PPP connection is first started, the two ends of the connection negotiate lots of options, trying to find a common set that they both support. If you are having trouble connecting with PPP, there are several tools available for debugging. The first is a logfile generated by DUN that records all PPP packets going to and from the local computer and the remote device. The second is the Network Monitor application, which can "listen" on the PPP interface and record all traffic going over the PPP link. In order to understand the PPP information, you have to have a detailed explanation of PPP readily available. Good sources for descriptions of the protocol are the Internet Request For Comments (RFC) documents available on the Internet. The following Internet RFCs cover PPP: RFC1661 The Point to Point Protocol (PPP) RFC1700 Assigned Numbers (PPP Protocol Field Assignments section)You should easily be able to find RFCs on many web and ftp sites. One of the official sites is. The Southwest Free Software Organization site at has an especially nice RFC display. You really do not have to understand the protocol completely in order to spot problems. If you cannot find the error, at least you will be able to produce a logfile that you can show to someone who does understand PPP. PPP LoggingLocate the key SYSTEM\CurrentControlSet\Services\RasMan\PPP and change Logging from 0 to 1. This will create a file called PPP.LOG in the <winnt root>\SYSTEM32\RAS directory. To debug a PPP session, first enable logging and then initiate the PPP connection. When the connection fails or exits, examine PPP.LOG to see what happened. more < PPP.LOG Line up event occurred on port 0 FsmInit called for protocol = c021, port = 0 FsmReset called for protocol = c021, port = 0 FsmThisLayerStarted called for protocol = c021, port = 0 <PPP packet sent at 02/06/1997 11:14:12:436 <Protocol = LCP, Type = Configure-Req, Length = 0x26, Id = 0x0, Port = 0 <C0 21 01 00 00 24 02 06 00 00 00 00 05 06 00 00 |.!...$..........| <5B D5 07 02 08 02 0D 03 06 11 04 06 4E 13 09 03 |[...........N...| <00 AA 00 A5 84 EF |...... | >PPP packet received at 02/06/1997 11:14:12:597 >Protocol = LCP, Type = Configure-Req, Length = 0x24, Id = 0x1, Port = 0 >C0 21 01 01 00 22 01 04 05 F2 02 06 00 0A 00 00 |.!..."..........| >03 0C C0 27 01 00 00 03 00 00 00 0E 05 06 64 03 |...'..........d.| >1E 2A 08 02 |.*.. | <PPP packet sent at 02/06/1997 11:14:12:597 <Protocol = LCP, Type = Configure-Nak, Length = 0xe, Id = 0x1, Port = 0 <C0 21 03 01 00 0C 03 08 C0 27 01 00 00 01 |.!.......'.... | >PPP packet received at 02/06/1997 11:14:12:597 >Protocol = LCP, Type = Configure-Reject, Length = 0x16, Id = 0x0, Port = 0 >C0 21 04 00 00 14 0D 03 06 11 04 06 4E 13 09 03 |.!..........N...| >00 AA 00 A5 84 EF |...... | ...What you are seeing is a trace of every PPP packet going to and from your computer to the remote PPP device. The Protocol and Type fields tell you what is going on. The data in the packets is presented in both hexadecimal and ASCII. One of the most common failures you may have when setting up a new PPP connection is with the negotiation of an authentication Protocol. This is controlled on the client side of RAS by the Security tab of Dial-Up Networking. Both ends of the PPP connection try to find a common mechanism for authentication. The Dial-Up Networking Security tab places various restrictions on the allowable authentication protocols. The PPP session should try to negotiate the most secure protocol first, and if this fails, try the second best, and so on. In reality, not every device that speaks PPP handles the authentication protocol negotiation gracefully, leading to interoperability problems between different vendor devices. Use the most secure protocol, which will normally be Accept only encrypted authentication. If both ends are Microsoft products, you could use MS-CHAP. For authentication failures, the most interesting part of the PPP.LOG file is going to be the section starting with Authentication phase. For example:Authenticating phase started <PPP packet sent at 02/06/1997 15:05:04:169 <Protocol = SHIVA PAP, Type = Protocol specific, Length = 0x28, Id = 0x0, Port = 0 <C0 27 06 00 00 26 01 05 65 61 70 02 15 31 5C 5C |.'...&..eap..1\\| <0B 11 3D 73 9F C7 2A 49 EB 67 64 7C A4 89 D5 5D |..=s..*I.gd|...]| <03 04 00 01 04 04 00 01 |........ | >PPP packet received at 02/06/1997 15:05:04:389 >Protocol = SHIVA PAP, Type = Protocol specific, Length = 0x8, Id = 0x0, Port = 0 >C0 27 02 00 00 06 00 00 |.'...... | FsmThisLayerUp called for protocol = c027, port = 0This DUN client is configured with the Accept only encryption authentication option, which accepts either SPAP, CHAP, or MS-CHAP. From this sequence, you can see that the local computer tried using the SPAP (Shiva PAP) authentication protocol, and the remote PPP device accepted it. You can see that protocol c027 succeeded from the lines' referrals to Shiva PAP and FsmThisLayerUp. In RFC 1700, c027 is listed as the Shiva Password Authentication Protocol or SPAP.c021 Link Control Protocol c023 Password Authentication Protocol c025 Link Quality Report c027 Shiva Password Authentication Protocol c029 CallBack Control Protocol (CBCP) c081 Container Control Protocol c223 Challenge Handshake Authentication Protocol c225 RSA Authentication Protocol c227 Extensible Authentication Protocol c26f Stampede Bridging Authorization Protocol c281 Proprietary Authentication Protocol c283 Proprietary Authentication Protocol c481 Proprietary Node ID Authentication Protocol The next example shows a failure:Authenticating phase started >PPP packet received at 02/06/1997 14:28:11:617 >Protocol = CHAP, Type = Protocol specific, Length = 0x1a, Id = 0x1, Port = 0 >C2 23 01 01 00 18 08 32 F9 F9 ED 00 1E 4D 60 6F |.#.....2.....M`o| >70 60 2F 74 66 73 74 2D 6E 62 |ora-login:. | <PPP packet sent at 02/06/1997 14:28:11:617 <Protocol = CHAP, Type = Protocol specific, Length = 0x21, Id = 0x1, Port = 0 <C2 23 02 01 00 1F 10 94 40 30 22 05 A5 DF 43 1E |.#......@0"...C.| <E0 85 54 8B 0F CA 64 48 4F 4D 45 5C 70 63 65 61 |..T...dHOMEcea| <70 |p | >PPP packet received at 02/06/1997 14:28:11:757 >Protocol = CHAP, Type = Protocol specific, Length = 0x1b, Id = 0x1, Port = 0 >C2 23 04 01 00 19 49 6E 76 61 6C 69 64 20 43 48 |.#....Invalid CH| >41 50 20 72 65 73 70 6F 6E 73 65 |AP response | Auth Protocol c223 terminated with error 7 FsmThisLayerDown called for protocol = c021, port = 0The "Protocol = CHAP" and the message "Invalid CHAP response" are clues to what is wrong. From looking at RFC1700, you can tell that "Auth Protocol c223" is CHAP. The next step is to examine the remote device you are calling and find out why it does not speak CHAP. Network Monitor and PPPThe Network Monitor is normally used to capture network traffic from a LAN interface, such as an Ethernet adapter. It is also possible to use it as a "WAN Analyzer" by listening on serial interface used by RAS and capturing packets from the PPP session. It is most useful during the initial negotiation between DUN and the remote device, as this is where errors are likely to occur. Follow these steps to locate errors: - Start Network Monitor. - Select interface to capture traffic from. Under the Capture-Networks menu, click on the Ethernet interface with all zeros for the Current Address (see Figure 1-2). - Start the capture. Select Capture-Start. - Start DUN. - Dial the entry that is to be debugged. - When the connection fails, go back to Network Monitor and select Capture-Stop and View. - Step through each packet and look for errors, especially with "Reject" in the Description field (see Figure 1-3). Keep in mind that the PPP device that you are calling in to is likely to have an ability to debug the PPP negotiation process, enabling the PPP connection to be debugged from either side of the conversation. Also realize that you are unlikely to be the first person to discover a new PPP problem between devices and you should search the Internet, web sites, and Usenet newsgroups before paying for help. Writing ScriptsWriting a script is pretty easy most of the time. These steps outline the process:.) - Connect to the remote system using Terminal Window or Hyperterminal. - Write down what the remote system sends and what you have to type. - Create the script in SWITCH.INF or .SCP language. - Associate the script with the dial-up entry by using the Script tab and selecting the script name from the Run this script scroll list. - Test the script. - If the script fails, turn on DEVICE.LOG debugging and correct errors. From information collected during the terminal session, a script can be created. The following is a sample SWITCH.INF script:From information collected during the terminal session, a script can be created. The following is a sample SWITCH.INF script: - A new phonebook entry is created by starting up Dial-Up Networking, selecting New, and filling out the form. - Under the Script tab, select Pop up a terminal window. - Dial entry. - When the connection is made, the terminal window appears, but no prompt is seen from the remote system. - After hitting ENTER twice, the login prompt appears:@ Userid: - Type your username and hit ENTER. If the script fails, turn on DEVICE.LOG debugging and correct errors (see "Debugging Scripts" for the procedure). - The next prompt appears:Password? - Type your password and hit ENTER. - Another prompt appears:Shiva LanRover/8E, Version 4.0.2 96/05/07 lanrover> - Type in ppp and hit ENTER. - The PPP session then starts:Exiting shell, starting PPP @3~$#$&~$#$#$%#^$# - At this point, you can continue to logon by clicking the Done button.; interactive lanrover entry [lanrover] ; needs two returns before prompt appears COMMAND=<cr> COMMAND=<cr> OK=<match>"Userid:" LOOP=<ignore> COMMAND=<username><cr> OK=<match>"assword?" LOOP=<ignore> COMMAND=<password><cr> ; have to explicitly start ppp OK=<match>"anrover>" LOOP=<ignore> COMMAND="ppp"<cr> ; ignore anything from here on OK=<ignore>And here is a sample .SCP script:proc main transmit "^M" transmit "^M" waitfor "Userid:" transmit $USERID transmit "^M" waitfor "assword?" transmit $PASSWORD transmit "^M" waitfor "anrover>" transmit "ppp^M" endprocEither of these scripts can be associated with the phonebook entry by using the Script tab and selecting the script name from the Run this script scroll list. Debugging ScriptsUnlike (your NT machine running dial-up networking) and the server (the comm-server you are logging into) in a log file, called <winnt root>\SYSTEM32\RAS\DEVICE.LOG. You have to specifically enable logging in the Registry in order for this to work. In KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\RasMan\Parameters, from Device" is what the remote computer sends back. The "Echo from Device" is simply the text you are sending being echoed back by the remote device. The actual exchange would look like this:Your Computer Remote Computer -------------------------------------------------------------- <nothing> netblazer login: eap Password: foo Login incorrect). SWITCH.INFThe SWITCH.INF file contains multiple scripts in the scripting language first introduced in NT 3.x. Section headerSection headers are used to delineate individual scripts within the SWITCH.INF. This is different from the Windows 95 scripting language, where each script is stored in a separate .SCP file. The header is simply a name enclosed in brackets:[myscript]Anything following the header is assumed to be script commands until the next header or the end of file. The name within the brackets appears in the scroll list Run this script in the Script tab of Dial-Up Networking. COMMANDCOMMAND is used to send text to the remote computer or device. It does not add a carriage-return character, so one must be added with the <cr> macro.COMMAND=string<cr>As each COMMAND statement takes about two seconds to execute, an empty statement such as:COMMAND=serves as a way to insert time delays into the script. The sequence:COMMAND=P COMMAND=P COMMAND=Pis equivalent to:COMMAND=PPPbut each character is separated by a two-second delay in the first sequence. This method could be used to communicate with extremely slow devices. OKThe OK command's main purpose is to look for a specific response from the remote computer or device. Most of the time this will be a prompt for the username or password.OK=<match>"ogin:"This OK command will try to match the string "ogin:" in any response coming from the remote device. The <match> macro is case-sensitive, so using the string "ogin:" will match either "Login:" or "login:". LOOPThe LOOP command is usually combined with the OK command and has the effect of a conditional loop. The LOOP ignores any text coming from the remote device until something matching the OK command is found.OK=<match>"ogin:" LOOP=<ignore>This OK and LOOP combination is useful for skipping through greeting messages or other text irrelevant to the login process. For example, if your Internet provider has a message of the day that is printed before the login prompt:Welcome to Joe Bob's ISP System down at 5pm tonight for repairs ********************************* login:The OK/LOOP combination would ignore all the text until it found the "login:" prompt. Response CommandsThe response commands deal with processing output from the remote device. - CONNECT=response <macro> The CONNECT command looks for a connect message from the communications device, indicating a successful connection. This is primarily used when talking to PAD devices in the PAD.INF file. - ERROR=response <macro> If the script is looking for a specific error message, the ERROR keyword will tell DUN to look for this error message and notify the user that an error has occurred. - ERROR_DIAGNOSTICS=response <diagnostics> If the script encounters an error message, RAS will try to interpret what it means and inform the user. - NoResponse Do not expect any response from the remote device. MacrosMacros are used to match or send special characters when sending text to or receiving text from the remote device. - <cr> Send carriage return character. - <lf> Send line feed character. - <match>string Look for string in output from remote device and exit loop. The <match> macro will find the string anywhere in the output (it does not have to be by itself) and is case-sensitive. For these reasons, <match>Login: would fail to match "login:", but using "ogin:" matches either case. - <?> Wildcard character for <match> macro that matches any single character. For example, <match>"<?>ogin:" could be used to match "Login:" or "login:". - <hXX> Refer to character via position in ASCII character set by hex number (XX). This is useful for describing non-printing characters, such as NUL, which could be matched with <h00>. The ASCII code for a carriage return is CR, which is 13 in base 10 and 0D in base 16. This could be represented by <h0d> in a script. - <ignore> Ignore the responses from the remote system. - <diagnostics> Interpret response from the remote system as an error diagnostic message and display it to user. - <username> Supply username from Connect To dialog box. Not supported in SLIP sessions. Supply password from Connect To dialog box. Not supported in SLIP sessions. CommentsComments can be used to annotate scripts to make them easier to maintain. A comment is started by a semicolon as the first character on the line:; ; LanRover requires 2 carriage-returns before prompting for username ; (expecting PPP/ARA?) ; Further InfoThere are several files in the <winnt root>\SYSTEM32\RAS directory: - RASPHONE.HLP Windows Help file for RAS - SWITCH.INF Sample scripts for modems and ISDN TAs - PAD.INF Sample scripts for PAD/X.25 devices Windows 95 SCP ScriptsThe Windows 95 Dial-Up Networking scripting language is supported under NT 4.0. In fact, you should be able to reuse any scripts you wrote for Windows 95 on NT 4.0 without modification. The Windows 95 scripting language uses separate files ending with the extension .SCP for each script. This different than the SWITCH.INF scripting language, which stores multiple scripts within the same file. The Windows 95 scripting language is "richer" in that it is more like a traditional programming language, with program-flow structures, variables, types, and so on. Another advantage over SWITCH.INF-scripts is a time-out capability that permits the script writer to handle unresponsive connections and other communications failure conditions gracefully. Script StructureAll scripts must have a main procedure, delimited by proc and endproc, that can contain variable declaration and commands.proc main variable declaration commands endproc VariablesVariables are either user- or system-defined names for holding values during the execution of the script. Variable names must begin with a letter or underscore character, but can contain mixed-case letters, numbers, and underscores. Be sure to avoid using any of the scripting language commands as variable names. These are called "reserved words," in that they are unavailable for use within the script. Variable Data TypesThe Windows 95 scripting language variables support the concept of type, which defines the kind of data contained in the variable and operations that can be performed on it. Variable declaration and assignmentVariables are declared with a type the first time they appear in the script:integer timeoutVariables are assigned values using an expression:timeout = 10Variables can also be declared and assigned in the same statement:integer timeout = 10 Predefined variablesThe system provides several variables as a way for scripts to check for a common condition at run-time. They are read-only, meaning that you can query their value, but not alter it. String literalsString literals are used to represent characters or strings that would be difficult to use because they contain nonprinting characters or characters that may be interpreted by the scripting language (instead of taken literally). ExpressionsExpressions are operations that yield a result which can be assigned to a variable or evaluated. CommentsThe comment character for scripts is the semi-colon. Anything following the comment character is ignored by the script processor.; ; Here is a comment KeywordsKeywords define the structure of the script and declare variable type. CommandsCommands control the flow of the script or perform some function on a variable. Functions Reserved WordsThe following reserved words are part of the script language and cannot be used as variable names:and boolean databits delay do endif endproc endwhile even FALSE getip goto halt if integer ipaddr keyboard mark matchcase none odd off on or parity port proc raw string then transmit TRUE until waitfor while Further InfoThere are several files in the <winnt root>\SYSTEM32\RAS directory: - RASPHONE.HLP - Windows Help file for RAS. - SCRIPT.DOC - Script documentation in Word format. - CIS.SCP, PPPMENU.SCP, SLIP.SCP, and SLIPMENU.SCP - Sample SCP scripts. PPTPThe Point-to-Point Tunneling Protocol can be used to create encrypted tunnels between computers separated by networks, enabling sites and users to connect in a low-cost and secure manner. TunnelingThe tunnel can create a path for several protocols to run over a protocol of a different type. This is called encapsulation, as the network traffic entering one end of the tunnel is encapsulated within the protocol native to the intermediate network and unencapsulated on the other end of the tunnel. The most common example of tunneling would be carrying IPX, NetBEUI, and TCP/IP over a TCP/IP-only network (such as the Internet). See figure 5-4 for a diagram of this example. EncryptionIf you are using your own dedicated ("leased") lines between sites or dialing into your company RAS server, you are not likely to be worried about a third party intercepting traffic. The act of sending traffic over the Internet brings up potential security problems. If you were conducting business or transferring sensitive data between sites using the Internet, someone could intercept the traffic and analyze it. PPTP encrypts traffic, preventing the packets from being read if they are snooped by a third party. CostMany companies have created large and complex in-house dial-up facilities for remote workers to dial into. Some companies use dedicated lines to link their sites, resulting in large, recurring facilities costs. Tunneling over the Internet may allow remote workers or sites to use the Internet in place of expensive company-owned facilities. Dial-Up Versus DedicatedNearly all descriptions of PPTP describe its use only in regard to dial-up situations. It is possible to use PPTP over a previously existing network connection, such as a dedicated connection to the Internet. If you can reach a PPTP server, you simply "dial" into it using its IP address. The PPTP session runs on top of the existing connection. Installing PPTPPPTP is installed as a protocol using the Protocol-Add button of the Network control panel. The only installation option is the number of Virtual Private Network (VPN) ports. Each end of each PPTP session requires a VPN port. VPN ports do not have to have a corresponding physical RAS port (COM port). They exist in software only. If you have only one PPTP session on your computer, you need only one VPN port. A RAS server requires as many VPN ports as might possibly be in use simultaneously, both incoming and outgoing. Once you have installed a VPN port, RAS and DUN treat it as if it were a physical port. The only difference is that an IP address or hostname is used instead of a phone number when calling the remote site. Using PPTPIn most cases, you will being using PPTP over a dial-up RAS connection to an ISP. You should first establish the RAS session to the ISP using DUN to dial the modem or ISDN entry. Once you are connected to the ISP, you can use DUN to dial the PPTP entry, which runs on top of the conventional RAS session. If you have a dedicated connection to the Internet or use a device that behaves as if it were permanently connected, you can skip the modem dialing entirely, and initiate the PPTP session on top of the existing Internet connection. Using PPTP over a dedicated connection means using RAS, even though you are not using RAS to create the initial connection. It may look a little silly to have the RAS modem monitor lights flashing and a baud rate of 10,000,000 when using PPTP over an Ethernet LAN. Other Tunnel ProductsThe market has yet not selected a winner in the tunnel area. Microsoft is pushing PPTP and several vendors are adding support for it, including US Robotics, Ascend, and 3Com. The main competition for PPTP is L2F (Layer 2 Forwarding), promoted by Cisco Systems, Shiva, and Nortel. Digital Equipment Corporation also has a tunneling product for Windows NT and Windows 95, called AltaVista Tunnel. Files Used by RASThere are several files that RAS uses to accomplish the logon procedure. They are stored in the directory <winnt root>\SYSTEM32\RAS.. - When DUN is started, it reads the system phonebook file (RASPHONE.PBK) or a user-specified phonebook for a list of possible entries to dial. The phonebook file supplies all the settings for the particular entry to DUN, including the device being used to dial, the phone number, the networking and authentication protocols, and so on. - If the device being used to connect is a modem, the modem type is looked up in the MODEM.INF file. Any commands or features unique to the particular modem are found here. - If the device is a PAD (used for packet networks such as x.25) the Network or PAD type is looked up in the PAD.INF file. - When dialing into a non-RAS computer or communications server using a script, the script associated with the phonebook entry is read from either the SWITCH.INF file or a standalone script in a amp;.SCP file. MODEM.INFThe role of the MODEM.INF file is to abstract interaction with modems so software can control modem characteristics in a generic manner, without the user supplying details about the specific brand, model, or type of modem. Previous to NT 4.0, all modems had to be described in the MODEM.INF file. In NT 4.0, the Universal Modem Driver (Unimodem) is used if the modem supports it. NT 4.0 still supports the MODEM.INF for backwards compatibility with non-Unimodem capable modems.Note: You can manually configure RAS to use MODEM.INF instead of Unimodem by editing the Registry. See KB article #Q150808. If your modem does not support Unimodem or is not listed in MODEM.INF, check if the modem manufacturer distributes a MODEM.INF entry on media that came with the modem or from a web site or BBS. You could also add your own entries to MODEM.INF, but you should think seriously about buying a new modem or one that complies with industry standards. File DescriptionMost modems made today still use the original AT command set that came from Hayes. The big problem is that each manufacturer has expanded on the original command set in their own proprietary way. There is also the concept of registers, which are general purpose NVRAM settings that can be used to store highly modem-specific settings. The meaning of the registers may change between firmware revisions of the same modem! For example, here is a fragment of the MODEM.INF that describes the US Robotics Sportster:[US Robotics Sportster 14400] CALLBACKTIME=10 DEFAULTOFF=compression MAXCARRIERBPS=19200 MAXCONNECTBPS=38400 <speaker_on>=M1 <speaker_off>=M0 <hwflowcontrol_on>=&H2&R2 <hwflowcontrol_off>=&H0&R1 <compression_on>=&K1 <compression_off>=&K0 <protocol_on>=&M4 <protocol_off>=&M0 <autodial_on>=ATDT <autodial_off>=ATD DETECT_STRING=ATI3<cr> DETECT_RESPONSE=Sportster 14,400 COMMAND_INIT=AT&F&C1&D2 V1 S0=0 S2=128 S7=55<cr> COMMAND_INIT=AT<hwflowcontrol><protocol><compression><speaker>&B1<cr> COMMAND_DIAL=<autodial><phonenumber><cr> CONNECT=\ <cr><lf>CONNECT <carrierbps><cr><lf> CONNECT_EC=\ <cr><lf>CONNECT <carrierbps>/ARQ<cr><lf>By assigning tags to various functions, such as turning compression on or off with compression_on and compression_off, software using the modem does not have to know that the USR Sportster uses &K1 for this function, while the Cardinal 14400 uses %C0. Software can also dynamically detect the type of installed modem using the DETECT_STRING. If it sends the ATI3 command to the modem and gets Sportster 14,400 back, it knows what type of modem is installed. This creates a plug and play capability for modems. The COMMAND_INIT string is similar to the init strings required by comm programs or fax software. The COMMAND_INIT typically resets the modem to the factory defaults (usually &F) and then changes anything that should be different from the factory default setting. By returning to the factory defaults each time you use it, the modem always starts with a clean configuration. The modem can tell the software what speed and type of connection it has made with the CONNECT message. This allows DUN or RAS to inform the user about the baud rate, bits per second (BPS), compression, error control, and so forth used during the connection to a remote computer or device. The CONNECT message is the same one you see when dialing a modem manually. RASPHONE.PBKThe RASPHONE.PBK (RAS phonebook) file contains entries that describe sites to which Dial-Up Networking can connect. Each phonebook entry contains phone numbers, security, and network settings. Users can create multiple phonebook files and they are available to Dial-Up Networking as long as they have the .PBK filename extension. The file RASPHONE.PBK is the default phonebook and will be used unless you specify an alternative. You can select alternative phonebooks in the GUI version of Dial-Up Networking by selecting More-User Preferences and the Phonebook tab. From the command line, you can dial using alternate phonebooks with the rasphone or rasdial commands. For example, assume the alternate phonebook file is called MYOWN.PBK and the entry name is ora. The rasphone command can specify an alternate phonebook using the -f flag and the phonebook entry using the -d flag:rasphone -f myown.pbk -d oraThe rasdial command takes the entry name, followed by the /phonebook: flag and the name of the alternate phonebook.rasdial ora /phonebook:myown.pbk File DescriptionYou should be able modify anything you need in the phonebook by using the DUN GUI. As the phonebook file is just a text file, it is possible to edit it by hand. It is safer to modify an existing entry than to try to create your own from scratch. If you do modify the phonebook file directly using an editor, you will have to quit and restart DUN for your changes to take effect. Entries in the phonebook file are started by an entry name in brackets. The entry name is followed by a list of parameters and values that have been set by the Dial-Up Networking GUI:[ora] Description=This is a comment AutoLogon=0 DialParamsUID=17651351 UsePwForNetwork=0 BaseProtocol=1 Authentication=-1 ExcludedProtocols=0 LcpExtensions=1 DataEncryption=0 SwCompression=1 UseCountryAndAreaCodes=0 AreaCode= CountryID=1 CountryCode=1 SkipNwcWarning=0 SkipDownLevelDialog=0 DialMode=1 DialPercent=90 DialSeconds=120 HangUpPercent=50 HangUpSeconds=120 IdleDisconnectSeconds=0 SecureLocalFiles=0 CustomDialDll= CustomDialFunc= AuthRestrictions=0 IpPrioritizeRemote=1 IpHeaderCompression=1 IpAddress=0.0.0.0 IpDnsAddress=0.0.0.0 IpDns2Address=0.0.0.0 IpWinsAddress=0.0.0.0 IpWins2Address=0.0.0.0 IpAssign=1 IpNameAssign=1 IpFrameSize=1006Most values are toggled on or off by setting them to 1 or 0. The Ip values are expected to be supplied dynamically at connection time. This is followed by MEDIA and DEVICE sections that describe the communications device to be used for the connection:MEDIA=serial Port=COM2 OtherPortOk=1 Device=Courier V.Everything ConnectBPS=115200 DEVICE=modem PhoneNumber=18005551212 PromoteAlternates=1 HwFlowControl=1 Protocol=1 Compression=1 Speaker=1If the entry uses a script, there is another DEVICE entry that has either the pathname of a Windows 95-style script:DEVICE=switch Type=D:\WINNT35\System32\ras\ora.scpor the name of an entry in the SWITCH.INF file:DEVICE=switch Type=netblazerAn entry for PPTP has the following MEDIA and DEVICE fields:MEDIA=rastapi Port=VPN1 OtherPortOk=1 Device=RASPPTPM DEVICE=rastapi PhoneNumber=208.26.94.11 PromoteAlternates=1 PAD.INFThe PAD.INF file contains descriptions of various PAD (Packet Assembler/Deassembler) devices and networks that RAS can connect to, which are typically X.25. The PAD.INF file use the same scripting language as SWITCH.INF. The following is a script to connect to the SprintNet packet network:[SprintNet, Standard] DEFAULTOFF= MAXCARRIERBPS=9600 MAXCONNECTBPS=9600 ; The next two lines ignore logon banners. COMMAND= OK=<ignore> ; The @ characters sets the SprintNet PAD for 8 databit communication. COMMAND=@ NoResponse ; The D character requests a 9600 speed. COMMAND=D<cr> ; We don't care about the response, so we ignore it (unless modem has hung up). ERROR_NO_CARRIER=<match>"NO CARRIER" OK=<ignore> ; A carriage return to initialize the PAD read/write buffers. COMMAND=<cr> ERROR_NO_CARRIER=<match>"NO CARRIER" OK=<ignore> ; Set the first half of X.3 settings on the PAD which make it work well with RAS. COMMAND=SET 1:0,2:0,3:0,4:1,5:0,6:1,7:0,8:0,9:0,10:0<cr> ERROR_NO_CARRIER=<match>"NO CARRIER" OK=<ignore> ; Set the other half of X.3 parameters. COMMAND=SET 12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0,22:0<cr> ERROR_NO_CARRIER=<match>"NO CARRIER" OK=<ignore> ; Finally try to call RAS X25 server. COMMAND=C <x25address>*<UserData><cr> CONNECT=<match>" CONNECT" ERROR_NO_CARRIER=<match>"NO CARRIER" ERROR_DIAGNOSTICS=<cr><lf><Diagnostics> ERROR_DIAGNOSTICS=<lf><cr><lf><Diagnostics>
http://oreilly.com/catalog/winnut/excerpt/ch05.htm
crawl-002
refinedweb
6,907
54.32
I am running Netscape 7.2 on a Windows 7 - 64 bit OS. When I open any link to a page with dynamic content, I receive an error window from the Shockwave Flash plugin, saying that the plugin performed an illegal operation, following which the system locks up. For example, the problem will occur if I go to the Adobe page that dynamically displays the installed Shockwave Flash plugin version. The Netscape program has been operating for a long time without this problem, so it must be something that I did recently. Any suggestion on how to solve this will be appreciated. Try asking on a Flash Player forum - this one is for Director's Shockwave Player, not Flash. OK, but the error window I got said Shockwave Flash, not just Shockwave and not just Flash. Macromedia screwed up the namespace. They already had a plugin called Shockwave (the Director plugin) when they named the Flash Player plugin "Shockwave Flash". You need to ask your question on another forum.
https://forums.adobe.com/thread/970634?tstart=0
CC-MAIN-2018-13
refinedweb
169
64.51
Namespace Not Generating In OTM After Transformation Last updated on SEPTEMBER 08, 2016 Applies to:Oracle Transportation Management - Version: 6.2.2 Information in this document applies to any platform. SymptomsACTUAL BEHAVIOR --------------- XSL file is used for transformation of Shipment XMl to be sent to an external system.This XSL file uses namespace which has to be there in output XML.The namespace is getting generated in the RAW XML which is obtained from transmission manager , but when OTM is sending out this XML using SOAP body as seen in the logs the elements are getting transmitted along with the namespace but not the attributes . The attributes are getting transmitted but not with the namespace. eg. <int:TransRequestIDDEV.OB-20110913-0031</int:TransRequestID> According to XSL made LineNbr should be prefixed with "int:" but it is not .It is getting generated in the RAW XML file but not in the XML obtained from the logs. EXPECTED BEHAVIOR ----------------------- The Outgoing xml should have the prefix "int:' STEPS ----------------------- The issue can be reproduced at will with the following steps: 1. Login to OTM and access Business Process Automation function and go to Integration action 2. Do a Send Outbound Integration. 3. View the xml and see that the prefix does not exist as expected. Cause My Oracle Support provides customers with access to over a Million Knowledge Articles and hundreds of Community platforms
https://support.oracle.com/knowledge/Oracle%20E-Business%20Suite/1384249_1.html
CC-MAIN-2018-09
refinedweb
231
54.32
Joel Christophel wrote:Look at your brackets for your getChannel() method. The first one is misplaced. Also, your switchTvOn() method has some problems. 1. It's return type is int, but you're returning a boolean. 2. Why isn't the return type void? You're not getting the TV's state, you're setting it. 3. Calling switchTvOn(false) should turn the TV off, and switchTvOn(true) should turn it on, but you're just setting things to true. 4. Also, you have two on variables, a local method variable and a state variable. When you do on = true; you're setting the local variable to true instead of the state variable. Here's how switchTvOn() should look: public void switchTvOn(boolean on) { this.on = on; } In the above, this.on refers to the on state variable at the top of your class, and on refers to the local on variable that was passed in to the method. All you're doing is setting the your TV on or off, depending on whatever boolean value the user passes in. One more thing: You should read up on access modifiers. Basically, classes, class variables, methods, and more can all be labeled with an access modifier (e.g. public, private, protected). When using ClassA from ClassB, ClassA's access modifiers will either block or allow the visibility of its various components. As a rule of thumb for now: 1. Classes should be public (e.g. public class Tester{}) 2. If methods and variables are only to be used within the class they're declared in, make them private. 3. If methods and variables are to be used from other classes, make them public. Cheers! then i used int newChannel again for method setChannel ... do you find this good programming practice or can it be improved ? when i call this methods changeVolume tv2.setChannel(10); it produces '0' output despite passing any value... if (on == true) true if (( volume == 1) && (volume == 100)) Abid Ramay wrote:ok .. i figured it out .. thanks to you guyz 1) i changed if statement -> if (on == true) ealier i was using assignment operator which changed the value to true instead of comparing it . Abid Ramay wrote:statement -> if (on == true) will result a boolean and cannot be compared to an 'int'
http://www.coderanch.com/t/617929/java/java/method-undefined-type
CC-MAIN-2014-42
refinedweb
384
76.22
September 2008 July 2009: This article discusses bundling large Python libraries using the zipimport module, using the Django 1.0 web application framework as an example. As of release 1.2.3 of the Python runtime environment, Django 1.0 is included in the runtime environment, and no longer needs to be bundled with your app. Using the version of Django included with the runtime environment provides faster start-up times for your application, and is the recommended way to use Django 1.0. The maximum file size is 10 megabytes, and the maximum file count (including application files and static files) is 10,000, with a limit of 1,000 files in a single directory. Introduction Using a Python web application framework with your App Engine application is usually as simple as including the files for the framework with your application's code. However, there is a limit to the number of files that can be uploaded for an application, and the standard distributions for some frameworks exceed this limit or leave little room for application code. You can work around the file limit using Python's "zipimport" feature, which is supported by App Engine as of the 1.1.3 release (September 2008). This article describes how to use Django 1.0 with Google App Engine using the "zipimport" feature. You can use similar techniques with other frameworks, libraries or large applications. Introducing zipimport When your application imports a module, Python looks for the module's code in one of several directories. You can access and change the list of directories Python checks from Python code using sys.path. In App Engine, your handler is called with a path that includes the App Engine API and your application root directory. If any of the items in sys.path refers to a ZIP-format archive, Python will treat the archive as a directory. The archive contains the .py source files for one or more modules. This feature is supported by a module in the standard library called zipimport, though this module is part of the default import process and you do not need to import this module directly to use it. For more information about zipimport, see the zipimport documentation. To use module archives with your App Engine application: - Create a ZIP-format archive of the modules you want to bundle. - Put the archive in your application directory. - If necessary, in your handler scripts, add the archive file to sys.path. For example, if you have a ZIP archive named django.zip with the following files in it: django/forms/__init__.py django/forms/fields.py django/forms/forms.py django/forms/formsets.py django/forms/models.py ... A handler script can import a module from the archive as follows: import sys sys.path.insert(0, 'django.zip') import django.forms.fields This example illustrates zipimport, but is not sufficient for loading Django 1.0 in App Engine. A more complete example follows. zipimport and App Engine App Engine uses a custom version of the zipimport feature instead of the standard implementation. It generally works the usual way: add the Zip archive to sys.path, then import as usual. Because it is a custom implementation, several features do not work with App Engine. For instance, App Engine can load .py files from the archive, but it can't load .pyc files like the standard version can. The SDK uses the standard version, so if you'd like to use features of zipimport beyond those discussed here, be sure to test them on App Engine. Archiving Django 1.0 When App Engine launched in Summer 2008, it included the Django application framework as part of the environment to make it easy to get started. At the time, the latest release of Django was 0.96, so this is the version that is part of version "1" of the Python runtime environment. Since then, the Django project released version 1.0. For compatibility reasons, App Engine can't update its version of Django without also releasing a new version of the Python runtime environment. To use 1.0 with App Engine with version "1" of the runtime environment, an application must include the 1.0 distribution in its application directory. The Django 1.0 distribution contains 1,582 files. An App Engine application is limited to 1,000 files, so the Django distribution can't be included directly. Of course, not every file in the distribution needs to be included with the application. You can prune the distribution to remove documentation files, unused locales, database interfaces and other components that don't work with App Engine (such as the Admin application) to get the file count below the limit. Using zipimport, you can include Django 1.0 with your application using just 1 file, leaving plenty of room for your own application files in the 1,000 file limit. A single ZIP archive of Django 1.0 is about 3 MB. This fits within the 10 MB file size limit. You may wish to prune unused libraries from the Django distribution anyway to further reduce the size of the archive. Update: Prior to the 1.1.9 release of the Python SDK in February 2009, the file size limit was 1 MB. With 1.1.9, the limit has been increased to 10 MB. These instructions produce a Django archive smaller than 1 MB. To make an archive containing all of Django, replace steps 2, 3 and 4 below with the following command: zip -r django.zip django To download and re-package Django 1.0 as a ZIP archives: - Download the Django 1.0 distribution from the Django website. Unpack this archive using an appropriate tool for your operating system (a tool that can unpack a .tar.gzfile). For example, on the Linux or Mac OS X command line: tar -xzvf Django-1.0.tar.gz - Create a ZIP archive that contains everything in the django/directory except for the .../conf/and .../contrib/sub-directories. (You can also omit bin/and test/.) The path inside the ZIP must start with django/. cd Django-1.0 zip -r django.zip django/__init__.py django/bin django/core \ django/db django/dispatch django/forms \ django/http django/middleware django/shortcuts \ django/template django/templatetags \ django/test django/utils django/views The confpackage contains a large number of localization files. Adding all of these files to the archive would increase the size of the archive beyond the 1 MB limit. However, there's room for a few files, and many Django packages need some parts of conf. Add everything in confexcept the localedirectory to the archive. If necessary, you can also add the specific locales you need, but be sure to check that the file size of the archive is below 1 MB. The following command adds everything in confexcept conf/localeto the archive: zip -r django.zip django/conf -x 'django/conf/locale/*' - Similarly, if you need anything in .../contrib/, add it to the archive. The largest component in contribis the Django Admin application, which doesn't work with App Engine, so you can safely omit the adminand admindocsdirectories. For example, to add formtools: zip -r django.zip django/contrib/__init__.py \ django/contrib/formtools - Put the archive file in your application directory. mv django.zip your-app-dir/ Using the Module Archive Tip: The latest version of the Django App Engine Helper (starting with version "r64") supports Django 1.0 with zipimport out of the box. Make sure your archive is named django.zip and is in your application root directory. All new projects created using the Google App Engine Helper for Django will automatically use django.zip if present. If you are upgrading an existing project you will need to copy the appengine_django, manage.py and main.py files from Google App Engine Helper for Django into your existing project. See Using the Google App Engine Helper for Django. The following instructions only apply if you are using Django without the Helper, or if you are preparing another module archive. To use a module archive, the .zip file must be on the Python module load path. The easiest way to do this is to modify the load path at the top of each handler script, and in each handler's main() routine. All other files that use modules in the archives will work without changes. Because App Engine pre-loads Django 0.96 for all Python applications, using Django 1.0 requires one more step to make sure the django package refers to 1.0 and not the preloaded version. As described in the article Running Django on App Engine, the handler script must remove Django 0.96 from sys.modules before importing Django 1.0. The following code uses the techniques described here to run Django 1.0 from an archive named django.zip: import sys from google.appengine.ext.webapp import util # Uninstall Django 0.96. for k in [k for k in sys.modules if k.startswith('django')]: del sys.modules[k] # Add Django 1.0 archive to the path. django_path = 'django.zip' sys.path.insert(0, django_path) # Django imports and other code go here... import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django.core.handlers.wsgi def main(): # Run Django via WSGI. application = django.core.handlers.wsgi.WSGIHandler() util.run_wsgi_app(application) if __name__ == '__main__': main() With appropriate app.yaml, settings.py and urls.py files, this handler displays the Django "It worked!" page. See Running Django on App Engine for more information on using Django. Using Multiple Archive Files for a Single Package Since all of Django 1.0 is too large to fit into a single archive, can we split it into multiple archives, each on sys.path? Actually yes, with some bootstrapping code to help Python navigate the different locations. When Python imports a module, it checks each location mentioned in sys.path for the package that contains the module. If a location does not contain the first package in the module's path, Python checks the next sys.path entry, and so on until it finds the first package or runs out of locations to check. When Python finds the first package in the module's path, it assumes that wherever it found it is the definitive location for that package, and it won't bother looking for it elsewhere. If Python cannot find the rest of the module path in the package, it raises an import error and stops. Python does not check subsequent sys.path entries after the first package in the path has been found. You can work around this by importing the package that is split across multiple archives from the first archive, then telling Python that the contents of the package can actually be found in multiple places. The __path__ member of a package (module) object is a list of locations for the package's contents. For example, if the django package is split between two archives called django1.zip and django2.zip, the following code tells Python to look in both archives for the contents of the package: sys.path.insert(0, 'django1.zip') import django django.__path__.append('django2.zip/django') This imports the django package from django1.zip, so make sure that archive contains django/__init__.py. With the second archive on the package's __path__, subsequent imports of modules inside django will search both archives. Additional Notes Some additional things to note about using zipimport with App Engine: - Module archives use additional CPU time the first time a module is imported. Imports are cached in memory for future requests to the same application instance, and modules from archives are cached uncompressed and compiled, so subsequent imports on the same instance will not incur CPU overhead for decompression or compilation. - The App Engine implementation of zipimport only supports .pyfiles, not precompiled .pycfiles. - Because handler scripts are responsible for adding module archives to the path, handler scripts themselves cannot be stored in module archives. Any other Python code can be stored in module archives.
https://cloud.google.com/appengine/articles/django10_zipimport?csw=1
CC-MAIN-2015-22
refinedweb
2,017
59.09
17 February 2012 03:42 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> “The location of the new plant is still undecided,” said the source. Construction of the new 41,250 tonne/year formaldehyde plant is expected to be completed in two years, the source said. Assam Petrochemical may initially import methanol to feed into the new formaldehyde plant, the source said. Meanwhile, the company is planning to start building a 165,000 tonne/year methanol plant at Namrup in the next three months, with completion expected in three years. It currently has a natural gas-based 33,000 tonne/year methanol plant at Guwahati in
http://www.icis.com/Articles/2012/02/17/9533096/indias-assam-petrochemical-plans-to-build-new-formaldehyde-plant.html
CC-MAIN-2015-11
refinedweb
105
63.9
Hot people. Thanks this time goes to Holger Blank, Malte Ubl, Jan Lehnardt and Tiffany Conroy. Keynote Brendan Eich (the creator of JavaScript) opened the conference with this Apple-inspired satirical advert for ES6. He was closely followed by Jed Schmidt (I knew I hadn't seen the last of him!) and Mandy Lauderdale performing an incredible assortment of topical songs about JavaScript. Unfortunately the quality of this video isn't great, but you'll get the idea! Mary Rose Cook - A Programming Language for Children Mary introduced a programming language that she's aiming at children called Isla. During her talk she said something that has really stuck with me. Programming is about magic. The magic that happens once you've typed in your program and then you first see it run. Much the same as stacking dominoes and then knocking the first one over. Mary was right, I had forgotten that's why I love programming. Sticking to the theme, she suggested that every programmer should at some point try writing a language (if you're using JavaScript PEG.js and multimethod.js might come in handy). Michael Bebenita - Low Level JavaScript This talk was turtles all the way down! The Sam Dutton - WebRTC: Real-Time Communication Without Plugins A frustratingly high-level look at WebRTC, which you can think of as a P2P version of WebSockets. I was hoping for a real deep-dive into some of the details but we were only shown the shiny demos. Don't get me wrong the technology itself is very cool, I think we'll be seeing a lot more of it as the browser support improves. Lennart C. L. Kats - Effectively Building Language Tools This talk was a bit of a sales pitch, encouraging developers to start writing plugins for the Cloud9 IDE platform. Florian Loitsch - JavaScript as a Compilation Target - Making it Fast A look at how the DART team has approached optimising their JavaScript output. DART itself doesn't interest me too much but it was interesting to see how similar the DART optimisations are to the optimisations applied by the JavaScript JIT compiler. The take home from this talk, DART's not quite as bad as it used to be. John Bender - Faster JavaScript with Category Theory John gave us a crash course on category theory and how it could be applied to the jQuery internals to speed things up. I'd recommend checking out the Wield project page. Garann Means - Improvisational JavaScript Garann noticed that bloggers were applying Tina Fey's rules of improv to everything from the workplace to dieting and thought that JavaScript was missing out. Her talk was a very interesting take on how to design robust, easy-to-use library code and interfaces. I think the most relevant of the improv rules was "Say yes and...", i.e. expect that users will give you partial or broken input sometimes, so try your best to work with it instead of throwing it back in their faces. E.g. don't interrupt a sign-up flow with an error if someone chooses an existing username, use their user ID instead and allow them to change it at a later date. Axel Rauschmayer - JavaScript Inheritance: Beyond the Basics Axel did a deep dive into inheritance as it was in JavaScript in ES3, how some new features in ES5 can help tidy up your code and how the proposed class feature of ES6 could help even further. My pro-tip - Functions have a prototype property Objects have an internal prototype reference Angus Croll - Break All the Rules A great talk systematically arguing the case for each of JavaScript's "Bad Parts". It was another spot-on reminder not to take advice at face value, but to look deeper into the problem and try to fully understand it. Margaret Leibovic - Firefox for Android Margaret flew the flag for the recently revamped Firefox for Android. Most of the browser chrome has been thrown out and replaced with a native UI to speed things up. The talk inspired me to try it out again as my experiences with the old version were very disappointing. Something I was pleasantly surprised to see mentioned was that Mozilla are looking to copy the iOS add to homescreen functionality over to Android. UPDATE - It is actually implemented but very well hidden in the menus compared to the iOS approach. Stuart Memo - JavaScript is the New Punk Rock A fascinating well-delivered talk on how the new web audio API could shake up music production again. Interspersed with live musical demos, Stuart delivered one of my favourite talks. James Halliday - Code Collage A nice reminder of the unix do one thing and do it well approach as applied to Node modules from one of the biggest package contributors on NPM, substack. This was extreme live coding, executed brilliantly. I didn't meet one person who wasn't in awe of this talk. Anders Heijlsberg/Luke Hoban - Introducing TypeScript This was a talk I was surprised to see on the schedule but I'm very glad it was. I'd already given a quick summary of my thoughts before the conference so I was looking forward to the talk. However, the feeling of people I talked to prior to the presentation was unanimously negative. Microsoft certainly don't have the best history on the web and I think people were concerned that this was VBScript2. The talk was great, it was really interesting to hear that Microsoft have been working on this project for 2 years, and to me it shows. If you haven't tried it out then I encourage you to checkout it's playground on the official site (start with the Walkthrough: JavaScript then Walkthrough: Types) and read through Nicholas C. Zakas's very balanced discussion of it's pros and cons. On a side note, wildly extrapolating from some shreds of evidence, I think we might soon see a browser-based Visual Studio from Microsoft. The editor used in the playground is a custom component that Microsoft has authored, which seems a strange choice for such a simple demo, as there's plenty of very good open-source options. Digging a bit deeper into the code behind the editor, all of it is namespaced under "vs". Even if they did choose to write one just for the playground the internal architecture is vastly over engineered for something so trivial, e.g. using multiple web-workers in the background. Even just comparing the size of the codebase to CodeMirror, it comes out suspiciously large. Francisco Jordano - OpenWebDevice: First Mobile Running Firefox OS Francisco introduced Firefox OS, Mozilla's late (and as yet unfinished) entry into the smartphone operation system race. In essence they've made PhoneGap, but at the operating system level instead of the app level. It's an interesting concept, but it's one that's already been tried unsuccessfully by Palm, so I'm hedging my bets on this one. Matthew Delaney/Jing Jin - The Web's Black Magic: As Viewed from Within WebKit Matthew and Jing picked a bit of a strange storyline for their talk but the content was really interesting. In essence they picked three optimisation techniques that are often touted on the internet as being the solutions to various performance problems, then set about explaining the WebKit source code behind the problem and the solution. The first was why you need to use setTimeout to trigger CSS transitions. This was a fairly basic explanation of the JavaScript event loop, but it was interesting to learn that a single execution cycle is called a runloop. The second problem was mixing DOM writes and reads in a loop. The solution is obviously to bundle all your reads together and your writes together but I was surprised at how hard it can be to spot that you've fallen into this trap. The final problem was the widely misunderstood just slap transformZ(0) on it. The talk covered the benefits of hardware compositing and how it can be abused. In summary use it wisely! Angelina Fabbro - Inspector Web and the Mystery of the Shadow DOM Angelina's talk on the shadow DOM was great, it's a very exciting topic which she devlivered with some steady-handed live coding. The shadow DOM is definitely the biggest thing yet to happen to the web and I'll be following it's progress closely. Divya Manian - Web Components with <insert favourite bleeding edge CSS spec> Divya took a deep dive into some of the topics Angelina introduced, showing how they can work together with other new CSS technologies e.g. regions, shaders(!) and more. Emily Rose - Node.js & Black Box Prototyping Thomas Kroeber - JavaScript on the Raspberry Pi Sebastian Golasch - Prof. JavaScript and his Incredible Machines There were then a number of hardware related talks, hardware I hear you ask, at a JavaScript conference?! Well yes, four talks in fact, mostly based around the Johnny-Five Node module. Johnny-Five is a framework for controlling an Arduino board from your computer using the Firmata protocol. To be clear this isn't JavaScript running on the Arduino itself, but rather JavaScript running in Node controlling the Arduino via the serial port. Emily Rose, Thomas Kroeber and Sebastian Golasch all showed off hardware projects to varying degrees of success. If you thought the software demo gods were bad, they've got nothing on the hardware demo gods! It was really interesting to see these projects, but as so few of the demos came off I think it would have been nice to see them condensed into a single talk. Jason Huggins - Everyone Loves Robots Those paying attention will have noticed that I said there were four hardware talks mentioned three. That's because Jason's hardware talk deserves special mention for a number of reasons. Firstly his demo came off without a hitch, secondly he used a robot to play angry birds and thirdly, HE USED A ROBOT TO PLAY ANGRY BIRDS! Even better he had a legitimate reason for doing so. He's one of the co-creators of Selinium and was looking for a fun way to automate UI testing on an iPad, I think he found it! I'd previously come across Jason's project on Hack-a-Day after he gave a talk earlier in the year at Pycon. The robot uses his miniaturisation of Grid-Beam called Bit-Beam for it's structural components, as soon as I saw Grid-Beam I was fascinated and had to try building some. I lost a four day bank-holiday weekend to that endeavor, so it was great to meet him and pass on the opinion of my significant other! Andrew Miadowicz - What Does Chakra do with your JavaScript? An interesting talk on how the IE10 (and therefore Windows 8 ) JavaScript engine works. JITs are like black magic to me so it was nice to get a crash course in how to write an efficient one. I can't begin to summarise the talk technically but I was impressed by the lengths they're going to when trying to achieve the best possible performance and security. With my limited knowledge, I think his top tip for writing a fast JIT was to optimistically assume the best and re-JIT if that proves not to be the case. Markus Leutwyler - How to get rich (quick) with JS Markus delivered quite a slow talk extolling the virtues of open-sourcing your product and making money from hosted services. I'm not sure I agree with him that you can't make money from developer tooling, Microsoft and JetBrains seem to be doing alright from it! Mr.doob/AlteredQualia - What's Next for Three.js? If you've not heard of Mr.doob I can only assume you're some kind of archivist looking over centuries old blog posts looking for the meaning of life (it's 42 by the way). Mr.doob is responsible for a good share of the crazy HTML5 experiments you'll have seen (this list is less than half). Together with AlteredQualia he is also responsible for the THREE.js JavaScript 3D graphics library which I've scratched the surface of previously. They took turns talking us through the history of THREE.js. I hadn't previously realised that the leaps in functionality e.g. WebGL support, had come from working with various Google sponsored projects. It was really interesting stuff and as these screenshots show, the progress the web has made in the past two years really is astounding - Paul Campbell/Eamon Leonard - Seacht Paul and Eamon are the organisers of Funconf, if you've never heard of it before (I fell into this category) - - Know that you've missed out on something very special. - Read this write-up of Funconf II. - Imagine that Funconf III introduced more DeLoreans, a private train, helicopters and horse and carts to the mix. The gents treated us to a very honest informal chat introducing the conferences, telling us about what it meant to them and now that it's run it's course how it's encouraged them to go on and organise more community events. It was a very inspirational talk that has pushed me to make more of an effort engaging with local user groups and tech meetups. Chris Williams - Disconnect (space intentionally left blank)
https://blog.scottlogic.com/2012/10/12/jsconf-eu-2012.html
CC-MAIN-2021-21
refinedweb
2,248
59.94
TypeError: unsupported operand for '*': integer and function To multiply an integer and a function seems to work in some cases: f = lambda n: n [2*f(n) for n in (0..9)] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] On the other hand I often receive this error message but cannot see an error in my code: /projects/sage/sage-6.9/src/sage/structure/element.pyx in sage.structure.element.RingElement.__mul__ (/projects/sage/sage-6.9/src/build/cythonized/sage/structure/element.c:17265)() 1852 elif PyInt_CheckExact(left): 1853 return (<ModuleElement>right)._mul_long(PyInt_AS_LONG(left)) -> 1854 return coercion_model.bin_op(left, right, mul) 1855 1856 cpdef RingElement _mul_(self, RingElement right): /projects/sage/sage-6.9/src/sage/structure/coerce.pyx in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/projects/sage/sage-6.9/src/build/cythonized/sage/structure/coerce.c:9739)() 1068 # We should really include the underlying error. 1069 # This causes so much headache. -> 1070 raise TypeError(arith_error_message(x,y,op)) 1071 1072 cpdef canonical_coercion(self, x, y): TypeError: unsupported operand parent(s) for '*': 'Integer Ring' and '<type 'function'>' Can someone explain what is going wrong here? Edit: Now I see what is going wrong: my expectations lead me astray! With Maple and f := n->n: two := n->2: (1) seq(2*f(n), n=0..9); (2) seq((2*f)(n), n=0..9); (3) seq((two*f)(n), n=0..9); All three versions lead to what I expect: 0, 2, 4, ... Not so with SageMath! Here only (1) works, (2) and (3) give TypeErrors. I'd call Maple's approach more natural and user-friendly. Perhaps things could be enhanced? The comment of the implementer "1069 # This causes so much headache" looks like this might be seen as a problem also by others. I edited my answer to answer the edit in your question.
https://ask.sagemath.org/question/31911/typeerror-unsupported-operand-for-integer-and-function/
CC-MAIN-2018-17
refinedweb
311
52.15
High performance, maintainable stylesheets. CSS. Interested in contributing, or just seeing CSS Blocks in action? Head over to CONTRIBUTING.md to learn how to spin up the project! With css-blocks added to your project, you receive: But, most importantly, CSS Blocks is ⚡️Statically Analyzable. Static analysis means css-blocks can look at your project and know with certainty that any given CSS declaration will, will not, or might under certain conditions, be used on any given element in your templates. Most stylesheet architectures have to walk a fine line between performance and maintainability. Tilt too far in either direction and either your users or the developers will end up paying the cost. With CSS Blocks, you can focus on making sure your stylesheets are easy to maintain as your application changes, and with the new CSS optimizer, OptiCSS, the small size of your app's production stylesheets after compression will amaze you. Gone are the days where you spend several minutes debugging your app only to discover a subtle typo that caused a selector to not match – CSS Blocks will give you a build error and suggest possible fixes. With IDE integration, projects using CSS Blocks will be able to quickly navigate to selector definitions that match your current template element and find which template elements match your current selector, autocomplete class names. With CSS Blocks new resolution system, cascade conflicts will be caught for you before you even know they exist and you will never have to fight a specificity war ever again. CSS Blocks is inspired by CSS Modules, BEM and Atomic CSS For a full deep-dive of the project architecture, I heavily recommend you review the CSS Blocks Architecture README! CSS Blocks requires deep integration with your build system and templating language. To learn how to install css-blocks for in your application, please consult the specific docs for your templating system and build system. CSS Blocks is available for use in the following templating languages: And has integrations with the following build systems: Don't see your preferred platform yet? Learn how to make your own Template Integration or Build System Integration and contribute it back! CSS Blocks is under active development and there are a number of features that have not yet been implemented! You can get a snapshot of the feature-set state here. ✅ = Implemented | ❌ = Not Implemented | 💀 = Deprecated | 🖌 = In Proposal | |Status| Feature | Description | |:--:|:--|:--| | Selectors || | ✅ | :scope| Scope selector for component root. | | ✅ | .class| Class selectors for component sub-elements. | | ✅ | .class[name]| State that is applied to scope and class selectors on state existence. | | ✅ | .class[name="value"]| Mutually exclusive sub-states for scope and class selectors to be applied when a sub-state value matches. | | ❌ | [name=value]| Bare state (not associated with an Originating Element) and optional substate selectors for targeting all elements in the Block that possess the state and/or sub-state. | | 🖌 | .class[name=value default]| Default state value to be applied when there is no other match. | | At Rules || | ✅ | @block local-name from "./file/path.css"| Reference another Block using a local name. | | ✅ | @block-debug block-name to channel| Debug call that will print a block interface to a "channel": comment, stderr, or stdout. | | ✅ | @block-global block.path| Declare a Block class or state as public. It may be used as a context selector in other Blocks. | | Properties || | ✅ | block-name: "custom-name";| Provide custom Block names in :scopefor a nicer debugging experience. | | ✅ | implements: block-name;| A Block can declare that it implements one or more other Block's interfaces in its :scopeselector and the compiler will ensure that all of those states and classes are styled locally. | | ✅ | extends: block-name;| A Block may specify it extends another Block in its :scopeselector to inherit and extend all the class and state implementations therein. | | ✅ | composes: "block.path";| Mixin-Style class and state composition. Apply other Blocks' Styles to one of yours. | | Functions || | ✅ | resolve("block.path");| Provide an explicit resolution for a given property against another Block. | | ❌ | constrain(val1, val2 ... valN);| Constrain this property to a list of specific values that may be set when this Block is extended. | | ❌ | range(min, max);| Constrain this property to a range of values that may be set when this Block is extended. | A "Block" is an isolated stylesheet, written in its own file, that contains all rulesets for any elements, and their various modes and interaction states, for a discrete unit of styling – like a component or design pattern. Typically, a single Block will contain styles for a particular component or concept, but it is entirely natural – and encouraged – for a template to consume multiple blocks and compose them together in the markup. A Block file may contain: The scope ruleset contains styles applied to the root of the scoped style subtree. All other elements assigned styles from a Block must be contained in the document subtree of an element assigned to the block's :scope. We use the special :scopepseudo-class to represent these styles. The :scopeselector may contain the special block-nameproperty so you may provide your own Block name for easy debugging and BEM class generation. If no block-nameis provided, we will infer the Block name from the file name. 💡 Feature Note: Block Names If two Blocks in your project have the same name, CSS Blocks will automatically generate a unique, but still human-readable, name for BEM output mode. :scope { block-name: custom-block-name; /* 👆 optional! */ /* ... more styles ... */ } Blocks may can contain other classes that may be applied to elements inside the scoped style sub-tree. These are just class selectors, but they are local to that Block and isolated from all other similarly named classes in other Blocks. .sub-element { /* ... */ } .other-sub-element { /* ... */ } Together, the :scopeselector and all declared .classselectors define the full interface of stylable elements available to a Block's consumer. States represent a mode or interaction state that the :scopeor a class – called the state's originating element – may be in. States are written as attribute selectors with the special statenamespace. :scope { /* ... */ } :scope[enabled] { /* ... */ } .sub-element { /* ... / } .sub-element[is-active] { / ... */ } ⁉️ What the pipe is going on here? Once upon a time, developers fell in love with XML and thus was born xhtml, a flavor of HTML that allowed HTML elements to be mixed together with elements from other XML syntaxes like SVG and MathML. CSS went along for the ride and so, while many have never seen or used the feature, CSS has support for namespaced elements and attributes. In CSS, the|symbol is used to delimit between a namespace identifier (assigned by the@namespaceat-rule) and the element or attribute name (also called a qualified name). In markup, instead of a pipe symbol, the colon is used to delimit a namespace identifier and a qualified name. Yes, this is confusing -- but we don't make CSS syntax, we just use it. States on the :scopeselector or a class selector may contain sub-states for more granular styling. Sub-states of a State are mutually exclusive and an element may only be in one sub-state of that state at any given time. :scope { /* ... */ } :scope[theme="inverse"] { /* ... */ } .sub-element { /* ... */ } /* Applied for any value of color, including no value. / .sub-element[color] { / ... */ } /* Applied for specific values of `color / .sub-element[color="red"] { / ... / } .sub-element[color="blue"] { / ... / } .sub-element[color="yellow"] { / ... */ } CSS Blocks implements a strict subset of CSS. This means we've intentionally restricted some of the features you're allowed to use in a Block file to ensure we can optimize your stylesheets as much as possible! As Opticss improves, we may choose to loosen some of these restrictions – keep an eye out for syntax updates as we approach thev1.0.0release! ::before, ::after, and all other pseudo-elements :hover, :active, and all other pseudo-classes, @media, @breakpoint, and all other @at-rules !importantis forbidden – you won't be needing it! tag, non-state [attribute], #idand *selectors are forbidden (for now!) :matches(), :not(), :something()and :has()are forbidden (for now!) In css-blocks, shallow selectors mean: /* ✅ Allowed! */ :scope:hover > .my-class { /* ... */ } /* ❌ Illegal! / :scope:hover > .my-class + .my-class { / ... */ } :scopestates, sub-states, or pseudo-classes. /* ✅ Allowed! */ :scope:hover .my-class { /* ... */ } :scope[active] > .my-class { /* ... */ } :scope[color=red] .my-class { /* ... */ } /* ❌ Illegal! / .container:hover > .my-class { / ... / } .container[active] .my-class { / ... / } .container[color=red] .my-class { / ... */ } :scopeused in the key selector. /* ✅ Allowed! */ .my-class + .my-class { /* ... */ } .my-class:hover ~ .my-class { /* ... */ } .my-class[active] + .my-class { /* ... */ } /* ❌ Illegal! / :scope + .my-class { / ... / } .another-class:hover ~ .my-class { / ... / } .another-class[active] + .my-class { / ... */ } 💡 Feature Note: Global States and Selectors "Global States" have their own rules on how they can be used in Block selectors! Keep an eye out for them a little later in this doc. Of course, because we statically analyze and compile all your code before it ever hits the browser, you will get a helpful error if any of these syntax restrictions are violated. Every specific template integration with css-blocks will have their own slightly unique syntax for how to interface with Block files. However, they all will allow you to apply classes and states in a way that is analyzable and rewritable at build time. 💡 Feature Note: Template Integrations Each integration implements a slightly different API. Ex: JSX lets youimportBlock files, Ember looks for, through convention, astylesheet.cssalongside every component template. Check out the README for your template language for full details. However, whatever the implementation is, it will feel as though you're interfacing with regular CSS on the platform. For example, in Glimmer you just write the classes and states exactly as you would expect when working with a normal stylesheet: :scope { /* ... */ } :scope[enabled] { /* ... */ } .button { /* ... */ } .icon { /* ... */ } .icon[inverse] { /* ... */ } {{!-- :scope selector is automagically applied to the template's root-level element. Thanks Glimmer! --}} {{value}} There are only two (2) common-sense rules to follow when using Block styles in your template: :scope's subtree. Blocks styles are, by design, scoped to the file they are written in, but we all know that in a real app your styles can't live in a vacuum! As you'll see below, there are many methods to compose blocks together in your application. However, most of these methods will begin with the humble @block. A Block may declare a dependency on another Block by using a @blockat the top of your file. A @blockcreates a locally scoped alias where you can access the public API (declared classes and states) of the referenced block. Block references don't cause any styles to be included. Instead, they are like an ES6 importstatement -- they make it possible to refer to the public interface of another Block from within the current Block. Adding a @blockis as simple as this: /* block-1.block.css */ :scope { block-name: block-1; } .my-class { /* ... */ } .my-class[my-state] { /* ... */ } /* block-2.block.css */ @block other-block from "./block-1.block.css"; :scope { block-name: block-2; } 🔮 Future Feature: Node Modules Block Resolution Whether you're integrating with a 3rd party library, or pulling in dependencies internal to your company, at some point you'll want to integrate with styles delivered via NPM! The resolution logic for@blocks tonode_moduleshasn't yet been implemented yet, but you can track progress (or even help out!) over on Github. With the above code, block-2now has a local reference other-blockwhich points to block-1. We can now freely use the other-blockidentifier inside of block-2when we want to reference reference block-1. This comes in handy! Especially with features like: A Block's public interface is defined by the states and classes it styles. A block may declare that it implements one or more other referenced blocks' interfaces, and the compiler will ensure that all the states and classes it defines are also in the implementing block. In this way, the compiler can guarantee it is safe to use different blocks to style the same markup in a component. You do this via the special implementsproperty in a Block's :scopeselector: /* block-1.block.css */ :scope { block-name: block-1; } .my-class { /* ... */ } .my-class[my-state] { /* ... */ } /* block-2.block.css */ @block other-block from "./block-1.block.css"; :scope { block-name: block-2; implements: other-block; } 💡 Feature Note: Implements Property Theimplementsproperty is only available in the:scopeselector. If you use it in any other selector, it will be ignored. However, the above code will throw an error at build time! $ Error: Missing implementations for .my-class, .my-class[my-state] from ./block-1.block.css For the build to pass, we need to implement the full public interface of block-1in block-2: /* block-2.block.css */ @block other-block from "./block-1.block.css"; :scope { block-name: block-2; implements: other-block; } .my-class { /* ... / } .my-class[my-state] { / ... */ } A Block may also choose to extend another referenced Block. This exposes all declared styles from the extended Block on the extending Block. Those inherited styles may then be used in a template by accessing them on the extending block, and can even be augmented by re-declaring the styles in the extending block! You do this via the special extendsproperty in a Block's :scopeselector. Lets say we have a component called. Basic forms have an input element, and a big green button. Simple enough: /* basic-form.block.css */ .button { font-size: 1.4rem; color: white; background-color: green; } .button[disabled] { color: #333; background-color: lightgray; } .input { font-weight: bold } But, as the project evolves we realize we need a new form for submitting information for a dangerous action, we're asked to create a new kind of form called. Danger forms look and function exactly the same as a basic form, except the button and labels are red. We could re-implement the entire stylesheet to create , but that would be a such a waste of all the hard work we already put in to ! Instead, we can simply extend theBlock, and only apply the small style changes we need: /* danger-form.block.css */ @block basic-form from "./basic-form.block.css"; :scope { extends: basic-form; } .button { background-color: darkred; } .label { color: darkred; } During rewrite, references to an inherited style will translate into the class(es) for the directly referenced style as well as all the classes that it inherits from so developers do not need to bring the complexity of the inheritance relationship into their templates. For example, a reference to danger-form.buttonwould result in adding both .basic-form__button, as well as .danger-form__buttonto the element's list of classes. When the blocks are compiled, property overrides are detected and automatically resolved. The selectors generated serve two purposes: .basic-form__button { font-size: 1.4rem; color: white; background-color: green; } .basic-form__button--disabled { color: #333; background-color: lightgray; } .basic-form__input { font-weight: bold; } .danger-form__button { background-color: darkred; } .basic-form__button.danger-form__button { background-color: darkred; } .danger-form__button--disabled { background-color: #957d7d; } .basic-form__button.danger-form__button--disabled { background-color: #957d7d; } .basic-form__button--disabled.danger-form__button--disabled { background-color: #957d7d; } .danger-form__label { color: darkred; } While this output is highly repetitive and may seem excessive, it's exactly the kind of repetition that OptiCSS is designed to search for and remove. From an authoring experience and in production, it's a laser-focused override with no performance impact. 💡 Feature Note: Extends Property Theextendsproperty is only available in the:scopeselector. If you use it in any other selector, it will be ignored. An extending block is able to re-define any property on any style it inherits from. CSS declarations defined in the extending Block will always take priority over the definitions inherited by the same named Style in the base Block. 🔮 Future Feature: Extension Constraints Sometimes, properties inside of a component are so important, that authors may want to constrain the values that extenders and implementors are able to set. In the near future, css-blocks will enable this use case through the customconstrain()andrange()CSS functions and possibly through other ideas like custom constraints and conflicts. You can come help out over on Github to make this happen faster! As your Blocks begin interacting with each other in increasingly complex ways, you will find yourself needing to reference specific classes or states on another Block, as you'll see later in this document. You do this using a small query syntax called a Block Path. Block Paths take the form: block.class[name='value'] All sections of this selector – except the leading Block name – are optional. The leading Block name must refer to an imported @blockat the top of the file. If css-blocks is unable to resolve a Block Path at build time, you will get a friendly error message in your console! All the following syntaxes are legal to select any given stylable on a referenced Block: |Stylable|Syntax| |:--|:--| |Scope| block| |Scope State| block[name]| |Scope Sub-State| block[name=value]| |Class| block.class| |Class State| block.class[name]| |Class Sub-State| block.class[name=value]| 🔮 Future Feature: Block Path Wildcards In some situations, you may want to select multiple classes, states or sub-states on a referenced block. In the near future you will be able to do so with a wildcard syntax:block.*,block.class[*],block.class[name=*]. Feel free to track progress of this feature here Every template integration will provide a way to use more than one Block inside of a template. The syntax for this may change depending on your templating system, so please check with your specific template integration's documentation. For Glimmer, using multiple blocks in a single template will look something like this: /* hoverable.css */ :scope { block-name: hoverable; box-shadow: 0 2px 3px rgba(0, 0, 0, 0.2); transition: box-shadow .28s; } :scope:hover { box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2) } .button { background-color: rgba(255, 255, 255, .5); color: black; transition: background-color .28s; } :scope:hover .button { background-color: rgba(255, 255, 255, 1); } /* stylesheet.css */ @block other from "./hoverable.css"; :scope { block-name: main; } .form { border: 1px solid gray; border-radius: 2px; padding: 16px; } .button { background-color: green; color: white; height: 32px; width: 100%; } {{!-- :scope selector from stylesheet.cssis automagically applied to the template's wrapper element. Thanks Glimmer! --}} Click Me! Above we have a simple template that contains a form with a single button that says "Click Me!". We style it with styles from the default Block for the template, stylesheet.css, and with styles from the referenced Block hoverable.css, referenced in this context as other. In this template, we have theelement assigned the scoped root for other, and we apply the buttonclass from both blocks to the element. But wait! If you try and run the css-blocks build with this code, you'd find an error in your console! The following property conflicts must be resolved for these co-located Styles: (template.hbs:4:19) color: main.button (stylesheet.css:12:2) hoverable.button (hoverable.css:12:2) background-color: main.button (stylesheet.css:11:2) hoverable.button (hoverable.css:11:2) Woah, what does this mean?! Well, if we stop and think for a second about what we just asked css-blocks to do, we'll realize that this error makes perfect sense. Because Blocks have their own entirely independently scoped cascades, and right now no Block file is aware of any other Block's styles, css-blocks doesn't inherently know which Block should take priority over another when used together. So, when css-blocks was asked to put the .buttonclass from both the default template stylesheet, and from hoverableonto the same element, it noticed that both classes are claiming to set the colorand background-colorproperties – and with this we have encountered our first Indeterminate Cascade Resolution. Which Block should win in this situation? Right now, the compiler has no idea. To answer that, css-blocks needs a little help from you. We are able to provide explicit cross-Block cascade resolutions to the compiler by using resolve(). Lets learn how we can fix our above error by moving on to the next section: Block Resolutions. The special resolve()function provides explicit resolution guidance for properties that are in conflict across two or more Block files. They look like any other property declaration: selector { property-name: resolve(""); } You will be asked by the css-blocks compiler to add resolutions if and when two styles are found on the same element in your templates that attempt to set the same CSS property. Resolve declarations work just like progressive enhancement and graceful degradation! The last declaration defined in the ruleset will win. This means that declaration order matters. There are two ways to resolve any given property: Override resolutions tell css-blocks that when these two styles are used together, we want this Block to override the value of the other Style's property. Here, we tell css-blocks to use the colorvalue from my-classinstead of other.selectorwhen both styles are applied to the same element: .my-class { color: resolve("other.selector"); color: red; } Yield resolutions tell css-blocks that when these two styles are used together, we want this Block to yield to the value of the other Style's property. Here, we tell css-blocks to use the colorvalue from other.selectorinstead of my-selectorwhen both styles are applied to the same element: .my-class { color: red; color: resolve("other.selector"); } 🔮 Future Feature: Resolve All Shorthand For straightforward resolutions where you just want to yield or assume full control of styling against another block, feel free to use the CSSallproperty to quickly override or yield to all property conflict with another block. The downside of doing this is that as new properties are added to another element, you don't get a chance to review them and decide: .my-class { color: red; background: blue; /* Yields all conflicts to other.selector*/ all: resolve("other.selector"); } 💡 Feature Note: Advanced Property Conflicts The css-blocks compiler is smart! If you have dynamic classes or states in your template, it will ask you to provide explicit resolutions between Blocks that even only have a chance of being used together on the same element. This way, we can guarantee that your styles will work regardless of the state your application may find itself it. Css Blocks is also aware of CSS shorthands and will ask you to resolve the lowest common denominator on conflicting shorthand/longhand expressions as well. So, continuing with the example from the previous section – Composition in Templates – we can satisfy the css-blocks compiler by adding in two explicit resolutions for colorand background-colorlike so: /* stylesheet.css */ /* ... */ .button { /* Override Resolution */ background-color: resolve("hoverable.button"); background-color: green; /* Override Resolution */ color: resolve("hoverable.button"); color: white; /* ... */ } Here we have told css-blocks that when our component's .buttonclass is used with hoverable's .buttonclass, we want our component's style declarations to win! We have declared an override resolution for both properties. If we were to switch around the order a bit so our background-colorresolution comes after our component's declaration, it means that when these two classes are used together, hoverable's .buttonclass will win, but only for that property. This is why you will never have to fight the cascade or use !importantever again! /* stylesheet.css */ /* ... */ .button { /* Yield Resolution */ background-color: green; background-color: resolve("hoverable.button"); /* Override Resolution */ color: resolve("hoverable.button"); color: white; /* ... */ } 💡 Feature Note: States and Pseudo-Classes States and Pseudo-Classes inherit all resolutions set on their containing Class or:scope. This means that in the above example, where we yield forbackground-color, and override forcolor, the button element where both classes are used will still usehoverable.button:hover'sbackground-color, but it's color will remainwhite, like our component styles define! It is important to note that Pseudo-Elements do not inherit any resolutions from their container class and must be explicitly resolved in the source stylesheets when found to be in conflict. So, for the following two Blocks where my-class-1[enabled]and my-class-2are used on the same element, one of the Blocks will need to resolve the conflicting border-widthproperty: /* other */ .my-class-1[enabled]::before { border: 1px solid red; } /* main.css */ @block other from "./other.css"; .my-class-2::before { border-width: 2px; border-width: resolve("other.my-class-2[enabled]"); } Sometime a class, identifier, or tag name comes from an external source, and the only thing you can do is use them as is. In these situations the Block must declare all external simple selectors it intendeds to use. These simple selectors may then be used as key selectors inside this Block. You'll get an error for any declared external selectors that aren't used or if they are used in the context selector. Styles targeting an external selector are not rewritten and their declarations cannot be optimized! Style collisions on an external selector are not detected or resolved. As a result, it is allowed to use !importanton declarations targeting an external selector. Warning: If external selectors and CSS block objects both target the same HTML element in their key selectors you will get unpredictable results. It's best to avoid this. @external h2.some-rando-class; .foo h2.some-rando-class { font-size: 32px !important; } In rare occasions, a Block may choose to declare declare that a certain State is global. These states are special in that they can be used in other Blocks like they are local to that block. This is most useful for global application states – like during initial application boot, or when a modal is displayed. ⚙️ Performance Note: Global States When you apply classes and other attributes to elements likeor it invalidates a lot of internal caches in the browser. It is still often a performance win compared to querying the document in javascript and applying classes on many elements. /* application.block.css */ @block-global [is-loading]; @block-global [is-saving]; /* navigation.block.css */ @block app from "application.block.css"; /* Gray out signout button when app is saving */ :scope[app|is-saving] .signout { color: gray; pointer-events: none; } /* Animate the logo when app is loading data */ :scope[app|is-loading] .logo { animation-name: bounce; }
https://xscode.com/linkedin/css-blocks
CC-MAIN-2021-43
refinedweb
4,365
56.55
IRC log of ws-addr on 2005-05-02 Timestamps are in UTC. 19:36:14 [RRSAgent] RRSAgent has joined #ws-addr 19:36:15 [RRSAgent] logging to 19:36:20 [mnot] zakim, this will be WS_ADDRWG 19:36:20 [Zakim] ok, mnot; I see WS_AddrWG()4:00PM scheduled to start in 24 minutes 19:36:26 [mnot] Chair: Mark Nottingham 19:36:35 [mnot] Meeting: Web Services Addressing WG Teleconference 19:38:09 [mnot] Agenda: 19:38:12 [mnot] Agenda: 19:40:43 [Marsh] Marsh has joined #ws-addr 19:55:48 [Nilo] Nilo has joined #ws-addr 19:56:43 [mlpeel] mlpeel has joined #ws-addr 19:58:05 [Zakim] WS_AddrWG()4:00PM has now started 19:58:05 [MSEder] MSEder has joined #ws-addr 19:58:12 [Zakim] + +44.196.286.aaaa 19:58:59 [Zakim] +MarkN 19:59:12 [RebeccaB] RebeccaB has joined #ws-addr 19:59:32 [Zakim] +MSEder 19:59:45 [MSEder] zakim, mute me 19:59:45 [Zakim] MSEder should now be muted 19:59:51 [Zakim] +Rebecca_Bergersen 20:00:12 [Zakim] +Bob_Freund 20:00:19 [Zakim] -Bob_Freund 20:00:20 [anish] anish has joined #ws-addr 20:00:28 [dhull] dhull has joined #ws-addr 20:00:33 [Zakim] +Nilo_Mitra 20:00:44 [TonyR] TonyR has joined #ws-addr 20:00:53 [Zakim] +Dave_Hull 20:01:06 [Zakim] +Bob_Freund 20:01:13 [Zakim] +??P11 20:01:13 [Marsh] zakim, code? 20:01:14 [swinkler] swinkler has joined #ws-addr 20:01:14 [Zakim] the conference code is 2337 (tel:+1.617.761.6200), Marsh 20:01:22 [Zakim] +Jonathan_Marsh 20:01:29 [Marsh] zakim, who's making noise? 20:01:33 [Zakim] +Steve_Winkler 20:01:38 [abbie] abbie has joined #ws-addr 20:01:39 [swinkler] Zakim, mute me 20:01:39 [Zakim] sorry, swinkler, I do not see a party named 'swinkler' 20:01:41 [Zakim] Marsh, listening for 10 seconds I heard sound from the following: Bob_Freund (82%) 20:01:45 [prasad] prasad has joined #ws-addr 20:01:56 [swinkler] Zakim, Steve_Winkler is me 20:01:56 [Zakim] +swinkler; got it 20:02:02 [swinkler] Zakim, mute me 20:02:02 [Zakim] swinkler should now be muted 20:02:20 [Zakim] +Prasad_Yendluri 20:02:21 [Zakim] +Ugo_Corda 20:02:23 [swinkler] regrets for the second half of the call. I have to drop at 2. 20:02:45 [Zakim] +Tom_Rutt 20:02:46 [Zakim] +Abbie_Barbir 20:03:00 [Zakim] + +46.7.30.2.aabb 20:03:05 [Zakim] +[Sun] 20:03:21 [marc] marc has joined #ws-addr 20:03:22 [Arun] Arun has joined #ws-addr 20:03:26 [Zakim] +Mark_Peel 20:03:34 [yinleng] yinleng has joined #ws-addr 20:03:36 [Zakim] +[IBM] 20:03:46 [Paco] Paco has joined #ws-addr 20:03:57 [TomRutt] TomRutt has joined #ws-addr 20:03:58 [alewis] alewis has joined #ws-addr 20:04:18 [Zakim] +Marc 20:05:06 [Zakim] +Mark_Little 20:05:40 [andreas] andreas has joined #ws-addr 20:05:45 [Zakim] +ALewis 20:06:03 [Zakim] +DOrchard 20:06:07 [plh] zakim, call plh-work 20:06:07 [Zakim] ok, plh; the call is being made 20:06:09 [Zakim] +Plh 20:06:29 [Zakim] +pauld 20:06:40 [swinkler] Zakim, unmute me 20:06:40 [Zakim] swinkler should no longer be muted 20:07:03 [pauld] Scribe: pauld 20:07:13 [swinkler] Zakim, mute me 20:07:13 [Zakim] swinkler should now be muted 20:07:29 [Zakim] + +1.408.748.aacc 20:07:39 [pauld] Chair: Mark Nottingham 20:07:44 [Zakim] +??P30 20:08:03 [TonyR] zakim, ??p30 is me 20:08:03 [Zakim] +TonyR; got it 20:08:12 [TonyR] zakim, mute me 20:08:12 [Zakim] TonyR should now be muted 20:08:36 [TomRutt] TomRutt has left #ws-addr 20:08:51 [pauld] Meeting: Web Services Addressing 20:09:05 [pauld] Topic: Administrivia 20:09:11 [Zakim] + +1.781.861.aadd 20:09:15 [swinkler] zakim, unmute me 20:09:15 [Zakim] swinkler should no longer be muted 20:09:24 [pauld] register for Berlin F2F, room limited to 20 20:09:48 [pauld] s/register/mnot: register/ 20:10:04 [swinkler] zakim, mute me 20:10:14 [Zakim] swinkler should now be muted 20:10:45 [Zakim] +??P2 20:11:14 [pauld] mnot: minutes April 19th, April 20th approved 20:11:32 [pauld] zakim, ??p2 is yinleng 20:11:32 [Zakim] +yinleng; got it 20:11:47 [pauld] Topic: Action Item Review 20:11:55 [TomRutt] TomRutt has joined #ws-addr 20:13:38 [Zakim] -Bob_Freund 20:13:42 [Zakim] +Umit_Yalcinalp 20:14:12 [uyalcina] uyalcina has joined #ws-addr 20:15:12 [Zakim] +Bob_Freund 20:15:50 [pauld] Topic: Proposed New Issues 20:17:07 [mnot] Topic: Proposed - Semantics of wsa:UsingAddressing@wsd:Required="false" 20:18:33 [Zakim] + +1.781.883.aaee 20:18:33 [pauld] mnot: dhull oulines his new issue on semantics of wsa:UsingAddressing@wsdl:Required="false" 20:18:41 [pauld] 20:18:45 [Zakim] - +1.781.861.aadd 20:18:56 [pauld] s/mnot: dhull:/dhull: / 20:21:17 [anish] as a side-note there is an issue (in my mind) about what the default value of wsdl20:required is 20:21:40 [uyalcina] I have raised an issue on that one in WSDL 2.0 wg 20:21:52 [pauld] marsh: baffled as the relevance to WSDL required='false', why do we need to define how wsdl:required works in our spec 20:22:11 [swinkler] swinkler has joined #ws-addr 20:22:16 [swinkler] swinkler has joined #ws-addr 20:22:34 [pauld] dhull: advertising a service with wsdl:required changes the semantics of our spec 20:23:36 [dims] dims has joined #ws-addr 20:23:59 [Arun] zakim, mute me 20:23:59 [Zakim] sorry, Arun, I do not see a party named 'Arun' 20:24:07 [Arun] zakim, [Sun] is me 20:24:07 [Zakim] +Arun; got it 20:24:12 [Arun] zakim, mute me 20:24:12 [Zakim] Arun should now be muted 20:24:30 [Zakim] +dims 20:24:38 [dims] zakim, mute me 20:24:38 [Zakim] dims should now be muted 20:24:47 [TomRutt] q+ 20:24:51 [Zakim] -Bob_Freund 20:25:12 [mnot] ack TomR 20:25:18 [pauld] discussion between paco and dhull regarding the scope of this issue over other bindings 20:26:18 [anish] q+ to find out whether the issue is -- how the server knows that ws-addr is engaged. Or is it more? 20:27:37 [Zakim] +Bob_Freund 20:27:41 [mnot] ack anish 20:27:41 [Zakim] anish, you wanted to find out whether the issue is -- how the server knows that ws-addr is engaged. Or is it more? 20:29:55 [pauld] tom: clarification of issue; the case we talking about is where a client isn't using addressing and doesn't send wsa:action. 20:29:57 [pauld] paco: should be possible to tell at the xml level if wsa is engaged 20:30:00 [pauld] anish: is the issue about how the server can detect addressing is engaged? 20:30:01 [pauld] dhull: possible to have bindings which don't work that way (scribe having difficulty hearing) 20:31:59 [Zakim] -Abbie_Barbir 20:32:06 [pauld] anish: so a strange binding that doesn't have something in the message to indicate addressing is in play may need something above current WSDL language 20:32:19 [plh] zakim, mute me 20:32:19 [Zakim] Plh should now be muted 20:32:34 [pauld] mnot: concerned that the current wording of the issue doesn't capture the discussion 20:33:00 [pauld] daveo: i'm confused 20:33:06 [pauld] umit: what's the likelyhood of this happening? 20:34:16 [Zakim] +JeffM 20:34:26 [pauld] dhull: cites intermediary use-case 20:35:15 [pauld] ACTION: dhull to restate the new issue regarding wsdl required='true' semantics 20:36:19 [pauld] mnot: volunteer for owning new issue regarding namespace split across two documents 20:36:48 [pauld] ACTION: jmarsh to promote discussion in issue i60 20:37:09 [pauld] Topic: issue lc6 and lc35 20:38:39 [dhull] q+ 20:39:35 [anish] q+ 20:40:04 [pauld] marsh: had an action to move this forward. still like my original formulation, but modified it folowing discussion related to 'endpoint conformance'. Does a conformant endpoint have to reject messages without wsa headers? Conformance only applies where wsa headers are in play. 20:40:15 [Zakim] -Mark_Little 20:40:33 [mnot] ack dhull 20:41:11 [pauld] mnot: messages on the list are still very fresh and many will not have seen them, so will time limit this discussion 20:41:33 [mnot] ack anish 20:42:54 [pauld] anish: reformulation isn't what i had in mind. An endpoint should conform to the soap binding specification which doesn't define how and when to send fault or reply messages. these are defined by WSDL MEPs and our specification 20:43:18 [TomRutt] TomRutt has left #ws-addr 20:43:58 [pauld] marsh: spec doesn't define what is a request-response MEP. We don't need to nail that down as it's in the domain of other specs. 20:44:17 [dhull] q+ 20:44:35 [pauld] anish: MEP in play belongs in the soap binding specification 20:45:18 [pauld] umit: unclear why this is a conformance for soap or core specs, rather wsdl section. 20:45:48 [pauld] paco: request-reply may exist regardless of if there is a WSDL description 20:46:24 [pauld] s/of if there is/of there being/ 20:46:42 [pauld] anish: not necessary rules have to be defined in WSDL 20:47:19 [pauld] paco: specs don't mandate a reply has to be sent, just how fields are used when on is sent 20:47:27 [pauld] marsh: that captures my intent 20:49:41 [pauld] dhull: core and soap are bound together. reads section 3 regarding MAPs as implying a fault / reply must be sent. compliance testing would test sending a response as an assertion 20:50:09 [pauld] marsh: spec should not define case when we don't use addressing. 20:50:54 [uyalcina] q+ 20:51:16 [pauld] dhull: sending a message to a conformant endpoint without addressing should be faulted. 20:51:49 [pauld] marsh: core specification isn't testable on its own, only when used inanother context, such as soap 20:53:17 [pauld] dhull: sounds like we're in agreement, solicits if anyone agrees we need more precise text. don't think normative statements belong in the core. 20:53:29 [pauld] marsh: agreed 20:53:58 [mnot] ack dhull 20:54:11 [pauld] s/agreed/agreed (conformance to the core is ill defined)/ 20:54:33 [pauld] daveo: agrees conformance to the core is not well defined 20:54:33 [mnot] ack umit 20:54:38 [mnot] ack uyal 20:54:52 [Zakim] -MarkN 20:55:23 [Zakim] +MarkN 20:55:38 [pauld] paco: one option is to put soap binding and core together in the same document 20:56:33 [dhull] q+ 20:56:43 [pauld] .. conformance can only be proven if core is paired with a binding. that's a well defined statement and may allow the core to remain separate. 20:56:49 [pauld] anish: agrees 20:57:08 [dhull] q- 20:57:29 [pauld] Topic: lc26 20:59:08 [pauld] marsh: had action to clarify fault to be returned if wsa:action header differs from http action in soap 1.1/1.2 20:59:58 [pauld] .. soap 1.1 has a required soapAction header (WS-I BP) 21:00:47 [pauld] .. proposal allows soapAction to be empty 21:00:58 [bob] bob has joined #ws-addr 21:01:11 [pauld] anish: we should clarify empty means open-quotes, closed-quotes to match WS-I BP 21:01:31 [Zakim] -swinkler 21:02:13 [pauld] marsh: do we have to define empty given it's possible for people to not be using the BP? 21:02:33 [pauld] mnot: suggests using BP as an example 21:02:34 [Zakim] -yinleng 21:02:42 [uyalcina] +1 to Marc 21:03:10 [pauld] marc: we should use this chance to nail text to match the BP 21:03:14 [mnot] zakim, who's making noise? 21:03:25 [Zakim] mnot, listening for 11 seconds I heard sound from the following: MarkN (13%), +44.196.286.aaaa (83%), Jonathan_Marsh (22%) 21:04:00 [pauld] zakim, aaaa is mpeel 21:04:01 [Zakim] +mpeel; got it 21:04:08 [pauld] zakim, mute mpeel 21:04:08 [Zakim] mpeel should now be muted 21:04:10 [Zakim] -dims 21:04:48 [Marsh] "The SOAPAction HTTP header is required when using the SOAP 1.1 HTTP binding. The value of the SOAPAction HTTP header MUST either be identical to the value of the wsa:Action header, or empty. The latter case supports the ability to obscure the wsa:Action header through SOAP-level security mechanisms, without requiring otherwise unnecessary transport-level security. Failure to have an identical value, or an empty value for SOAPAction, results in the Invalid M 21:05:05 [TonyR] zakim, unmute me 21:05:05 [Zakim] TonyR should no longer be muted 21:05:09 [TonyR] q+ 21:05:17 [dhull] s/or empty/or be empty/ 21:06:14 [mnot] ack TonyR 21:06:34 [pauld] anish: does anyone want to be non-BP compliant (at least in this case)? 21:06:55 [pauld] tonyR: seems like low cost to allow non-BP cases 21:06:59 [pauld] marsh: works for me 21:07:09 [TonyR] zakim, mute me please 21:07:09 [Zakim] TonyR should now be muted 21:08:00 [pauld] ACTION: approved lc26 with Jonathan's original proposal combined with his updated proposal 21:08:33 [pauld] RESOLUTION: approved lc26 with Jonathan's original proposal combined with his updated proposal 21:08:43 [mnot] ... leaving out "" 21:09:11 [pauld] Topic: lc28 and lc33 21:09:17 [mlpeel] mlpeel has joined #ws-addr 21:09:46 [Marsh] 21:10:57 [pauld] marsh: outlines proposal 21:13:43 [pauld] marsh: editorial guidelines: we should use [] refps notation consistantly ; it should be clear that echoing headers is at the XML representation, not infoset level 21:14:08 [pauld] marc: may have already done some of this in the latest editors draft 21:14:50 [pauld] paco: fine with this 21:14:53 [dhull] q+ 21:15:25 [mnot] ack dhull 21:15:57 [pauld] mnot: suggests editors to work on this direction and WG to review 21:16:48 [anish] q+ 21:17:54 [mnot] ack anish 21:19:53 [dhull] q+ 21:20:13 [pauld] discussion between marsh and marc regarding use and structure of notation 21:21:03 [pauld] anish: suggest dropping use of serialized regarding infoset. prefers 'mapped' 21:21:21 [mnot] ack dhull 21:22:23 [bjarlestam] bjarlestam has joined #ws-addr 21:24:10 [pauld] discussion of serialising IRIs .. going off piste .. 21:26:05 [pauld] RESOLUTION: close issue lc28 with Jonathan's proposal and adding word 'infoset' where appropriate 21:26:54 [pauld] marsh: outlines proposal for lc33 21:28:16 [dhull] q+ 21:28:51 [mnot] 21:28:54 [anish] things would be so much easier and non-convoluted if we just get rid of abstract props and keep only the infoset stuff 21:29:21 [mnot] ack dhull 21:30:26 [uyalcina] looks good to me, 21:30:56 [pauld] s/lc33/lc36/ 21:31:06 [mnot] zakim, who is here? 21:31:06 [Zakim] On the phone I see mpeel (muted), MSEder (muted), Rebecca_Bergersen, Nilo_Mitra, Dave_Hull, anish, Jonathan_Marsh, Prasad_Yendluri, Ugo_Corda, Tom_Rutt, +46.7.30.2.aabb (muted), 21:31:09 [Zakim] ... Arun (muted), Mark_Peel, [IBM], Marc, ALewis (muted), DOrchard, Plh (muted), pauld, +1.408.748.aacc, TonyR (muted), Umit_Yalcinalp, +1.781.883.aaee, Bob_Freund, JeffM, MarkN 21:31:14 [Zakim] On IRC I see bjarlestam, mlpeel, bob, dims, uyalcina, alewis, Paco, yinleng, Arun, marc, prasad, abbie, TonyR, dhull, anish, RebeccaB, MSEder, Nilo, Marsh, RRSAgent, Zakim, mnot, 21:31:16 [Zakim] ... plh, pauld 21:31:20 [pauld] RESOLUTION: closed LC36 with Jonathan's proposal 21:32:24 [MSEder] zakim, unmute me 21:32:24 [Zakim] MSEder should no longer be muted 21:34:21 [MSEder] zakim, mute me 21:34:21 [Zakim] MSEder should now be muted 21:34:21 [pauld] Topic: lc33 21:34:31 [Zakim] -[IBM] 21:34:58 [pauld] s/Topic: lc33/Topic: lc34/ 21:36:14 [TonyR] zakim, unmute me 21:36:14 [Zakim] TonyR should no longer be muted 21:36:58 [pauld] marsh: outlines proposal for duplicate headers at the ultimate recipient 21:37:20 [pauld] tonyr: suggests dropping term 'ultimate recipient' 21:37:37 [pauld] marsh: we still need to target a particular node 21:38:07 [pauld] anish: how do we determin if it's targetted at a particular node (as opposed to a role?) 21:38:18 [pauld] marc: that's the joy of soap! 21:39:14 [pauld] marc: you can't have more than one of these targetted at a node, which is stricter and not deterministic from looking at the message 21:39:48 [Zakim] -Ugo_Corda 21:39:57 [pauld] anish: can have multiple 'To's if they are targetted at differnet nodes? 21:40:07 [pauld] mnot: action item is regarding faults 21:40:39 [pauld] marc: glen had a use-case for this 21:41:33 [pauld] anish: recipient node has to decide which roles it is playing 21:42:06 [pauld] umit: unconvinced why we ended up with node rather than role. why did we do this? 21:42:14 [pauld] marsh: glen and marc convinced us! 21:42:58 [pauld] marc: suggests only having one To header (at most) but doesn't satisfy Glen's use-case 21:43:39 [pauld] anish: questions reason for using node rather than role 21:44:55 [pauld] mnot: role is in the infoset [node isn't] 21:45:18 [dhull] q+ 21:45:37 [pauld] marc: raises case where a node is playing two roles with two To's 21:46:48 [mnot] ack dhull 21:47:27 [pauld] dhull: thinks this is put out of scope by our spec; we should just be talking about the ultimate receiver 21:48:01 [pauld] marc: ultimate receiver [node] always plays at least two roles 21:48:52 [pauld] umit: likes proposed solution with role rather than node 21:50:05 [pauld] marsh: would welcome amendment, but wants to be consistant with soap 21:50:24 [dhull] q+ 21:50:34 [pauld] anish: discussion of Glen's (WS-Routing) use-case 21:50:55 [mnot] ack dhull 21:51:36 [pauld] dhull: thinks wording regarding targetted and ultimate receiver is correct 21:51:52 [mnot] 21:52:17 [pauld] .. wants clarification regarding multiple faults and errors 21:54:51 [pauld] .. fault coming back should clarify which role being played by a node caused the error 21:55:07 [pauld] marc: soap 1.2 has a role element 21:55:37 [Zakim] -ALewis 21:55:43 [pauld] tonyr: thinks it's 'actor' 21:56:12 [anish] this is both a 'node' element and an 'role' element 21:56:19 [anish] s/this is/there is/ 21:57:04 [anish] 21:57:14 [anish] 21:57:32 [pauld] marc: thinks we've covered intemediary processing 21:59:15 [pauld] vikas: ignoring that an intemediary may exist is the safest way of working on the Internet 22:00:49 [Zakim] -Arun 22:00:51 [Zakim] -anish 22:00:52 [Zakim] -Marc 22:00:53 [Zakim] -Rebecca_Bergersen 22:00:55 [Zakim] -Plh 22:00:56 [Zakim] -MarkN 22:00:57 [Zakim] - +1.408.748.aacc 22:00:58 [pauld] ACTION: marc to respond to Jonathan's proposal for lc34 22:00:58 [Zakim] -Mark_Peel 22:00:59 [Zakim] -MSEder 22:00:59 [bob] bob has left #ws-addr 22:01:00 [Zakim] -Nilo_Mitra 22:01:01 [Zakim] - +1.781.883.aaee 22:01:03 [Zakim] -Tom_Rutt 22:01:05 [Zakim] -Bob_Freund 22:01:06 [Zakim] -Jonathan_Marsh 22:01:08 [Zakim] - +46.7.30.2.aabb 22:01:09 [TonyR] TonyR has left #ws-addr 22:01:10 [Zakim] -TonyR 22:01:12 [Zakim] -mpeel 22:01:14 [Zakim] -pauld 22:01:15 [mnot] rrsagent, make logs public 22:01:16 [Zakim] -Prasad_Yendluri 22:01:18 [Zakim] -JeffM 22:01:20 [Zakim] -Dave_Hull 22:01:21 [mnot] rrsagent, please generate minutes 22:01:21 [RRSAgent] I have made the request to generate mnot 22:01:32 [Zakim] -Umit_Yalcinalp 22:01:33 [Zakim] -DOrchard 22:01:34 [Zakim] WS_AddrWG()4:00PM has ended 22:01:35 [Zakim] Attendees were +44.196.286.aaaa, MarkN, MSEder, Rebecca_Bergersen, Bob_Freund, Nilo_Mitra, Dave_Hull, anish, Jonathan_Marsh, swinkler, Prasad_Yendluri, Ugo_Corda, Tom_Rutt, 22:01:39 [Zakim] ... Abbie_Barbir, +46.7.30.2.aabb, Mark_Peel, [IBM], Marc, Mark_Little, ALewis, DOrchard, Plh, pauld, +1.408.748.aacc, TonyR, +1.781.861.aadd, yinleng, Umit_Yalcinalp, 22:01:41 [Zakim] ... +1.781.883.aaee, Arun, dims, JeffM, mpeel 22:02:56 [pauld] s/mnot: dhull / 22:03:03 [pauld] s/mnot: dhull /dhull: / 22:26:10 [yinleng] yinleng has left #ws-addr 22:39:58 [MSEder] MSEder has left #ws-addr
http://www.w3.org/2005/05/02-ws-addr-irc
CC-MAIN-2016-18
refinedweb
3,582
54.9
I have been trying to deploy some small android apps on my vs2012 to Nexus 5(kitkat) emulator (Xamarin Android Player). And also the "hello world" first android application even with out editing anything. But it can't work for me. VS2012 says the Deploy is succeeded but when I try to open it on the emulator, it says " Unfortunately, Helloworld has stopped.". I have searched a lot to see any problem on it. but I haven't found helpful yet. I am a beginner for such development. Please help me why is it like this. Answers Have you tried to debug the issue? Are there any exceptions? Yes, I have tried to debug it. No errors found. No exceptions. For the sake of testing, I have tried to debug and deploy the "Hello world" template with out editing anything.But it is all the same. Hi @MarewAtnafu I'm posting a code snippet which is actually help you to find whats wrong with an app? Following methods will be in your first running activityof an application Now, try to execute your application. If its crashed then please go to file manager and find Exceptiondirectory and find Fatal.txtthere you can find app crashed reason. Let me know once you try this. Thanks!! RIYAZ Thanks a lot @rzee7. I have tried the code snippet many times. But it doesn't work. No folder is created! I have edited the "GetLocalPath" to "GribLocalPath" in LogUnhandledException method of the code snippet. I had also provided write and read permissions for the app but no working yet. Hello @MarewAtnafu Where you have written this code? I can help you remotely if you say? Thanks RIYAZ Hello @rzee7 Doha, Qatar. I am using the trial Xamarin platform. May this be the problem? I'd suggest you to use once Genymotion if an issue still there please upload your Hello AppDemo and we'll sort out Cheers!! RIYAZ Thanks @rzee7, I have tried in Genymotion. But it is the same. No folders created. Here is Main activity. cs file. If you need extra information I can provide you. using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using System.IO; using System.Threading.Tasks; using System.Globalization; namespace App4 { [Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; } Hi MarewAtnafu, Have you find a solution to your problem? I have the same problem... I did the "PhoneWord" app from the "Getting Started" tutorial of Xamarin without changing anything and when I try to start the app from vs2015 using the emulator, I got the error "unfortunately, PhoneWord has stopped"... Does someone know how to solve this problem? Thanks a lot! Sorry guys, I solved my problem by myself switching "Compile using Android version:" on the good option ... Unfortunately, [App Name] has stopped. Please help me out for resolving above error for solving this issue in Visual studio Inside the solution go to Properties--->Android options--->packaging--->here uncheck the "Use fast deployment". it will work Hi, If you are deploying to the emulator, try to check the X86 checkbox, Project-> 'Application Name' Properties ->Android Options->Advanced->Supported Architectures is armeabi-v7a. I am running the Hyper-V Android Emulator but i guess it is the same with the Android Player. Do it both for the Debug and Release version. Hope this helps. I have the same problem. I have set a break point at the very first line of code, but I do not even get to that line. The suggestions above did not help me. Is there a log file or something that I can look for? @ClausBehn first of all your app not loading(as this thread is) how your break point will fire. If your app not stopping and loading properly than you are in the wrong thread. for that made another post or you can go through existing posts. How did you fix it? Mine still wont work... I have followed the instructions for the Introductory Phoneword app. If I try Debug Any CPU Android_Accelerated_x86 (Android 6.0 - API 23) I get "Unfortunately Phoneword has stopped". I set a breakpoint at line 14 base.OnCreate(bundle) but it doesn't reach it. Output is InspectorDebugSession(6): StateChange: Start -> EntryPointBreakpointRegistered InspectorDebugSession(6): Constructed Android application is debugging. InspectorDebugSession(6): HandleTargetEvent: TargetExited InspectorDebugSession(6): Disposed If I try to compile with Android_ARMv7a (Android 6.0 - API23) I get the message about Running an x86 based AVD is 10x faster, then once I go beyond that, the Android word appears on the emulator and just stays there. Then the output window of visual studio says: InspectorDebugSession(5): StateChange: Start -> EntryPointBreakpointRegistered InspectorDebugSession(5): Constructed Android application is debugging. Couldn't connect to logcat, GetProcessId returned: 0 InspectorDebugSession(5): HandleTargetEvent: TargetExited InspectorDebugSession(5): Disposed The only thing that is maybe non-standard is that I installed the Android SDK on an external drive which is currently plugged in. That doesn't seem to be generating an error. Any help would be appreciated.
https://forums.xamarin.com/discussion/52103/unfortunately-app-name-has-stopped
CC-MAIN-2019-47
refinedweb
853
60.92
Just a idea. Widgets/controls for Pythonista I am currently trying to make a calendar for a hotel booking system. I have started out by just focusing on a creating a single cell that represents a day. I did this with a class that inherits from ui.View. In that cell, I create multiple subviews for indicators in the top right of the cell as well as indicators in the bottom of the cell cell. Then writing methods in the class to manipulate the contents of the various cell/view. Also some animations within the cell also. The goal being that another class would create as many of these objects as required and position them appropriately to form something that looks like a calendar. Long intro to my main point... Writing this small custom class, it occurs to me, how hard would be for @omz to be able to load a custom class that inherits ui.View into the ui builder, and at minimum render it and provide graphical positioning. One step further could be to offer a property page if the class had decorated properties for example. I am sure it could go further. But even the simplest implementation could lead to some nice controls/widgets being created for Pythonista in my ui.View. I hope this is useful feedback. you can insert custom views in the ui builder. you can position it, and set the basic View type properties, but it is just rendered as a box. Insert a normal view and set the Custom View Class in the attributes panel. @JonB, I just see where you can do it. I feel a little embarrassed, I didn't see that before. But I think the documentation is really lacking. I Know documentation is very difficult to control and keep updated. Many years ago, Xerox charged us around 10,000usd just for our help file per language. Nothing about the content, was just the translation. But it seems to me we should have some web tools to report these things To omz. Another Example, if you look up ui.Button in the help, there are no params, but title is a param to that method. So nothing against omz, would like to report in a way that is helpful. I wonder how many people really know what you have pointed out here. I think it's really powerful. Thanks again. I missed that for a long time too. I was thinking of suggesting that omz place the source docs on github so that people can contribute -- various folks have found minor documentation shortcomings which could be easily fixed by the community (obviously the pull requests would ultimately get approved by omz). Actually, all the docs do exist in the app -- in both html and sphinx sources. (you can find the pylib folder from os.file. I then created a hardlink to the folder to make it easier to get there from stash). Though I think the sphinx configuration files are needed to compile to html (haven't tried yet). omz place the source docs on github so that people can contribute If omz is willing to do so, this would be a great idea. Wiki is perhaps a better paradigm that raw GitHub for collaborative editing of web docs but either way would be a nice improvement. @ccc I think sounds great. Especially Wiki. Those pages end up being very rich with info, examples etc. as well as taking some of the burden out of it from omz. I still can't believe such a great and complete product for a tiny price. @JonB, I don't know those tools you speak of. I am guessing like in the tools in C that would rip out all your function prototypes for documentation purposes. This is one thing untyped languages don't help with I guess. I have briefly looked at the testing modules. So, I am guessing that funcs/classes that contained some testing code, could be run and types expected could be examined and collected during the running of those test suites to form some semi automatic documentation for the prototypes. Whilst *args and **kwargs are really nice, not so nice to document I guess. Again, I am not sure. Maybe there are some wiz bang tools out there. Just my thoughts really An open-to-contributions documentation sounds like a great idea, but a GitHub repo would probably be better than a wiki, because: - I'm not aware of any wiki software that uses reStructured Text as its markup format, which AFAIK is what the Python documentation uses. DokuWiki uses Markdown stored in plain text files (instead of a database like e. g. MediaWiki does), that could be an acceptable solution. - Wikis quickly become inconsistent, because pages are edited independently and changes are usually not approved in any way. An advantage of GitHub and PRs is that related changes can be done in a single PR, and they can be discussed before being merged by omz. - Wikis are a popular target of bored kids (or possibly also non-kids). This might be less of an issue in this case though, because the docs wiki would not have much exposure. @JonB, it took me a bit of time to unpack your statement: you can find the pylib folder from os.file. I finally did find the location of embedded docs (at least the HTML versions). Is there a more straightforward way to find the Pythonista app path? import os app_path = os.path.abspath(os.path.join(os.__file__, '../..')) @omz: If you were to make the Pythonista (and perhaps Editorial) docs collaborative, I would gladly help out. I don't know how hard it would be for you to do this, though. If it isn't possible or you don't want to enable collaboration on the official docs, I would like to ask you permission to make a clearly unofficial, expanded version based off of the official stuff. @ccc: If @omz does give his consent, maybe we could include said unofficial docs on the Pythonista Tools website? It is already one of the (I think...) most popular unofficial Pythonista resources, so, at least in my mind, it would make sense to host it there. Speaking of which, I completely agree with @dgelessus on the repo vs. wiki debate. I see no reason to be redundant and reiterate his points here: they are already well-formulated. :)
https://forum.omz-software.com/topic/1849/just-a-idea-widgets-controls-for-pythonista
CC-MAIN-2017-47
refinedweb
1,077
73.07
This is a continuation of a previous article that described the DARL language and its basis in Fuzzy Logic. In that article, I talked about the problem of "blackbox" models in Machine Learning, and how the DARL technology was initially developed to behave as a model you can machine learn to, that you can also understand. Such algorithms are sometimes labelled "whitebox" for obvious reasons. The DARL.AI website now gives you API access to machine learning using a supervised learning, fuzzy logic rule induction algorithm. This interface is free. The REST interface is described here. Machine learning can be processor intensive, depending on the amount of training data. To spread out the load, the processing is performed by an Azure function responding to a queue and returning results via email. I've constructed a very simple project that will access this web service and fire off three benchmark machine learning examples. Machine learning falls into several types., like an equation, exists. Machine learning algorithms are used when nothing else will work. This is typically when the problem to be solved is noisy, poorly specified or ephemeral. Machine learning is seldom absolutely correct. In all real world situations, you will have to deal with some inaccuracy. This might be misclassification or some prediction error. It is also entirely possible that your inputs are not related in any discernable way to your outputs, so the model performance will be poor. To use the DARL Machine learning service, you need several things: The project here on GitHub contains the example code for accessing the web service. There are three examples provided, each consisting of a data file in XML and a darl skeleton, embedded in the executable. class Program { static string destEmail = "support@darl.ai"; //put your email address here! static void Main(string[] args) { DarlML("yingyang").Wait(); DarlML("iris").Wait(); DarlML("cleveheart").Wait(); } static async Task DarlML(string examplename) { var reader = new StreamReader(Assembly.GetExecutingAssembly(). GetManifestResourceStream($"DarlMLRestExample.{examplename}.darl")); var source = reader.ReadToEnd(); reader = new StreamReader(Assembly.GetExecutingAssembly(). GetManifestResourceStream($"DarlMLRestExample.{examplename}.xml")); var data = reader.ReadToEnd(); var spec = new DarlMLData { code = source, data = data, sets = 5, jobName = examplename};//use your own choice of training percent (1-100) //and sets, (3,5,7,9) var valueString = JsonConvert.SerializeObject(spec); var client = new HttpClient(); var response = await client.PostAsync("", new StringContent(valueString, Encoding.UTF8, "application/json")); //check for errors here... } } Don't forget to replace the email address with your own! The class encapsulating the ML specification looks like this: public class DarlMLData { /// <summary> /// Your DARL code /// </summary> /// <remarks>Should contain a single ruleset decorated with "supervised" /// containing only I/O. Outside of the ruleset the "pattern" parameter should be specified, /// along with mapinputs,mapoutputs and wires. MAP I/O should have paths.</remarks> public string code { get; set; } /// <summary> /// The training data /// </summary> /// <remarks>this can be in XML or Json. If the former XPath should be used /// to specify paths in the ruleset. If the latter, JsonPath</remarks> public string data { get; set; } /// <summary> /// Number of sets to use for numeric variables. Only values 3,5,7 and 9 can be specified. /// </summary> [Range(3,9)] public int sets { get; set; } /// <summary> /// The percent to train on /// </summary> /// <remarks>Must be between 1 and 100</remarks> [Range(1, 100)] public int percentTrain { get; set; } /// <summary> /// </summary> /// <remarks>Because Machine learning can be CPU intensive training is performed /// via a queue in a secondary process. /// Results and the mined DARL will be emailed to this address. /// </remarks> [DataType(DataType.EmailAddress)] public string email { get; set; } /// <summary> /// A name to identify the job in the returned email /// </summary> public string jobName { get; set; } } The three data sets provided demonstrate classification of different kinds of data. The system can handle numeric outputs too. To illustrate how to construct a darl skeleton, we'll look at the data of the Iris example. <?xml version = "1.0"?> <irisdata> <Iris> <sepal_length>5.10</sepal_length> <sepal_width>3.50</sepal_width> <petal_length>1.40</petal_length> <petal_width>0.20</petal_width> <class>Iris-setosa</class> </Iris> This is one pattern out of 150. The Iris DARL skeleton looks like this: pattern "//Iris"; ruleset iris supervised { input numeric petal_length; input numeric sepal_length; input numeric petal_width; input numeric sepal_width; output categorical class; }; The section pattern "//Iris"; defines the XPath (since the data is XML) to find all the patterns in the data. pattern "//Iris"; Within the ruleset, which is annotated with supervised, the inputs and output are specified. supervised Finally, mapinput and mapoutput definitions are tied to the XPath to find the data item relative to the pattern. This happens in this case to just be the name of the data item in the XML. mapinput mapoutput The Wire elements link the MapInput and Mapoutput elements to the ruleset. Wire MapInput Mapoutput When you run the example, you will receive 3 emails back. The Iris email will look like this, assuming you've kept the same parameters: Job id: 7f29976a-b094-426d-b8f0-763f4abf1bb5 Training on 100% Train performance 96.0526315789474(%/RMS Error) Unknown responses 0% Thanks for using DARL Machine Learning. DARL.AI Support. If you would like to unsubscribe and stop receiving these emails, click here and the included DARL code will look like this: pattern "//Iris"; ruleset iris supervised { // Generated by DARL rule induction on 6/15/2018 10:31:34 AM. // Train correct: 96.05% on 152 patterns. // Percentage of unknown responses over all patterns: 0.00 input numeric petal_length { {very_small, -Infinity,1,1.6},{small, 1,1.6,4.4}, {medium, 1.6,4.4,5.1},{large, 4.4,5.1,6.9},{very_large, 5.1,6.9,Infinity}}; input numeric petal_width { {very_small, -Infinity,0.1,0.3},{small, 0.1,0.3,1.3}, {medium, 0.3,1.3,1.8},{large, 1.3,1.8,2.5},{very_large, 1.8,2.5,Infinity}}; input numeric sepal_length { {very_small, -Infinity,4.3,5.1},{small, 4.3,5.1,5.8}, {medium, 5.1,5.8,6.4},{large, 5.8,6.4,7.9},{very_large, 6.4,7.9,Infinity}}; input numeric sepal_width { {very_small, -Infinity,2,2.8},{small, 2,2.8,3}, {medium, 2.8,3,3.3},{large, 3,3.3,4.4},{very_large, 3.3,4.4,Infinity}}; output categorical class {"Iris-setosa","Iris-versicolor","Iris-virginica"}; if petal_length is very_small then class will be "Iris-setosa" confidence 1; // examples: 4 if petal_length is small then class will be "Iris-setosa" confidence 1; // examples: 39 if petal_length is medium then class will be "Iris-versicolor" confidence 0.977272727272727; // examples: 44 if petal_length is large and petal_width is medium and sepal_length is medium then class will be "Iris-virginica" confidence 1; // examples: 1 if petal_length is large and petal_width is medium and sepal_length is large then class will be "Iris-versicolor" confidence 0.75; // examples: 4 if petal_length is large and petal_width is large then class will be "Iris-virginica" confidence 0.888888888888889; // examples: 27 if petal_length is large and petal_width is very_large then class will be "Iris-virginica" confidence 1; // examples: 13 if petal_length is very_large then class will be "Iris-virginica" confidence 1; // examples: 9 }; Note that the inputs and outputs are now annotated with fuzzy sets and categories. These are discovered in the data and inserted automatically. The Ruleset now contains a set of DARL rules that categorize Irises. Extra information about the rule inference process and the degree of support for each rule are included as comments. The DARL rulesets you get back can be used with the online inference REST API as specified in the previous article, so that's how you re-use Learned rule sets. Machine learning is a very big subject. I can't hope to tell you everything here. Please look at the DARL Machine learning help for more advice. Please report any bugs, especially exceptions, through the DARL support button on the DARL.AI pages. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
https://www.codeproject.com/Articles/1248572/DARL-and-Whitebox-Machine-Learning
CC-MAIN-2020-50
refinedweb
1,339
56.86
How do I get itemDoubleClick event in spark DataGrid ???Mitul Golakiya Mar 6, 2012 11:15 PM Hello Everyone, Recently I am working with Spark DataGrid. Before I was using AdvancedDataGrid. In that I was capturing itemDoubleClick event. But I am not able to find such a event in SparkdataGrid. So I want to capture double click event on single row of DataGrid. Some people told that, I have to use my custom ItemRenderer to do that. But is there any way to capture itemDoubleClick event in Spark DataGrid without creating custom ItemRenderer ??? 1. Re: How do I get itemDoubleClick event in spark DataGrid ???tinylion_uk Mar 6, 2012 11:19 PM (in response to Mitul Golakiya) I think, just user gridDoubleClick then check which row and column in the handler 2. Re: How do I get itemDoubleClick event in spark DataGrid ???Mitul Golakiya Mar 7, 2012 1:49 AM (in response to tinylion_uk) I had also tried it... But the problem is, when you continously click on two rows of DataGrid, it also detect it as double click, even if those two rows are different.... It detects double click on whole grid... 3. Re: How do I get itemDoubleClick event in spark DataGrid ???Carol L. Frampton Mar 8, 2012 6:43 AM (in response to Mitul Golakiya) You are correct. I looked a the code and the comment says it dispatches a double click if the 2nd click is within the DOUBLE_CLICK_TIME even if the first click was on another cell. This code figures out if the double-click is a true double-click. <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="" xmlns: <fx:Script> <![CDATA[ import spark.events.GridEvent; private var lastColumnIndex:int = -1; private var lastRowIndex:int = -1; // set this to change the double click time //mx_internal::event.grid.DOUBLE_CLICK_TIME = 480; // ms protected function dataGrid_gridClickHandler(event:GridEvent):void { trace("click on this cell", event.rowIndex, event.columnIndex); lastRowIndex = event.rowIndex; lastColumnIndex = event.columnIndex; } protected function dataGrid_gridDoubleClickHandler(event:GridEvent):void { if (event.rowIndex == lastRowIndex && event.columnIndex == lastColumnIndex) trace("a real double click on this cell", event.rowIndex, event.columnIndex); else trace("this is a gridClick on another cell", event.rowIndex, event.columnIndex); lastRowIndex = event.rowIndex; lastColumnIndex = event.columnIndex; } ]]> </fx:Script> <s:DataGrid <s:ArrayCollection> <s:DataItem <s:DataItem <s:DataItem <s:DataItem <s:DataItem <s:DataItem <s:DataItem <s:DataItem <s:DataItem <s:DataItem </s:ArrayCollection> </s:DataGrid> </s:Application> 4. Re: How do I get itemDoubleClick event in spark DataGrid ???Tim John Feb 3, 2014 5:18 AM (in response to Carol L. Frampton) DataGrid now has a property called doubleClickMode (since 4.5 according to the comments). Set that to 'cell' or 'row' to ensure correct behaviour. Oddly, when this value is set as an MXML property, it causes an RTE, as the property doesn't seem to be using the invalidation pattern, but doing it this way will work: <s:DataGrid
https://forums.adobe.com/thread/971940
CC-MAIN-2015-11
refinedweb
488
68.26
Tips and tricks for scalable CI/CD flow Alex Barashkov ・4 min read When you plan a project, you don’t always know how big it will be by the end. It’s crucial, therefore, to follow guidelines that make the development process as smooth as possible. One especially useful tool for this is a Continuous Integration/Delivery flow, or CI/CD flow. At the beginning of a typical development process, before the project is ready for publication, your CI flow looks something like this: During the development phase, more steps are added to the process until it looks something like the image below. However, you may see many more steps than this in some projects. Original image. In this article, I will demonstrate a typical CI/CD flow and provide tips to help you scale this up for bigger projects. Note that these recommendations are made on the assumption that you have developed your infrastructure setup using Docker and orchestration tools, such as Kubernetes. Define Your VCS Flow All modern CI tools rely on version control systems, so to maintain your CI flow at a high level you should have a proper version control flow in place. I recommend Git Flow or Github Flow if you’re looking for ideas. Pick one and adapt your pipeline according to your needs. Recommendations: - Run tests on each push in any branch. This helps your developers find bugs faster and speed up the code review process. - Define branches that you will use to trigger Docker image build processes and deploy them as shown in the image above. - If your releases have a complicated manual approval process, use tags to trigger production releases. Specify Your Environments Once you have a git flow in place, integrate it with your builds’ logic and adapt it for the number of environments you have. Initially, you will likely deploy everything to production after your local environment testing. Later on, you may decide to do development, UAT, and production. Example: We often use a master branch to initiate deployment to the development environment. Then we merge the master branch into the release branch. This triggers a deployment to UAT, where we allow a small number of users to test the new version. If everything works correctly and the QA team confirms the release, we create a tag from the release branch, which initiates deployment to production. Set Up Notifications You should keep track of all CI flow processes via the notification channel you prefer. We use Slack for our projects. - Create a system-notification channel and enable it to send notifications about all CI and infrastructure processes. - Set up notifications about success or failure statuses and to alert you when the build starts. Keep Docker Image Simple It is best practice not to pass to Docker image env variables. All env variables should be passed through the Docker run command or on your orchestration tool level (for example, Kubernetes). This will also help keep your CI configuration files simple. Unify Your Pipeline Companies today increasingly use microservices architecture; a unified pipeline helps you benefit from this by scaling faster to deployment and configuring your CI in new microservices. In Drone CI or Travis CI, there are plenty of CI environment variables you could use during your pipeline steps (find them at Travis CI env variables and Drone CI env variables). Here are a few examples of CI env variables in action: To tag a Docker image, you can use a concatenation of a build branch and build number. As a result, you will have something like “master-6.” Alternatively, you can use your git tag version. tags: "${DRONE_COMMIT_BRANCH}-${DRONE_BUILD_NUMBER}" Use a repository name for deployments in your orchestration tools. Example of Drone CI deployment to Kubernetes cluster with env variables. deploy: image: peloton/drone-k8s-deployment deployment_names: "${DRONE_REPO_NAME}" container_names: "${DRONE_REPO_NAME}" namespaces: microservices docker_image: "62673275295.dkr.ecr.eu-west-1.amazonaws.com/${DRONE_REPO_NAME}:${DRONE_COMMIT_BRANCH}-${DRONE_BUILD_NUMBER}" date_label: deployment.drone.io/date-deployed secrets: [kubernetes_url, kubernetes_token] Define Docker Image Names Convention You should define a strategy for naming Docker images based on the specifics and importance of your environment. For example, in development and UAT environments where you don’t need to have a rollback functionality, you can use branch names as a tag so that all new builds override the previous image. For production, it’s better to tag images with the version number of the release (v1.0.0), which makes your registry more structured and readable by reducing its size. Use Builder Pattern If you can compile and build something on the CI level, it can be helpful to do this as an extra step before putting it in the final image. Take a look at this video to get a better understanding. DB Migrations as a Separate Step Do not do your migration as a part of your Dockerfile; instead, do it in a separate step. Extra commands, such as compilation of assets or migrations, should be run as separate steps, not executed at Docker start. You should also try to get your Docker images up and running in the shortest amount of time possible. Avoid Private Libraries and Submodules Any extra dependencies, such as private npm modules or submodules, can cause problems for you during the setup process of your CI configuration. For example, if you have a submodule and by default your CI only has access to your repositories through http and an authorization token, your configuration for the local machine through git will not work. You will need to override your submodule and not all CI tools provide that feature. Drone CI Submodule Override Example You will face similar issues if you use private npm modules, because you will need passkeys or already downloaded modules inside the Docker Image. Summary When you configure a CI for a new project, spend some time thinking about and defining name conventions, potential methods of growing and unification of your build steps. This helps you to deploy new services faster, use those practices as a groundwork for new projects and onboard employees in the pipeline process faster. Dev.to Review #9: Top 7 Of The Week, Discussed Two devs get together to discuss the week's Top 7 posts on dev.to How can it be Continuous Integration if it uses branches? the DB migration thing should be written on the sky :P why would branches and CI be mutually exclusive? Branches might be the most important part when developing a system with multiple developers. CI means Continuous (keyword here) Integration it means that every change made to the code is integrated the moment it is committed therefore branching cannot be CI at most it can be Very Often Integration but not CI. davefarley.net/?p=247 This guy explains it way better than me. Did you read all the comments in reply to that blog post? Branching does not prevent CI. Failing to integrate changes regularly prevents CI. I think those comments are wrong and didn't got the idea. Continuous integration is continuous not often, continuous. That means that every change, no matter how little, is integrated immediately. Branches on the other hand only integrate when, in best case, the developer does rebase often(and is still a half integration cuz you are doing things on your bubble without active feedback) or in worst case, when the branch is merged therefore the integration is not continuous.
https://dev.to/alex_barashkov/tips-and-tricks-for-scalable-cicd-flow--49b7
CC-MAIN-2019-35
refinedweb
1,240
52.7
0.6.2-release From OpenSimulator r8067 | melanie | 2009-01-17 11:35:40 -0700 (Sat, 17 Jan 2009) | 3 lines Change list type to compare length instead of references. Fixes Mantis #3002 r8066 | justincc | 2009-01-16 14:56:13 -0700 (Fri, 16 Jan 2009) | 4 lines - Rig up enough infrastructure to actually perform a successful 'standalone' teleport unit test with checks that the scene presence disappeared from sceneA and appeared in sceneB - However, I'm not convinced that the actual process in the test completely reflects reality, and a lot of stuff had to be rigged up (which should get resolved over time) r8065 | justincc | 2009-01-16 11:31:07 -0700 (Fri, 16 Jan 2009) | 2 lines - minor: Future archiver test stub r8064 | mw | 2009-01-16 10:56:44 -0700 (Fri, 16 Jan 2009) | 2 lines Added support so that during the loading of a xml link list, it checks if a linked hypergrid region's real location is within 4096,4096 map spaces of its "local" location. If it is outside of that range ( so it wouldn't be possible to teleport to it) then it ignores it and doesn't create a link. See the hypergrid wiki page for more details. r8063 | mw | 2009-01-16 05:52:05 -0700 (Fri, 16 Jan 2009) | 5 lines Added some basic relocation mapping support for when loading hypergrid links from a xml file. Console Command: link-mapping <StartXloc> <StartYloc>. This results in only the last two digits of any of the locations defined in the xml file being used, and those 0-99 values being added to the StartXloc and StartYloc figures. For more infomation, see the email on the mailing list and the soon to be added instructions on the wiki's hypergrid page. Also made the Secion Names in xml file case insensitive. r8062 | chi11ken | 2009-01-15 21:42:24 -0700 (Thu, 15 Jan 2009) | 1 line Minor formatting cleanup, add copyright header. r8061 | chi11ken | 2009-01-15 21:23:10 -0700 (Thu, 15 Jan 2009) | 1 line Update svn properties. r8060 | diva | 2009-01-15 16:37:49 -0700 (Thu, 15 Jan 2009) | 3 lines Eased the locking times of ScenePresences. No locks were removed, just the locking periods changed. - Added an additional lock in GetScenePresences() - Changed ForEachClient to use GetScenePresences() instead of the main ScenePresences dictionary, so that there is no need to lock. r8059 | justincc | 2009-01-15 14:37:22 -0700 (Thu, 15 Jan 2009) | 2 lines - Delete OpenSim/Framework/OpenJpeg for now, with Teravus' permission ;) r8058 | justincc | 2009-01-15 14:29:24 -0700 (Thu, 15 Jan 2009) | 2 lines - add file I just missed out, nggggff r8057 | justincc | 2009-01-15 14:27:55 -0700 (Thu, 15 Jan 2009) | 3 lines - Add new unit test for simple teleport in a standalone. - Does not yet check results. r8056 | mw | 2009-01-15 10:09:51 -0700 (Thu, 15 Jan 2009) | 1 line Small bit of refactoring related to the hypergrid link loading from xml files. r8055 | mw | 2009-01-15 08:31:40 -0700 (Thu, 15 Jan 2009) | 1 line Added support for a "excludeList" as part of the hypergrid xml link file loading. So that certain links in the file will be ignored. See the wiki's hypergrid page for details (in about a hour). r8054 | mw | 2009-01-15 07:37:04 -0700 (Thu, 15 Jan 2009) | 4 lines Added initial support for reading hypergrid links from a xml config file. Although its currently still activated by using console command: link-region <URI of xml file> , the uri should be able to be a local file path or a http uri. I'm adding details of the format of the xml file to the wiki's hypergrid page. TODO: Add a initial startup option for setting the uri and making it autoload it. Add support for scanning the xml file to check that its own region(s) aren't in the list, and if they are, ignoring them. This would allow setting up "virtual link/grid lists" on webservers, that people can add their own regions to and also point those regions to those same lists, so they load the other region's data. Add support for automapping of those region/link lists. r8053 | dahlia | 2009-01-14 19:17:30 -0700 (Wed, 14 Jan 2009) | 1 line Added a taint to the sculpt texture callback in an attempt to mitigate Mantis #2908. Thanks Teravus for the suggestions :) r8052 | justincc | 2009-01-14 13:40:14 -0700 (Wed, 14 Jan 2009) | 5 lines - Move the timed_out change to earlier on in the async handler - There appears to be a bug on mono 1.9.1 (and maybe later), where sometimes the async wait will be signalled even though that async callback has not executed - This change may make it slightly better but it's difficult to tell (it definitely still occurs) - Also this patch closes the wait handle explicitly, as recommended in the MSDN docs. This doesn't have any impact on the bug though r8051 | justincc | 2009-01-14 12:53:15 -0700 (Wed, 14 Jan 2009) | 3 lines - Adjust log messages so that we don't get a CONNECTION BEGIN for notifications that won't actually lead to a client connection (because they are from a neighbouring teleport target that needs to trigger a child seeds adjustment on a child agent that has been kept around) r8050 | sdague | 2009-01-14 12:34:14 -0700 (Wed, 14 Jan 2009) | 3 lines - Added MySQL Grid unit tests From: Arthur Rodrigo S Valadares <arthursv@linux.vnet.ibm.com> r8049 | justincc | 2009-01-14 11:48:57 -0700 (Wed, 14 Jan 2009) | 3 lines - Remove absolute position and authentication handler addition for incoming 'new user notifications' that have existing scene presences - The position will be reset if the connection turns out to be a root one, and since the client is already authenticated another authentication will not occur anyway r8048 | justincc | 2009-01-14 11:46:33 -0700 (Wed, 14 Jan 2009) | 2 lines - minor: Change around more debugging messages r8047 | justincc | 2009-01-14 10:34:04 -0700 (Wed, 14 Jan 2009) | 2 lines - Do some log tweaking to better see incoming connection success (and failure) r8046 | justincc | 2009-01-14 09:52:12 -0700 (Wed, 14 Jan 2009) | 5 lines - Fix typo which meant that RestComms was never enabled if you explicitly enabled it - In fact, it would only be activated if there was no [Communications] section at all (which would be the case for most people with existing region setups unless they specifically added it in - This fix means that enabling inter-region rest comms is now the default r8044 | justincc | 2009-01-14 07:53:42 -0700 (Wed, 14 Jan 2009) | 4 lines - Apply - This fixes MSSQL for user friends lookups - Thanks StrawberryFride r8043 | joha1 | 2009-01-14 00:16:03 -0700 (Wed, 14 Jan 2009) | 1 line Added a primitive shape function for spheres r8042 | nlin | 2009-01-13 21:59:57 -0700 (Tue, 13 Jan 2009) | 5 lines Improve parsing of joint parameters for NINJA physics (Mantis #2966). Multiple spaces or leading/trailing spaces when specifying the prims to connect should no longer cause problems. r8041 | diva | 2009-01-13 21:18:28 -0700 (Tue, 13 Jan 2009) | 1 line Easy on locking m_scenePresences in RequestTeleportLocation. With the extra locks of SceneGraph ScenePresences introduced in 7982, this was making TPs not close the agent in the departing region due to locking. That locking problem seemed to occur only in Linux/mono -- I suspect a mono bug here. r8040 | melanie | 2009-01-13 16:29:54 -0700 (Tue, 13 Jan 2009) | 3 lines Change fake parcel ids to allow a Z coordinate. Change TP by lure to also transmit and use a Z coordinate. r8039 | teravus | 2009-01-13 16:27:48 -0700 (Tue, 13 Jan 2009) | 2 lines - Add a second logoffuser message with the region secret. - This ensures that the user will be logged off successfully by a properly permissioned user server r8038 | teravus | 2009-01-13 16:25:47 -0700 (Tue, 13 Jan 2009) | 2 lines - Fix a few caps limiter that were causing problems - Added a path for all sessionids to be logged off when a region secret is provided. (helps log-off dead agents). r8037 | teravus | 2009-01-13 15:27:26 -0700 (Tue, 13 Jan 2009) | 3 lines - Fix an invalid seed cap that could be causing issues. - CapsUtil.GetRandomCapsObjectPath(); contains a / and the regionInfo.httpServerURI contains a / so that makes - response.SeedCapability = regionInfo.httpServerURI + CapsUtil.GetCapsSeedPath(capsPath); contain two "//" leading to a seed caps path definition like //CAPS/f7ba4238-ec86-4a2b-b3f6-4d9b56070000/, which is wrong r8036 | sdague | 2009-01-13 12:55:07 -0700 (Tue, 13 Jan 2009) | 3 lines - Extended TextureSenderTests and modified TestClient.cs with new methods From: Arthur Rodrigo S Valadares <arthursv@linux.vnet.ibm.com> r8035 | justincc | 2009-01-13 11:35:20 -0700 (Tue, 13 Jan 2009) | 2 lines - minor: remove some mono compiler warnings r8034 | justincc | 2009-01-13 11:23:37 -0700 (Tue, 13 Jan 2009) | 2 lines - minor; Very minor non-functional tidy ups r8033 | justincc | 2009-01-13 10:16:56 -0700 (Tue, 13 Jan 2009) | 2 lines - Add copyright notice to NHibernate.UserFriend r8032 | justincc | 2009-01-13 10:13:49 -0700 (Tue, 13 Jan 2009) | 4 lines - Apply - Puts ordinary getters and setters into NHibernate.UserFriend since previous c# 3.0 get/set failed on MSVC#2005 - Thanks mpallari r8031 | justincc | 2009-01-13 10:04:52 -0700 (Tue, 13 Jan 2009) | 4 lines - Apply - Removes now unnecessary revision 2 and 3 files that should have been removed in an earlier patch - Thanks tlaukkan! r8030 | justincc | 2009-01-13 10:01:57 -0700 (Tue, 13 Jan 2009) | 3 lines - Removing set-time command since it doesn't actually do anything at all - If this was crucial to someone then it should be reinsertable as a module r8029 | justincc | 2009-01-13 09:56:10 -0700 (Tue, 13 Jan 2009) | 2 lines - minor: Add a couple of code comments about enabling httpserver logging r8028 | justincc | 2009-01-13 09:49:01 -0700 (Tue, 13 Jan 2009) | 2 lines - minor: Stop friendship termination crashing the client thread if the friend to be terminated could not be found r8027 | lbsa71 | 2009-01-13 03:06:53 -0700 (Tue, 13 Jan 2009) | 1 line - Added resolving explicit .exe project names. This fixes mantis #2967 r8026 | lbsa71 | 2009-01-13 02:31:27 -0700 (Tue, 13 Jan 2009) | 1 line - Fixed breaking VS2008 build. Added missing Statistics reference r8025 | drscofield | 2009-01-13 01:15:43 -0700 (Tue, 13 Jan 2009) | 13 lines From: Christopher Yeoh <yeohc@au1.ibm.com> The attached patch adds the automatic granting of PERMISSION_CONTROL_CAMERA on request to a script when an avatar is sitting on the object that the script resides in. It also automatically removes PERMISSION_TAKE_CONTROLS and PERMISSION_CONTROL_CAMERA from the scripts when an avatar stands up. It doesn't remove the other automatically granted permissions but this follows LL server behavior. Removing these two permissions avoids some potential race conditions (accidentally taking control after the avatar has stood up) which may be why LL put them in the first place. r8024 | justincc | 2009-01-12 13:42:44 -0700 (Mon, 12 Jan 2009) | 2 lines - Extend current stub packet handler test into a really basic one that checks that a sent in packet ends up on the client queue ready for processing r8023 | ckrinke | 2009-01-12 13:14:39 -0700 (Mon, 12 Jan 2009) | 6 lines Thank you kindly, Tlaukkan (Tommil) for a patch that: Cleaned up schema creation scripts of MySQL to compliant form and created SQLite scripts from them. In future it would be optimal if scripts from different databases could be generated from MySQL scripts to ensure optimal consistency between schemas of different databases. Did not yet review column names. ID columns seem to have variety in naming which can be confusing. r8022 | justincc | 2009-01-12 12:37:56 -0700 (Mon, 12 Jan 2009) | 2 lines - Separate starting a client thread into a separate Start() method (which matches the existing Stop() and Restart() methods) r8021 | homerh | 2009-01-12 12:28:40 -0700 (Mon, 12 Jan 2009) | 2 lines Fix some C#3.0-isms that broke build in Mono 1.2.6 and MSVC# 2005. Fixes Mantis #2989. r8020 | homerh | 2009-01-12 12:24:20 -0700 (Mon, 12 Jan 2009) | 1 line Fixed some svn properties r8019 | justincc | 2009-01-12 11:45:03 -0700 (Mon, 12 Jan 2009) | 3 lines - Extend PacketHandlerTest to fire in a packet. - Can't test result yet since the Client thread handles it with unpredictable timing r8018 | justincc | 2009-01-12 11:00:46 -0700 (Mon, 12 Jan 2009) | 4 lines - Apply - Add the KanEd scripts to the standard library - Thanks Fly-Man- r8017 | justincc | 2009-01-12 10:54:53 -0700 (Mon, 12 Jan 2009) | 2 lines - Remove FunSLUDP code since this has moved to r8016 | justincc | 2009-01-12 10:51:43 -0700 (Mon, 12 Jan 2009) | 4 lines - Apply - Adds first version of MsSql2005Dialect support for NHibernate - Thanks mpallari r8015 | justincc | 2009-01-12 10:44:39 -0700 (Mon, 12 Jan 2009) | 5 lines - Apply - Add single conversion to MSSQLManager.DbTypeFromType - May resolve storage of prim information under MSSQL - Thanks SirKimba r8014 | justincc | 2009-01-12 10:31:30 -0700 (Mon, 12 Jan 2009) | 2 lines - refactor: move packet handler interface into a separate class r8013 | mw | 2009-01-12 08:37:30 -0700 (Mon, 12 Jan 2009) | 2 lines Added WearableItem class to the framework. This class can be used to: load from disk, create from code, or modify a existing Wearable item. Its not currently used by anything in trunk but is a handy utility class. I'll be writing some instructions on its use as part of a more general article on various methods of creating better initial avatars for new users. Which will include some code samples, but as each grid has its own requirements, there will be no out of the box solution included. r8012 | sdague | 2009-01-12 08:34:05 -0700 (Mon, 12 Jan 2009) | 3 lines Caught exceptions in some console commands From: Arthur Rodrigo S Valadares <arthursv@linux.vnet.ibm.com> r8011 | sdague | 2009-01-12 08:33:56 -0700 (Mon, 12 Jan 2009) | 4 lines Enhanced LoginServiceTests to test for authentication and response Expanded TestUserDataPlugin to cover new methods From: Arthur Rodrigo S Valadares <arthursv@linux.vnet.ibm.com> r8010 | melanie | 2009-01-12 06:19:33 -0700 (Mon, 12 Jan 2009) | 4 lines Cause permissions on root prims to not override folded permissions anymore Fix propagation of folded permissions from object inventory to agent inventory. r8009 | mw | 2009-01-12 03:16:33 -0700 (Mon, 12 Jan 2009) | 1 line a little bit more work on LLFileTransfer.cs, from over the christmas/new year period. Still not working/in use but hopefully I can finish it soon. r8008 | mikem | 2009-01-12 02:04:31 -0700 (Mon, 12 Jan 2009) | 1 line Make ZERO_ROTATION.y a float. Fixes Mantis #2985. r8007 | ckrinke | 2009-01-11 20:49:48 -0700 (Sun, 11 Jan 2009) | 4 lines Commenting out the succesful REST message as under heavy use there are multiple messages in a second and that is usually (in my experience) meaning the logging itself is slowing down the program. Leaving the unsuccesful message as we need to know about that path. r8006 | ckrinke | 2009-01-11 11:24:16 -0700 (Sun, 11 Jan 2009) | 12 lines Thank you kindly, Tlaukkan (Tommil) for a patch that: Fixed all NHibernate unit tests by implementing missing persistency methods, tables, columns and fixing bugs in the existing implementation. Two minor changes to classes outside NHibernate module: Added Scene instantiation for SceneObjectGroup in OpenSim.Data.Tests.BasicRegionTest as this was required by the NHibernate persistency. In the process added also mock constructor to Scene which only populates RegionInfo in the scene which is used by ScenePart.RegionUUID. NHibernate module is still in experimental state and has not been tested at opensim region or ugaim runtime configuration. Adding unit tests to build is not yet advisable nor using NHibernate module in any production setup. r8005 | ckrinke | 2009-01-10 09:31:00 -0700 (Sat, 10 Jan 2009) | 9 lines Thank you kindly, Tlaukkan (Tommil) for a patch that: NHibernate MySQL migration was not working as mysql dialect is MySQL5Dialect now instead of MySQLDialect which is the migration sub folder name. Fixed this by adding simple dialect to migration sub type mapping to manager initialization to avoid need of renaming migration script folder each time MySQL version changes. Removed shared session and changed session to be constructed per call as NHibernate session is not thread safe. Refactored manager member names to be according to the naming convention (full words in camel case). r8004 | dahlia | 2009-01-10 02:15:23 -0700 (Sat, 10 Jan 2009) | 1 line Revert progressive texture patch from r8001 until issues can be addressed r8003 | ckrinke | 2009-01-09 21:23:23 -0700 (Fri, 09 Jan 2009) | 2 lines Include the changes from StrawBerryFride's patch to OpenSim.ini.example. r8002 | ckrinke | 2009-01-09 21:16:06 -0700 (Fri, 09 Jan 2009) | 5 lines Thank you kindly, StrawberryFride for a patch that: Enable users to enable only selected methods out of the available set of remote methods to restrict remote functionality to less harmful methods, such as admin_broadcast, or admin_region_query. r8001 | dahlia | 2009-01-09 18:46:47 -0700 (Fri, 09 Jan 2009) | 1 line Thanks jhurliman for a patch that implements progressive texture downloading - Mantis #2655 r8000 | justincc | 2009-01-09 14:15:34 -0700 (Fri, 09 Jan 2009) | 2 lines minor: remove mono compiler warning r7999 | justincc | 2009-01-09 14:05:53 -0700 (Fri, 09 Jan 2009) | 2 lines - minor: Put in stub LLPacketHandler testing code r7998 | melanie | 2009-01-09 08:15:41 -0700 (Fri, 09 Jan 2009) | 3 lines Prevent error message from scripted IM Fixes Mantis #2970 r7997 | melanie | 2009-01-08 19:59:56 -0700 (Thu, 08 Jan 2009) | 4 lines Finish dwell sending, adding the forgotten method body. Add UserInfo and a dummy reply to enable Hippo Viewer users to disable IM logging (option was greyed out in OpenSimulator before) r7996 | teravus | 2009-01-08 15:01:57 -0700 (Thu, 08 Jan 2009) | 2 lines - Adds the variables passed to the hashtable BaseHttpServer passes in. - Null check on Sessions_report. r7995 | justincc | 2009-01-08 14:05:24 -0700 (Thu, 08 Jan 2009) | 2 lines - Establish placeholder for future TextureSender tests r7994 | justincc | 2009-01-08 12:28:10 -0700 (Thu, 08 Jan 2009) | 2 lines - refactor: move url sending from scene to DialogModule r7993 | justincc | 2009-01-08 12:18:45 -0700 (Thu, 08 Jan 2009) | 2 lines - minor: Remove now unused SendEstateMessage... method in Scene I forgot from last commit r7992 | justincc | 2009-01-08 12:14:52 -0700 (Thu, 08 Jan 2009) | 2 lines - refactor: move code to send a dialog to a user from scene to DialogModule r7991 | justincc | 2009-01-08 12:05:22 -0700 (Thu, 08 Jan 2009) | 3 lines - refactor: move estate dialog to DialogModule - This appeared only to be implemented for the region, and doesn't currently seem to work anyway r7990 | justincc | 2009-01-08 11:50:46 -0700 (Thu, 08 Jan 2009) | 2 lines - refactor: move code for sending a message to all users in a region to the DialogModule r7989 | chi11ken | 2009-01-07 18:13:08 -0700 (Wed, 07 Jan 2009) | 1 line Update svn properties, minor formatting cleanup. r7988 | teravus | 2009-01-07 16:35:11 -0700 (Wed, 07 Jan 2009) | 1 line - Add session length to session.report. r7987 | teravus | 2009-01-07 16:20:23 -0700 (Wed, 07 Jan 2009) | 3 lines - Added session report. - Full or two criteria. UserID, or VersionString - Added link to session report from client report. r7986 | justincc | 2009-01-07 13:46:28 -0700 (Wed, 07 Jan 2009) | 2 lines - refactor: Make some direct IClientAPI calls go through the dialog module instead r7985 | justincc | 2009-01-07 13:29:09 -0700 (Wed, 07 Jan 2009) | 3 lines - Move general alert code to DialogModule. - Should be a clean build - last failure looked like a mantis hiccup r7984 | justincc | 2009-01-07 13:13:40 -0700 (Wed, 07 Jan 2009) | 2 lines - minor: Remove mono compiler warnings from WindModule r7983 | justincc | 2009-01-07 13:09:37 -0700 (Wed, 07 Jan 2009) | 2 lines - refactor: Establish DialogModule, move some alert code from Scene to here r7982 | justincc | 2009-01-07 12:33:20 -0700 (Wed, 07 Jan 2009) | 2 lines - Slightly increase ScenePresences locking where it's technically required in SceneGraph r7981 | justincc | 2009-01-07 11:46:27 -0700 (Wed, 07 Jan 2009) | 4 lines - Apply - This fixes adding and updating user profiles in MySQL on platforms that have a commas as a decimal separator - Thanks Tommil! r7980 | justincc | 2009-01-07 11:36:27 -0700 (Wed, 07 Jan 2009) | 2 lines - refactor: Remove MakeHttpRequest wrapper method from Scene in favour of a direct call r7979 | ckrinke | 2009-01-07 08:03:41 -0700 (Wed, 07 Jan 2009) | 4 lines Thank you kindly, StrawberryFride for a patch that: Solves the problem of unable to load prim items on region start in MSSQL. The error was in the MSSQLRegionData code that loads objects from the database, due to reliance on the ParentID field that is not used. r7978 | teravus | 2009-01-06 20:40:13 -0700 (Tue, 06 Jan 2009) | 2 lines - Added a client version report. - Added a report-> link generator. r7977 | justincc | 2009-01-06 14:39:55 -0700 (Tue, 06 Jan 2009) | 2 lines - prune and regrade log messages relating to client login and logout r7976 | justincc | 2009-01-06 11:26:27 -0700 (Tue, 06 Jan 2009) | 3 lines - Rename GetRandomCapsPath() to GetRandomCapsObjectPath() to fit in with terminology used elsewhere - Last build break was probably a Bamboo failure - hopefully this should succeed r7975 | justincc | 2009-01-06 11:12:22 -0700 (Tue, 06 Jan 2009) | 2 lines - Fix build break - forgot that I had renamed an argument r7974 | justincc | 2009-01-06 11:06:53 -0700 (Tue, 06 Jan 2009) | 2 lines - Move common string aggregation for caps seed path to a method in CapsUtil r7973 | justincc | 2009-01-06 10:30:37 -0700 (Tue, 06 Jan 2009) | 2 lines - Yeah, might just want to add the new class as well - sigh r7972 | justincc | 2009-01-06 10:27:04 -0700 (Tue, 06 Jan 2009) | 2 lines - minor: Move GetRandomCapsPath() to a CapsUtil class r7971 | justincc | 2009-01-06 09:39:08 -0700 (Tue, 06 Jan 2009) | 2 lines - Remove unused CAPSService r7970 | justincc | 2009-01-06 08:26:30 -0700 (Tue, 06 Jan 2009) | 2 lines - remove mono compiler warnings r7969 | afrisby | 2009-01-06 08:14:15 -0700 (Tue, 06 Jan 2009) | 4 lines - Added three new events to SceneGraph: - OnObjectCreate - OnObjectDuplicate - OnObjectRemove r7968 | justincc | 2009-01-06 08:09:52 -0700 (Tue, 06 Jan 2009) | 2 lines - refactor: Remove the need to separately pass in the http listener to the scene - this is always available via CommsManager r7967 | justincc | 2009-01-06 07:44:45 -0700 (Tue, 06 Jan 2009) | 2 lines - refactor: call AddHttpHandler() directly via CommsManager r7966 | justincc | 2009-01-06 07:37:39 -0700 (Tue, 06 Jan 2009) | 2 lines - refactor: call AddStreamHandler() directly via CommsManager r7965 | justincc | 2009-01-06 07:30:50 -0700 (Tue, 06 Jan 2009) | 2 lines - refactor: call AddLLSDHandler directly via CommsManager r7964 | justincc | 2009-01-06 07:20:54 -0700 (Tue, 06 Jan 2009) | 2 lines - refactor: drop AddXmlRpcHandler() from scene in favour of call via CommsManager r7963 | teravus | 2009-01-05 18:10:26 -0700 (Mon, 05 Jan 2009) | 1 line - Mjnor: Clarified comment to ensure that people are aware of how to end the recursive calls r7962 | teravus | 2009-01-05 17:57:33 -0700 (Mon, 05 Jan 2009) | 5 lines - Kill an endless loop in the Instant Message delivery system - Must compare user region with previous calling of the same method to determine if we should look the user up. - The first time, the previous region handle will be 0, so therefore it'll use the cached version. - The second time, previousRegionHandle will be what we looked up on the first round - The third time, it'll say.. we tried to deliver it once with or without lookup, we tried to deliver it a second time with lookup, and failed both times so end! r7961 | teravus | 2009-01-05 17:07:24 -0700 (Mon, 05 Jan 2009) | 1 line - Added a way for the sim stats reporter to say to the scene that the stats are illogical. r7960 | homerh | 2009-01-05 14:45:20 -0700 (Mon, 05 Jan 2009) | 1 line Use correct name for friendship offer. Fixes Mantis #2959. r7959 | justincc | 2009-01-05 13:58:57 -0700 (Mon, 05 Jan 2009) | 2 lines - minor: remove some mono compiler warnings r7958 | justincc | 2009-01-05 13:43:03 -0700 (Mon, 05 Jan 2009) | 3 lines - Stop bothering to populate and retrieve the parent local ids for MSSQL, as was done for SQLite and MySQL in r7586 - This may resolve r7957 | homerh | 2009-01-05 13:24:42 -0700 (Mon, 05 Jan 2009) | 4 lines Add the "Blank" texture, too. NOTE: I didn't mention that in my last checkin, but you'll have to clear your viewer cache to see the new textures in the library. r7956 | homerh | 2009-01-05 12:59:29 -0700 (Mon, 05 Jan 2009) | 2 lines Added viewer's default terrain textures. This fixes Mantis #2947. Thanks jhurliman r7955 | justincc | 2009-01-05 12:36:48 -0700 (Mon, 05 Jan 2009) | 2 lines - Centralize references to the well known blank texture 5748decc-f629-461c-9a36-a35a221fe21f to a constant in OpenSim.Framework.Util r7954 | justincc | 2009-01-05 11:58:10 -0700 (Mon, 05 Jan 2009) | 2 lines - add the required System.xml reference as well r7953 | justincc | 2009-01-05 11:52:43 -0700 (Mon, 05 Jan 2009) | 2 lines - Add prereqs and usings required by the Windows compiler r7952 | teravus | 2009-01-05 11:35:50 -0700 (Mon, 05 Jan 2009) | 7 lines - Resolve a few bugs in the Stats Collector - Update limiter logic reversed - Resolve a few bugs in the Viewer Stats collector - Catch the logoff ViewerStats post (darn those caps deregistrations) - Check the type of the correct map when checking - Resolve a leak in Prototype_distributor - .Close, .Dispose()! r7951 | justincc | 2009-01-05 11:33:12 -0700 (Mon, 05 Jan 2009) | 4 lines - Add the actual tests from - Apologies for missing these out yet again - Thanks to Tommil for this code r7950 | justincc | 2009-01-05 11:30:56 -0700 (Mon, 05 Jan 2009) | 2 lines - Add seed cap check to login test r7949 | justincc | 2009-01-05 11:04:47 -0700 (Mon, 05 Jan 2009) | 2 lines fixes mantis #2950 r7948 | justincc | 2009-01-05 11:00:53 -0700 (Mon, 05 Jan 2009) | 3 lines - Simplify test code by always setting up mock 'in memory' user and inventory data plugins for every TestCommunicationsManager - imo the gain in simplcity of test code outweighs the very small cost of setting up some stuff that some tests will never use r7947 | justincc | 2009-01-05 10:38:39 -0700 (Mon, 05 Jan 2009) | 3 lines - Extend stub to test the successful login of a user on the local login service - Test does not do authentication r7946 | justincc | 2009-01-05 09:30:35 -0700 (Mon, 05 Jan 2009) | 2 lines - Check in login service tests beachhead r7945 | sdague | 2009-01-05 08:59:08 -0700 (Mon, 05 Jan 2009) | 3 lines change the drop order to see if this affects unit test fails From: Sean Dague <sdague@gmail.com> r7944 | sdague | 2009-01-05 08:43:30 -0700 (Mon, 05 Jan 2009) | 3 lines - Fixes a small bug where load-oar fails due to whitespace in region name. From: Arthur Rodrigo S Valadares <arthursv@linux.vnet.ibm.com> r7942 | chi11ken | 2009-01-04 21:34:17 -0700 (Sun, 04 Jan 2009) | 1 line Update svn properties, minor formatting cleanup. r7941 | teravus | 2009-01-04 21:09:04 -0700 (Sun, 04 Jan 2009) | 5 lines - Adds an active log to the WebStats console. for an example of it in use as it is right now see - It still isn't quite ready to be used mainstream. - A couple of things to note, it doesn't keep track of the logs if nobody is looking at the stats. - It doesn't read the whole log file. Just the last 10 lines of the stream. Tested to 1GB+ logfiles with no noticeable performance issues. r7940 | afrisby | 2009-01-04 12:41:55 -0700 (Sun, 04 Jan 2009) | 1 line - Another minor GenericMessage fix - If we assume the method names are case-insensitive, we should process them as such. r7939 | afrisby | 2009-01-04 12:39:17 -0700 (Sun, 04 Jan 2009) | 1 line - Added some information to HandleGenericMessage to indicate that it's not the packet that isnt being processed, but instead the method-type. r7938 | dahlia | 2009-01-04 12:09:31 -0700 (Sun, 04 Jan 2009) | 1 line sync with primmesher r26 on forge r7937 | afrisby | 2009-01-04 12:09:22 -0700 (Sun, 04 Jan 2009) | 2 lines - Minor tweak to crash logger to copy ini with log if save-to-dir is on. - Added BinaryGenericMessage handler for cases where GenericMessage isnt transmitting pure-utf8 characters. r7936 | dahlia | 2009-01-04 11:36:13 -0700 (Sun, 04 Jan 2009) | 1 line Improve LOD scaling for anisotropic sculpted prim meshes r7935 | melanie | 2009-01-03 13:57:59 -0700 (Sat, 03 Jan 2009) | 2 lines Connect dewww request packets to the land module to makle dwell work r7934 | melanie | 2009-01-03 13:45:33 -0700 (Sat, 03 Jan 2009) | 2 lines Plumb the remaining dwell packets r7933 | diva | 2009-01-03 09:18:20 -0700 (Sat, 03 Jan 2009) | 1 line Fixed logic for sending foreign user information (HG). r7932 | diva | 2009-01-03 02:01:58 -0700 (Sat, 03 Jan 2009) | 1 line This may fix the home jump problem. r7931 | diva | 2009-01-03 01:51:54 -0700 (Sat, 03 Jan 2009) | 1 line Extra check to avoid client crashes on HG home teleports. r7930 | diva | 2009-01-03 00:31:48 -0700 (Sat, 03 Jan 2009) | 1 line Undoing the bump up of MajorInterfaceVersion number back to 2. This just doesn't work in practice! r7929 | diva | 2009-01-03 00:05:33 -0700 (Sat, 03 Jan 2009) | 2 lines Another interregion comms change that will not work well with previous versions. This commit moves InformRegionOfChildAgent from OGS1 to RESTComms, effectively having the complete child agent life cycle over REST: create=POST, update=PUT, close=DELETE. Additional changes include more functions in the IHyperlink interface, and some refactorings in the HG code for better reuse in RESTComms. r7928 | diva | 2009-01-02 20:41:41 -0700 (Fri, 02 Jan 2009) | 1 line Plumbing for moving InformRegionOfChildAgent over to RESTComms: pack and unpack methods for AgentCircuitData. This code is not used yet. r7927 | teravus | 2009-01-02 20:30:03 -0700 (Fri, 02 Jan 2009) | 4 lines - Updates the sim stats module. Cleans out some of the rot. - Adds a prototype web stats module which is disabled by default. It's functional with one report right now, however, the database structure may change, so I don't recommend enabling this to keep actual stats right now. I'll let you know when it's safe. - Adds Prototype for ajaxy web content - removed a warning or two. r7926 | diva | 2009-01-02 19:29:49 -0700 (Fri, 02 Jan 2009) | 1 line Split agent updates into two messages: full update and position+camera update. They're both sent over HTTP PUT. The full update is sent on TPs, for now; later it will also be sent on region crossings. r7925 | melanie | 2009-01-02 17:03:41 -0700 (Fri, 02 Jan 2009) | 2 lines Plumb in dwell in a couple of places r7924 | diva | 2009-01-02 17:00:37 -0700 (Fri, 02 Jan 2009) | 1 line Some plumbing for additional agent update messages. Not used yet. Removed the compilation warnings on this file, and completed the packing/unpacking of AgentData (VisualParams, Anims and Groups). r7923 | justincc | 2009-01-02 13:23:00 -0700 (Fri, 02 Jan 2009) | 2 lines - Add System.Xml to LindenUDP.Tests project for Windows builds r7922 | justincc | 2009-01-02 13:22:35 -0700 (Fri, 02 Jan 2009) | 3 lines - Move EventQueueGetModule to the EventQueue namespace - Not going to move EventQueueHelper as of now since the subsequent direct references to the module namespace would seem to somewhat defeat the point r7921 | justincc | 2009-01-02 13:11:20 -0700 (Fri, 02 Jan 2009) | 2 lines - Add Nini.Config and System.Xml references to MockScene for Windows compilers r7920 | justincc | 2009-01-02 13:07:29 -0700 (Fri, 02 Jan 2009) | 2 lines - refactor: move event queue module code to its own folder r7919 | justincc | 2009-01-02 12:46:12 -0700 (Fri, 02 Jan 2009) | 2 lines - reference is to Nini.Config, not Nini r7918 | justincc | 2009-01-02 12:43:30 -0700 (Fri, 02 Jan 2009) | 2 lines - Add Nini reference to Communications.OGS1 r7917 | homerh | 2009-01-02 10:55:55 -0700 (Fri, 02 Jan 2009) | 1 line Fix another build error on MonoDevelop r7916 | melanie | 2009-01-02 10:41:12 -0700 (Fri, 02 Jan 2009) | 3 lines Allow some values that are set in OpenSim.ini to be set from region config XML as well. r7915 | homerh | 2009-01-02 10:22:24 -0700 (Fri, 02 Jan 2009) | 5 lines Use only one (static) (de-)serializer for (de-)serializing SOPs. That improves performance drastically, at least for Mono, as the (de-)serializers can then be optimized (and won't use reflection anymore). On my system, before this change de-/serialization took ~9s/9s, whereas after the change it takes ~.5/.2s. r7914 | homerh | 2009-01-02 10:22:06 -0700 (Fri, 02 Jan 2009) | 1 line Get build working on MonoDevelop again. r7913 | melanie | 2009-01-02 09:24:44 -0700 (Fri, 02 Jan 2009) | 3 lines Small fix to prevent client thread crash in multi-region instances when a scripted object is paid r7912 | teravus | 2009-01-02 07:24:49 -0700 (Fri, 02 Jan 2009) | 1 line - Adding some recognizable and search-able test to some WriteLine(e.ToString()) messages so that when they occur, we can figure out what threw them. r7911 | melanie | 2009-01-02 05:57:21 -0700 (Fri, 02 Jan 2009) | 6 lines Fixes Mantis #2945 Committing the above patch with changes. Thank you, Gerhard. Removed unneccessary verbosity in case of no error, added more output for errors. Added support for HTTP Uri fetching which I had added in my last commit. Converted the Console.WriteLines to log4net. r7910 | melanie | 2009-01-01 22:52:01 -0700 (Thu, 01 Jan 2009) | 3 lines Add the ability to read the ini file from a URI. If the -inifile option is a http:// URI, it will be fetched and parsed as an XML config. r7909 | diva | 2009-01-01 12:42:24 -0700 (Thu, 01 Jan 2009) | 4 lines Major changes in interregion communications. This breaks compatibility with older versions, and may result is all sorts of weirdnesses when interacting with sims in older versions. Changes: - Introducing synchronous Teleports. Now the receiving region calls back the sending region after the client has been made a root agent there, that is, after client sends CompleteMovement to the destination. - SendCloseAgent moved from OGS1 Remoting to RESTComms. r7908 | diva | 2009-01-01 12:29:30 -0700 (Thu, 01 Jan 2009) | 2 lines Minor fix for HG request neighbors. Should not return hyperlink neighbors, only neighbors on the same grid. I'm still not sure if this is a bug or a feature, so this may change again. My first commit of 2009 -- Happy New Year! r7907 | diva | 2008-12-31 14:14:31 -0700 (Wed, 31 Dec 2008) | 1 line Beginning of true REST style for interregion comms, SendChildAgentUpdate only. Agents are now resources accessed at http://<host>:<port>/agent/<uuid>/[action/]. PUT is SendChildAgentUpdate. r7906 | diva | 2008-12-31 13:49:04 -0700 (Wed, 31 Dec 2008) | 1 line Minor bug fix in HG home regions management, removing the use of m_knownRegions.Count for creating the local handler. Local handlers are now created using a random number generator. r7905 | homerh | 2008-12-31 13:09:17 -0700 (Wed, 31 Dec 2008) | 1 line Slight optimisation: Don't check for duplication if we won't use the result anyway. r7904 | homerh | 2008-12-31 12:35:46 -0700 (Wed, 31 Dec 2008) | 6 lines - Added the fixed Ode.NET.dll - Adapted code to match the corrected signatures - Fixes Mantis #2934. Hopefully. Note: Physics on linked objects still don't work correctly: It doesn't crash the region anymore, but the example object in the mentioned mantis now falls through the ground. r7903 | homerh | 2008-12-31 12:35:33 -0700 (Wed, 31 Dec 2008) | 1 line Added a missing setMass for initializing the mass of prims r7902 | diva | 2008-12-31 11:26:31 -0700 (Wed, 31 Dec 2008) | 1 line Added http-method to the hashtable that gets passed to GenericHTTPMethods. r7901 | chi11ken | 2008-12-30 23:54:33 -0700 (Tue, 30 Dec 2008) | 1 line Update svn properties. r7900 | diva | 2008-12-30 17:49:34 -0700 (Tue, 30 Dec 2008) | 1 line Folded HG regionhandle lookup into the normal RESTInterregionComms, to avoid proliferation of "modes". r7899 | diva | 2008-12-30 17:18:24 -0700 (Tue, 30 Dec 2008) | 1 line Added a SendChildAgentDataUpdate call on Teleports, so that the agent at the destination will have all the necessary information. r7898 | diva | 2008-12-30 16:53:51 -0700 (Tue, 30 Dec 2008) | 1 line Removing unnecessary null checks on structs in AgentsData pack/unpack. r7897 | justincc | 2008-12-30 13:48:31 -0700 (Tue, 30 Dec 2008) | 3 lines - Remove mono compiler warnings - Leaving the 23 warnings in ChildAgentDataUpdate.cs for Diva to look at r7896 | justincc | 2008-12-30 12:00:19 -0700 (Tue, 30 Dec 2008) | 5 lines - Implement saving of region settings in OAR files - This means that you can now save terrain textures, water height, etc. - Estate settings are not supported - Older OAR files without these settings can still be loaded r7895 | homerh | 2008-12-30 09:16:47 -0700 (Tue, 30 Dec 2008) | 1 line OpenUser_Main is now public. Fixes Mantis #2940. Thanks SirKimba r7894 | diva | 2008-12-29 18:21:13 -0700 (Mon, 29 Dec 2008) | 1 line Making the default choice for InterregionComms work, and removing an unnecessary console debug message. r7893 | chi11ken | 2008-12-29 18:08:07 -0700 (Mon, 29 Dec 2008) | 1 line Update svn properties, minor formatting cleanup. r7892 | diva | 2008-12-29 15:44:04 -0700 (Mon, 29 Dec 2008) | 1 line Changing the default Comms module to be RESTComms, in case none is specified in OpenSim.ini. RESTComms is a super-set of LocalComms. Calls to local regions do no use REST, they use internal function calls. r7891 | diva | 2008-12-29 15:22:05 -0700 (Mon, 29 Dec 2008) | 1 line Final part for implementing SendChildAgentDataUpdate with modules. This is the part that uses the modules in Scene and related classes. This commit breaks compatibility of sim-sim SendChildAgentUpdates with older versions of OpenSimulator. r7890 | diva | 2008-12-29 14:40:20 -0700 (Mon, 29 Dec 2008) | 1 line This is a beefy commit containing the communication modules that implement SendChildAgentUpdate. This commit has only the modules, but not their usage. It should be harmless. r7889 | diva | 2008-12-29 14:26:44 -0700 (Mon, 29 Dec 2008) | 1 line Minor change in HGSceneCommunicationService, making one field public readonly. Totally harmless. r7888 | diva | 2008-12-29 14:10:35 -0700 (Mon, 29 Dec 2008) | 1 line Merged the InterregionData that Melanie had placed there onto the existing ChildAgentDataUpdate. This commit involves a change in prebuild.xml, because ChildAgentDataUpdate uses OpenMetaverse.StructuredData. Still no use of this data structure, though. Crossing my fingers that this partial commit will compile ok... r7887 | diva | 2008-12-29 13:43:33 -0700 (Mon, 29 Dec 2008) | 1 line First commit in a series of commits for Interregion REST comms. This one simply deletes the skeleton module that Melanie kindly placed for me to start working on this. r7886 | justincc | 2008-12-29 09:56:48 -0700 (Mon, 29 Dec 2008) | 6 lines - Apply with some changes - This allows configuration of the assetset and library control file paths to be other than ./inventory/Libraries.xml and ./assets/AssetSets.xml - This is controlled via the LibrariesXMLFile and AssetSetsXMLFile configuration settings in [StandAlone] in OpenSim.ini (in standalone) and via the user and asset config xml files for grid mode - Thanks to SirKimba for the patch r7885 | melanie | 2008-12-28 16:55:34 -0700 (Sun, 28 Dec 2008) | 5 lines Revamp the return logic to close a privilege escalation loophole. Estate owner / Master avatar returns would place the item in the returner's inventory rather than the owner's if the owner was not in sim. r7884 | ckrinke | 2008-12-28 15:31:21 -0700 (Sun, 28 Dec 2008) | 2 lines Thank you kindly, StrawberryFride for a patch that: Persists appearance with MSSQL more properly. r7883 | melanie | 2008-12-28 12:15:20 -0700 (Sun, 28 Dec 2008) | 2 lines Demonstration code for modular comms. No user functionality r7882 | melanie | 2008-12-28 10:22:31 -0700 (Sun, 28 Dec 2008) | 2 lines Insert a 15 seconds delay before the script engine starts loading scripts r7881 | teravus | 2008-12-28 09:30:00 -0700 (Sun, 28 Dec 2008) | 2 lines - More NINJA Joint physics fixes from nlin. fixes mantis #2874
http://opensimulator.org/wiki/0.6.2-release
CC-MAIN-2021-49
refinedweb
7,056
62.21
Congratulations! sets you up well to continue your learning journey into other adjacent areas. So if there’s something you’re really interested in learning about, now’s a good time to see whether you have enough knowledge to jump into that. However, for most users, I think there are a few natural next steps. Data structures and algorithms If you haven’t already learned about these, this is my strongest recommendation. A data structure is a collection of data and a well defined set of methods to access or manipulate that data. The most common data structure used in programming is the array, which holds a number of elements of the same type in sequential memory. You can manipulate the data inside an array by using array indexing to directly access (or modify) the elements inside the array. In the lessons, we also covered the stack data structure, which provide push, pop, and top functions to access the data on the stack. An algorithm is a self-contained set of operations that typically manipulate or calculate outputs from the data in a data structure. For example, when you look through an array to find the median value, you’re executing an algorithm. Binary search is an algorithm to determine if a given value exists in a sorted array. Sorting routines (such as selection sort and bubble sort) are algorithms that sort data sets. Over the years, mathematicians and computer scientists have come up with a fairly standard set of reusable data structures and algorithms that are useful for constructing more complex programs. These all have various tradeoffs. For example, arrays are fast to access data and sort, but slow to add or remove elements. Linked lists, on the other hand, are slow to access data and sort, but very fast to add or remove elements (if you already know where those elements are). Why does it matter? Let’s use an analogy. If you were going to build a house, you could build all of your tools from scratch if you wanted. But it would take a long time, and you’d probably mess quite a few things up and have to start over (ever created a hammer? Me neither). Also, if you use the wrong tool for the job, your quality would suffer (try nailing in nails with a wrench). More likely, you’d go to the local hardware store and buy a few tools: a hammer, a level, a carpenter’s square, etc… and then read some internet tutorials on how to use them properly. These would vastly accelerate your house construction efforts. Data structures and algorithms serve the same purpose in programming: they are tools that, if you know how to use them, can vastly accelerate how quickly you can get things done at quality. The good news is that many of these data structures and algorithms have already been implemented in the standard library. You’ve already encountered some of these in the preceding tutorials: std::array, std::vector, std::stack, std::string, and std::sort, to name a few. Learning to use these effectively and appropriately is a great use of your time. If you’re short on time (or patience), learning how to use the most common data structures and algorithms is the minimum you should do. But if you have the inclination, try recreating those data structures yourself, from scratch. It’s really good practice on writing reusable code, and will help you down the road when something you need isn’t in the standard library. But then throw them out, and use the ones in the standard library. :) The C++ standard library The bulk of the C++ standard library is data structures and algorithms. However, the standard library contains other things too, and another next step could be to explore those. Among other things, there are numerics (math) libraries, input/output routines, functions to handle localization and regionalization, regular expressions, threading, and file access. Every new release of C++ (which has been happening about every 3 years now) adds a batch of new functionality into the standard library. It isn’t critical that you know how everything in there works, but it’s worth at least being aware of what exists, so that if you happen upon the need for it, you can go learn more as needed. is my go-to reference for discovering what exists. Graphical applications In our tutorial series, we developed console applications, because they’re easy, cross-platform, and don’t require installing additional software. Unlike many modern programming languages, C++ does not come with functionality to create application windows, or to populate those windows with graphical elements or graphical user interface widgets (checkboxes, sliders, etc…). To do those things in C++, you’ll need to enlist the help of a 3rd party library. Getting a graphical application up and running requires a few additional steps. First, you’ll need to actually install the 3rd party library and connect it to your IDE, so you can compile it into your program. Most graphical libraries should come with instructions on how to do this for the most popular IDEs. Next, you need to instantiate an OS window, which requires calling certain function from the toolkit. Most, if not all, of the libraries should have sample programs that you can compile and dissect if you’re not sure how to do something basic. There are a lot of libraries out there, and which one you should use depends on your requirements (you’ll have to do your own research to determine which one is right for you). Popular choices include Qt, WxWidgets, SDL, and SFML. If you want to do 3d graphics, all of these frameworks support OpenGL, and there are great OpenGL tutorials on the internet. Graphical applications typically run differently than console applications. With a console application, the program starts executing at the top of main() and then runs sequentially, usually stopping only for user input. Graphical applications also start executing at the top of main(), typically spawn a window, populate it with graphics or widgets, and then go into an infinite loop waiting for the user to interact with the window (via mouse click or keyboard). This infinite loop is called an event loop, and when a click or keypress happens, that event is routed to the function(s) that handle that type of event. This is called event handling. Once the event is handled, the event loop continues to run, waiting for the next bit of user input. TCP/IP / Network programming (aka. the internets) These days, it’s pretty rare to find programs that don’t connect to the internet, a back-end server/service, or leverage the cloud in some way. Any program that requires you to have an account and log in is connecting to a server and authenticating a user. Many programs connect to some service to check whether an update is available. Social applications maintain a persistent connection to a social infrastructure, to allow users to communicate with each other on demand. These are examples of networking. Networking (broadly) is the concept of having your program connect to other programs, either on your machine, or on network-connected machines, to exchange information. Networking is a powerful tool -- in the past, if you wanted to change the behavior of your application, you had to release an application update. Now, with some good program design, you can simply update information on a server somewhere, and all instances of the program can leverage that change. As with many things C++, there are libraries out there to help make your C++ programs network capable. The Asio C++ library is a commonly used one (there are two variants -- a standalone version, and a version that integrates with Boost, which is a library that provides a lot of different functions, much like the standard library). Multithreading All of the programs we’ve seen in this tutorial series run sequentially. One task is completed, then the next one starts. If a task gets stuck (e.g. you’re asking the user for input and they haven’t entered any yet), the whole program pauses. This is fine for simple academic programs, but not so great for actual applications. Imagine if your program couldn’t handle the user clicking on something because it was busy drawing something on the screen, or if the whole program paused/froze when a network call was happening. The program would feel unresponsive. Fortunately, a method exists to allow programs to execute multiple tasks at the same time. This is called threading. Much like how (most of) you can walk and chew bubble gum at the same time, threading allows a program to “split” its attention and do multiple things in parallel. For example, some graphical applications (such as web browsers) put the rendering (drawing graphics) portions of the applications on a separate thread, so that updating the screen doesn’t block other things (like accepting user input) while the drawing is happening. Network calls are often done on separate threads, so that if the network call takes a while to resolve, the application doesn’t grind to a halt while its waiting. Threading is powerful, but it introduces additional complexity, and a lot of room for additional errors. Therefore, I wouldn’t recommend starting here -- but it is a good area to learn about eventually, especially if you want to do complex graphical applications or network programming. Improve your fundamentals Another option is to spend time improving your understanding of best practices. For this, I highly recommend having a read-through of the CPP Core Guidelines, with an optional delving into the GSL library. A good bye! At this point, I’d like to take a moment to thank you for stopping by and reading this tutorial series. I hope you enjoyed your time here and have found this site useful. Special thanks to those of you who have helped keep this website a free resource available to everyone by viewing ads that interest you. Please drop by again! Good luck (and skill) in your future endeavors, and happy programming! And remember, old programmers never die -- they just go out of scope. -Alex PS: If you have any feedback or other suggestions for things to explore next, please mention them in the comment section below. Do you have any other websites for learning c programming language or html or anything like these? Hi Nascardriver and Alex! I finished all tutorials from your site and I want to ask you if is ok to start with Unreal Engine 4 or what I need to know before I start with it. At the same time I will continue with cppreference and more. I hope you can answer me. (sorry for my bad english) You should know enough to use it. Whatever you don't know you can look up. Thank you so much! Brilliant, thanks very much for this great tutorial. I last programmed C++ in 1995 - it's come on a bit :) Hi Nascardriver again! You mentioned a CMakeLists.txt. I went through microsoft Cmake section and it was all about creating a project from scratch.And more likely to create cross platform apps. How can I create that listfile for my existing project (solution)? I also searched other places and nothing to do so. I even ended up to download Cmake GUI 3.17 but honestly didn't figure that out! however I uploaded other files in the directory to repo. they didn't contain my preferences on language standard!- And something else about the review of my program: I needed a constructor of a class to do a certain job (fill with zeros) it doesn't need any parameter to do so! In the other hand I also have another constructor with no parameter that does another job (fill random numbers) it is as follows: and this one does another job: is there any standard or a conventional way to address this issue? because I overload the constructor with a random useless parameter type in the context, the one I would never need to use. Here it was a bool: Here's a very minimal CMakeLists.txt, assuming that your files are in a "src" directory I don't know if VS has builtin support for CMake and I don't know how to invoke CMake on Windows, you'll have to look up instructions for that. The sudoku.vcxproj sudoku.sln files are what contain your project settings (I don't know if they're both required). Now other people can open your project in VS. People with other IDEs still have to compile it manually, this wouldn't be the case with CMake, but Windows projects often don't support anything apart from VS. > I needed a constructor You can't have multiple functions with the same signature. The caller wouldn't be able to differentiate them. You can add a parameter to your constructor and fill the block based on that And possibly add a default argument to the constructor if you want to. If you don't want to merge the constructors into one, you can keep them apart and add useless parameters like you did. Then add static member functions to `Block` that call those constructors so the user of your code doesn't have to care about the parameters. To prevent having weird parameters, you can add custom types and use those Hi nascardriver and alex I have written a little program which solve a given board of sudoko (it can produce an initial one too. it may be unsolvable and program will tell) I uploaded it in gitHub. I wonder if you have enough time to check that out and point me my bad! (or good I hope) I learned all I know about c++ from this site. I didn't know anything at all before so this program is what I learned from you. Hi! I can't look at everything, but here's a quick review: - You didn't push any files that allow compilation of your code. Anyone who wants to compile your code has to set up a project themselves and guess which compiler settings are required. If you're using VS, push your project files. If you're using a good OS, push the file that you're using to compile your code or to generate a build script (Most often CMakeLists.txt). - File naming is consistent, nice. As always, avoid abbreviations. Is that GridColor or GridColumn? Only you know. And in 3 month, you'll have forgotten too. Same goes for your variable names. `b`allon, `pos`ture, `num`eric, etc. aren't very descriptive. - Use single quotes for characters. Double quotes are for strings. - `size_t` is C, `std::size_t` is C++. - Magic numbers. Use constants or get the values dynamically, eg. `grid.size()` is you have something like that. - There are spell-checker plugins that work in code. - Use your auto-formatter. - main.cpp:65 should probably be a reference. - You shouldn't need so many indexes in `Position`. If you know the size of your field, you can calculate everything based on `m_index` (If that's the index into the big array). - Empty destructors - #pragma once and manual header guard. The #pragma once is never used because of your manual guard, and it prevents compilation of compilers that don't support it. If your IDE adds #pragma once when you create new files, disable that. - In the loop in `GridCollar::gridCollegeCheck`, you don't need the index for anything. Use a standard algorithm or a range-based for-loop. - `GridColumbia::m_gridCola`: You know the size, this should be `std::array`. - You only need 1 header guard per header. Looking at BOARD_T_H and BOARDVEC_T_H. - Copy initialization. - Missing includes. Good classes, good operators, good const, good documentation, good job :) Hi thanks for the review. I GET it! I'm lazy at naming variables (I tried my best but sometimes it is a pain in the head!.) I'm very unfamiliar with gitHub and its aspects. most of the works in this program is for exercising. and implement what I learned so far.I tried to do everything at least once, like header guards. I had a very confusing times with those range based loops so I turn into classic ones. And some of the above I have question: what do you mean by line 65 in main.cpp be a reference? >> `size_t` is C, `std::size_t` is C++. what is the difference? I mean is std::size_t has something in particular to prefer it to size_t? >> Empty destructors : what harm is in those? I have no dynamically allocated member in any class. >>You know the size, this should be `std::array`. Is std::array faster than std::vector? because sometimes it goes like it is in infinite loop and I'm counting how many check have been done and it was as high as 4 million times. I am almost certain that the algorithm is consistent! but the amount of check that is done makes me doubt the algorithm! and Last but not least: >>Good classes, good operators, good const, good documentation, good job :) I assume myself a student of Alex and you.if it doesn't bother you.(that is what I learned is what I learned here.) and of course the "GOOD JOB" is actually to you :) P.S corrected as much correction you reviewed as I could and will push it to github to a branch named corrected. > line 65 in main.cpp be a reference You're creating a copy of the grid by doing this. You probably don't want to create a copy, but work with the original grid > `size_t` is C, `std::size_t` is C++ They're the same thing, but one is in the `std` namespace and the other isn't. The non-std variables and functions exist because some headers are compatible with C. If some other library also declares a `size_t` without a namespace, you'll run into name conflicts. > Empty destructors There's no reason to have them. They don't do anything, so you might as well remove them to avoid confusion. If I see a user-provided destructor, I assume that there's some special cleanup happening. You said it yourself, you're lazy, so why spent time writing something that does nothing? > Is std::array faster than std::vector? `std::array` is faster and safer than `std::vector`, because it doesn't do dynamic allocations and has a known size. I don't understand what you said after that. Where is an infinite loop? As you mentioned I am lazy and those destructors was automatically created by IDE (VS) so I had to remove them by myself and that was against the laziness :). But if it makes a difference I will clean them all. bonbon? OK then I get it I will never ever use non descriptive variable I learned my lesson I went through all the codes and rename what was non descriptive. :) >>about infinite loop: sometimes I get result in a reasonable time (say 7-8 second -I got a 2.8Ghz cpu) but sometimes it goes on and on without any result or error! the checking repeats for 4 million times as I end the execution! Is it worth a shot to implement std::array instead of vector? to see if it give me a result on those long no result executions? Those infinite loops aren't caused by vectors. This sounds like a bug in your solving algorithm. I haven't seen your entire code, but if you've used the vector correctly, you shouldn't notice a difference when you change the board type. You might notice a difference when you change the return types of your getRow and getColumbian functions (I don't remember the real names), because those probably get called very often. Thank you for helping me out! Hello there! I have learned C++. I know how to program C++. This website taught me a lot about C++ language. But language is not the only thing in software development. There are other tools that are used while programming like version control(git), unit testing, performance profiling, build systems, continuous integration and many more that i am probably not aware of. Can you suggest some resources where i can learn these advanced concepts of software development? It can be books, websites or anything. Sorry if this is a bit off topic. :) Excellent work. Very thanks. Thank you Alex and Nascardriver!!! Just finished going through all of these and just wanted to express my gratitude for all the work you've put into these wonderful and in-depth tutorials thank you thank you Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/appendix-c-the-end/
CC-MAIN-2020-29
refinedweb
3,504
64.2
2.3. Manipulating Data with ndarray¶ It’s impossible to get anything done if we can’t manipulate data. Generally, there are two important things we need to do with data: (i) acquire it and (ii) process it once it’s inside the computer. There’s no point in trying to acquire data if we don’t even know how to store it, so let’s get our hands dirty first by playing with synthetic data. We’ll start by introducing NDArrays, MXNet’s primary tool for storing and transforming data. If you’ve worked with NumPy before, you’ll an ideal ingredient for machine learning. 2.3.1.. For even more math, see the “Math” section in the appendix. We begin by importing MXNet and the ndarray module from MXNet. Here, nd is short for ndarray. In [1]: import mxnet as mx from mxnet import nd The simplest object we can create is a vector. arange creates a row vector of 12 consecutive integers. In [2]: x = nd.arange(12) x Out[2]: [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.] <NDArray 12 @cpu(0)> From the property <NDArray 12 @cpu(0)> shown when printing x we can see that it. Since we are dealing with a vector, both are identical. In [4]: x.size Out[4]: 12 In the following, we use the reshape function to change the shape of the line vector x to (3, 4), which is a matrix of 3 rows and 4 columns. Except for the shape change, the elements in x (and also its size) remain unchanged. In [5]: x = x.reshape((3, 4)) x Out[5]: [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.]] <NDArray 3x4 @cpu(0)> It can be awkward to reshape a matrix in the way described above. After all, if we want a matrix with 3 rows we also need to know that it should have 4 columns in order to make up 12 elements. Or we might want to request NDArray to figure out automatically how to give us a matrix with 4 columns and whatever number of rows that are needed to take care of all elements. This is precisely what the entry -1 does in any one of the fields. That is, in our case x.reshape((3, 4)) is equivalent to x.reshape((-1, 4)) and x.reshape((3, -1)). In [6]: nd.empty((3, 4)) Out[6]: [[-7.083049e+22 4.572437e-41 -7.083049e+22 4.572437e-41] [ 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00] [ 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00]] <NDArray 3x4 @cpu(0)> The empty method just grabs some memory and hands us back a matrix without setting the values of any of its entries. This is very efficient but it means that the entries can have any form of values, including very big ones! But typically, we’ll want our matrices initialized. Commonly, we want one of all zeros. For objects with more than two dimensions mathematicians don’t have special names - they simply call them tensors. To create one with all elements set to 0 a shape of (2, 3, 4) we use In [7]: nd.zeros((2, 3, 4)) Out[7]: [[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]] <NDArray 2x3x4 @cpu(0)> Just like in numpy, creating tensors with each element being NDArray that needs to be created through a Python list. In [9]: y = nd.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) y Out[9]: [[2. 1. 4. 3.] [1. 2. 3. 4.] [4. 3. 2. 1.]] <NDArray 3x4 @cpu(0)> In some cases, we need to randomly generate the value of each element in the NDArray. This is especially common when we intend to use the array as a parameter in a neural network. The following creates an NDArray with a shape of (3,4). Each of its elements is randomly sampled in a normal distribution with zero mean and unit variance. In [10]: nd.random.normal(0, 1, shape=(3, 4)) Out[10]: [[]] <NDArray 3x4 @cpu(0)> 2.3 use the dot function for matrix operations. Next, we will perform matrix multiplication to transpose x and y. We define x as a matrix of 3 rows and 4 columns, and y is transposed into a matrix of 4 rows and 3 columns. The two matrices are multiplied to obtain a matrix of 3 rows and 3 columns (if you’re confused about what this means, don)> Just like in Numpy, we can construct binary NDarrays by a logical statement.44 For stylistic convenience, we can write y.exp(), x.sum(), x.norm(), etc. also as nd.exp(y), nd.sum(x), nd.norm(x). 2.3.3.4. Indexing and Slicing¶ Just like in any other Python array, elements in an NDArray can be accessed by its index. In good Python tradition the first element has index 0 and ranges are specified to include the first but not the last..3’ll find that id(y) points to a different location. That don’t want to run around allocating memory unnecessarily all the time. In machine learning, we might have hundreds of megabytes of parameters and update all of them multiple times per second. Typically, we’ll want to perform these updates in place. Second, we might point at the same parameters from multiple variables. If we don’t update in place, this could cause a memory leak, and could cause): 140148078643520 id(z): 140148078643520 programs, we can also use x[:] = x + y or x += y to reduce the memory overhead of the operation. In [26]: before = id(x) x += y id(x) == before Out[26]: True 2.3 don.3.7. Problems.
http://gluon.ai/chapter_crashcourse/ndarray.html
CC-MAIN-2019-04
refinedweb
991
73.07
DNS and WINS In Windows NT Server 4.0 or later, the DNS service provides for the use of WINS lookup. This feature enables configured DNS zones to refer queries not answered from current zone information to a WINS server for further resolution. With this added search of the WINS namespace, both DNS and WINS are used to complete a full search of registered names for a matched response. WINS lookup is supported for both forward and reverse lookup zones and can be enabled on a per-zone basis or configured for selected zones. This feature should also be configured to prevent replication or zone transfer of WINS resource records to servers with other DNS implementations that do not recognize the WINS resource records. Down-level clients (Windows NT 3.5 and 3.51, Windows NT 4.0, Windows 95, and Windows 98), however, rely on NetBIOS, which can use an NBNS (WINS), broadcast, or flat LMHOSTS file. In particular, the NetBIOS name service is used for domain controller location. WINS Referral WINS filled the role of domain and machine locator service for previous versions of Windows NT. Windows 2000 does not require WINS in a NetBIOS-less environment. However, WINS is always a WINS database. To enable this kind of lookup, you can create a WINS referral zone in DNS that points to the WINS database. This zone does not perform any registrations or updates, as it simply refers DNS lookups to WINS. Whenever Windows 2000-based clients send a query with an unqualified name, the default domain name suffix is tried first. Additional suffixes, however, can be supplied as part of the DHCP configuration. If the name of the WINS Referral zone is one of them, all WINS client names can be resolved.
http://www.informit.com/articles/article.aspx?p=20971&seqNum=4
CC-MAIN-2020-10
refinedweb
295
64.61
In this tutorial, we will learn to create a MQTT client with ESP32 to publish sensor readings and to subscribe to different topics using HiveMQ. Our aim is to create an MQTT client that will be able to subscribe to MQTT topics and publish sensor readings on MQTT topics. We will use the PubSubClient library to connect our ESP32 development board with the HiveMQ MQTT broker. PubSubClient library provides useful functions to easily connect with MQTT brokers. After the ESP32 successfully connects with the MQTT broker, we will publish sensor data and also learn to subscribe to a particular topic. Any appropriate sensor can be used but for this article, we will use a BME280 sensor which is used to measure temperature, pressure, and humidity. This guide covers the following topics: - Brief introduction to MQTT protocol - BME280 sensor and its connection with the ESP32 board - Developing an ESP32 MQTT client - Using MQTT topic to publish sensor data acquired from BME280 sensor - Connecting ESP32 with MQTT broker (HiveMQ) - Receiving messages on ESP32 by subscribing to MQTT topic - Publishing MQTT messages from the ESP32 board to MQTT broker MQTT Protocol<< For a detailed tutorial regarding MQTT, its main components, MQTT broker and working follow the link: What is MQTT and How MQTT Works? Introduct ESP32 The connection of BME280 with the ESP32 board Required Components We will need the following components to connect our ESP32 board with the BME280 sensor. - ESP32 board - BME280 Sensor - Connecting Wires - Breadboard Schematic Diagram Connect the ESP32 device with BME280 as shown in the schematic diagram below: Vin is connected with a 3.3V pin on the module and both the ESP32 board and the sensor is commonly grounded. In some BME280 sensors, the SCK terminal means the SCL pin and is connected with its respective GPIO pin on the ESP32 board. Likewise, the SDI terminal means the SDA pin and is connected with its respective GPIO pin on the board. You may like to read these BME280 tutorials: - BME280 with ESP32 – Display Values on OLED ( Arduino IDE) - ESP32 Send Sensor Readings to ThingSpeak using Arduino IDE (BME280) - MicroPython: BME280 with ESP32 - MicroPython: BME280 Web Server with ESP32/ESP8266 Setting up Arduino IDE install libraries for the BME280 sensor and the PubSubClient library. Installing BME280 Libraries As we are connecting the BME280 sensor with ESP32_3<< Installing_5<< ESP32 MQTT Client Arduino Sketch Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file and save it. You need to enter your network credentials. This sketch will develop an ESP32 MQTT client by following the steps given below: - Connecting the ESP32 board with the local network - Setting up the ESP32 Client and the BME280 sensor - Connecting the ESP32 to an MQTT broker - Publishing the sensor readings to the MQTT topics - Subscribing to the MQTT messages in order to receive them #include <Arduino.h> #include <WiFi.h> #include <PubSubClient.h> #include <Adafruit_BME280.h> #include <Adafruit_Sensor.h> WiFiClient wifiClient; PubSubClient mqttClient(wifiClient); Adafruit_BME280 bme; const char* ssid = "Your_SSID"; const char* password = "Your_Password"; char *mqttServer = "broker.hivemq.com"; int mqttPort = 1883; void setupMQTT() { mqttClient.setServer(mqttServer, mqttPort); mqttClient.setCallback(callback); }."); // subscribe to topic mqttClient.subscribe("esp32/message"); } } } void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("Connected to Wi-Fi"); if (!bme.begin(0x76)) { Serial.println("Check BME280 connections!"); } setupMQTT(); } void loop() { if (!mqttClient.connected()) reconnect(); mqttClient.loop(); long now = millis(); long previous_time = 0; if (now - previous_time > 1000) { previous_time = now;); } } void callback(char* topic, byte* message, unsigned int length) { Serial.print("Callback - "); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char)message[i]); } } How the Code Works? Let us understand how each part works to develop a successful ESP32 MQTT client. Installing Libraries The code starts with including all the necessary libraries which are needed for the proper functionality of the code. The WiFi.h library will help in establishing the connection between our ESP32 module to a wireless network. The Adafruit_Sensor and the Adafruit_BME280 libraries which we installed earlier are also included as they are necessary as we have to interface the sensor with the ESP32. Additionally, the PubSubClient library will be needed for MQTT protocol. #include <Arduino.h> #include <WiFi.h> #include <PubSubClient.h> #include <Adafruit_BME280.h> #include <Adafruit_Sensor.h> Creating Objects Next, we will create an object of WiFiClient called wifiClient which we will pass as a parameter inside PubSubClient mqttcllient (). Moreover, we will also define the Adafruit_BME280 object named bme by setting it on the default I2C GPIO pins. WiFiClient wifiClient; PubSubClient mqttClient(wifiClient); Adafruit_BME280 bme; server and port. As we are using HiveMQ as the MQTT broker so we have defined the server as “broker.hivemq.com.” You can use any other broker as well. Just replace the mqttServer variable appropriately. char *mqttServer = "broker.hivemq.com"; int mqttPort = 1883; void setupMQTT() In the setupMQTT(). void setupMQTT() { mqttClient.setServer(mqttServer, mqttPort); mqttClient.setCallback(callback); } void reconnect() This function will be called in the process of reconnecting the MQTT broker. This is a void function which also takes in no arguments. Inside the function, we are connecting our ESP32 client with the MQTT broker by using a random client ID which will be associated with our client. In case, the connection is successfully made then the ESP32 client will subscribe to the message “esp32/message” by using mqttClient.subscribe(). This will be used to receive messages from the MQTT broker. This function will be called in the loop() function to reconnect the client with the MQTT broker if a successful connection was not made already.."); mqttClient.subscribe("esp32/message"); } } } void callback() We will use the callback() function to subscribe to MQTT topics so that our ESP32 board will be able to receive messages of that topic. In the reconnect() function, we had subscribed our ESP32 board to the “esp32/message” topic. In the callback() function, the client will receive the messages of the subscribed topic. These will get displayed in the serial monitor. void callback(char* topic, byte* message, unsigned int length) { Serial.print("Callback - "); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char)message[i]); } } setup() Inside the setup() function, we will connect our ESP32 board with the Wi-Fi and initialize the BME280 sensor as well as set up the MQTT broker. Firstly, Wi-Fi” will get displayed on the serial monitor. WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("Connected to Wi-Fi"); Next, the BME280 sensor will get initialized and in case of failure, an error message will be printed on the serial monitor. if (!bme.begin(0x76)) { Serial.println("Check BME280 connections!"); } Moreover, we will also call the setupMQTT() function to configure the MQTT broker which will also set up the call-back function. setupMQTT(); loop() Inside the loop() function we will connect our ESP32 board with the MQTT broker. If the connection is unsuccessful, we will call the reconnect() function which we previously defined. After successfully connecting our client with the MQTT broker, we are ready to send sensor data and receive messages. if (!mqttClient.connected()) reconnect(); mqttClient.loop(); Now we will learn how to publish sensor data to MQTT topics. This is being achieved by using the PubSubClient library. After every second, we will take BME280 sensor readings by using bme.readTemperature(), bme.readPressure() and bme.readHumidity().These functions measure ambient temperature, barometric pressure and relative humidity respectively. These readings will get saved in their respective variables called temperature, pressure and humidity. Then we will convert each float variable to a char array. This will help us in publishing the sensor data to its respective topic. - For temperature readings, the topic is: “esp32/temperature” - For humidity readings, the topic is: “esp32/humidity” - And for pressure readings, the topic is: “esp32/pressure” You can use any other topic names as well. To publish the sensor data to its respective topic we will use mqttCleint.publish() and pass the topic as the first parameter and the data as the second parameter. This is done for all three topics.); Demonstration client and the broker. Setting HIVEMQ as MQTT Broker Open HiveMQ by following this link. Click the ‘Connect’ button. Publishing messages Now go to Subscriptions and add the subscription topics which we used in the program sketch. We will add these three topics which we have subscribed to: esp32/temperature, esp32/humidity, and esp32/pressure. After adding the topics you will be able to view the sensor readings in the messages section. Similarly you will be able to view temperature, pressure and humidity readings in the serial monitor as well. Testing for ESP32 Subscription Now we will check the ESP32 topic subscription on the topic where we have subscribed our ESP32 module. Head over to ‘Publish’ and in the Topic specify the topic which you used in the program code where the ESP32 is subscribed. In our case, it is “esp32/message.” In the message section, write any text which you want to send to your board. Then hit the ‘Publish’ button. Open your serial monitor. You will be able to see the same message get published to our ESP32 board. Conclusion In conclusion, we were able to create our ESP32 MQTT client and tested publishing and subscribing with the help of HiveMQ broker. We were successfully able to send BME280 sensor readings from the module to the broker via MQTT protocol. This tutorial is compatible with any other appropriate broker as well. You just need to specify its server and port in the program sketch. 2 thoughts on “ESP32 MQTT Client: Subscribe and Publish BME280 sensor readings on HiveMQ” HI, I have a question about using MQTT broker. In your tutorial, you used Hive as a broker. So could I open Hive in another LAN (for example my esp32 is at my home and I use a computer in my workplace via Hive to access these data. We have problem with Covid 19 so I couldn’t test it. Could you guide me how to create my own broker as Hive or integrate MQTT to application! Thanks! I have new question. If I have 2 Raspbberry Pi and both of them run this firmware. So What will we get on Hive? Thanks!
https://microcontrollerslab.com/esp32-mqtt-client-publish-subscribe-bme280-readings-hivemq/
CC-MAIN-2021-39
refinedweb
1,727
57.16
Since Groovy 2.2 we can assign the DelegatingScript class to a Script as a base script class. We use the CompilerConfigurationto set the base script class. After we have assigned the DelegatingScript class we can then set a delegate class for the Script. And this delegate class is then used to evaluate the script contents. This is a very easy setup for DSL scripts. import org.codehaus.groovy.control.CompilerConfiguration // Simple Car class to save state and distance. class Car { String state Long distance = 0 } // Custom Script with methods that change the Car's state. // The Car object is passed via the constructor. class CarScript { private final car CarScript(final car) { this.car = car } def start() { car.state = 'started' } def stop() { car.state = 'stopped' } def drive(distance) { car.distance += distance } } // Create CompilerConfiguration and assign // the DelegatingScript class as the base script class. def compilerConfiguration = new CompilerConfiguration() compilerConfiguration.scriptBaseClass = DelegatingScript.class.name // Configure the GroovyShell and pass the compiler configuration. def shell = new GroovyShell(this.class.classLoader, new Binding(), compilerConfiguration) // Simple DSL to start, drive and stop the car. // The methods are defined in the CarScript class. def carDsl = ''' start() drive 200 stop() ''' // Define Car object here, // so we can use it in assertions later on. def car = new Car() // Define CarScript instance so we can use it as delegate // for the script. def carScript = new CarScript(car) // Set delegate carScript to script, so the DSL // can be executed. def script = shell.parse(carDsl) script.setDelegate(carScript) // Run DSL script. script.run() // Checks to see that Car object has changed. assert car.distance == 200 assert car.state == 'stopped' Code written with Groovy 2.2. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/groovy-goodness-set-delegating
CC-MAIN-2017-34
refinedweb
286
53.58
Why is it necessary to uninstall the module ex46 in the exercise 46 of Learn Python The Hard Way? Is there any specific reason? Why is it necessary to uninstall the module ex46 in the exercise 46 of Learn Python The Hard Way? Uninstall? Did I have you install it? If I have you uninstall then it’s just so it doesn’t pollute your later projects. Ok. Can you mention those harms which a module can do if not uninstalled? The biggest one is that you might do an import of the wrong code. Let’s say you have this line: from ex46 import mything Now, you’re working on the file: ex46/mything.py And you keep making changes over and over and NOTHING changes. Then, 2 days later you figure out it’s because the file that is actually being loaded is your installed ex46/mything.py that’s really in ~/.venvs/ex46/mything.py. Thanks. Now I understood. 1 Like
https://forum.learncodethehardway.com/t/is-it-necessary-to-uninstall-module-in-lpthw-3x46/3870
CC-MAIN-2022-40
refinedweb
164
84.07
[Last modified: Mar 96] Answer: Editres, part of the MIT delivery, is a powerful widget tree analysis tool and is highly recommended. There's negligible overhead in making editres available to an application and many projects keep the editres "hook" active even for operational programs. It isn't built in to Motif (at 1.2.*), but you can do this in your application: #include <X11/Xmu/Editres.h> XtAddEventHandler(shell_widget, (EventMask) 0, True, (XtEventHandler) _XEditResCheckMessages, NULL); once for each shell widget that you want to react to the "click to select client" protocol. Then link your client with the R5 libXmu. Thanks to David Brooks, OSF, for the original answer. Jan Sandquist (ehsjasa@ehs.ericsson.se) supplied the current code snipet above. Joachim Fabini (jo@vmars.tuwien.ac.at) suggested that I remove the older use of "extern void _XEditResCheckMessages()" which resulted in core dumps on some platforms. NOTE: Ken Lee has placed his November, 1994 editres tutorial on the Web: [ Usenet FAQs | Web FAQs | Documents | RFC Index ]
http://www.faqs.org/faqs/motif-faq/part8/section-39.html
CC-MAIN-2019-04
refinedweb
168
58.48
Equivalent of robofab.RFont.update() In Fontlab you use RFont.update()to update the data & also the UI. This is a handy way of checking that whatever behavior you intend to happen (for instance, in a loop) is actually happening. I see from the Robofab docs that RFont.update()doesn't do anything outside Fontlab. So how do you trigger an equivalent UI refresh in Robofont? (BTW, note that many existing Fontlab scripts call RFont.update(). For forward-compatibility, perhaps it makes sense for RFont.update()to have the same effect on the Robofont UI.) there is a myFont.update():) that is posting a font is changed notification to all the subscribed objects see (just seeing that the glyph.update()is not listed in the docs, will add this as well) OK, then here's an example illustrating my confusion: import robofab.world f = robofab.world.CurrentFont() g = f["A"] for n in range(0,54): g.rotate(10) f.update() I expect this code to rotate the A glyph 540 degrees in 10-degree increments, and that each step would be visible in the UI (because I'm calling update()after each rotate().) Instead I only see the final state (a net rotation of 180 degrees). In other words, the code behaves as if f.update()doesn't exist, and then the UI updates itself after the script exits. So is there a flaw in f.update(), or a flaw in my understanding of what it does? mmm, when there are several requests to update a view close after each other, cocoa will ignore previous request and refresh / update the view only once. but you can force the view to update / refresh: import robofab.world f = robofab.world.CurrentFont() g = f["A"] collectionView = f.document().getGlyphCollection() view = collectionView.getGlyphCellView() # get the glyph cell view for n in range(0,54): g.rotate(10) g.update() view.display() # force the view to redisplay hope you like the animation :) I see what you mean Frederik, but I still think this is a flaw, for two reasons. - The discrepancy between the behavior of update()in Fontlab vs. update()in Robofont reduces the portability of Robofab scripts and makes it harder to create modules that can be shared between environments. Robofab becomes incompatible with itself. If Robofab-in-Robofont has some extras compared to Robofab-in-Fontlab, that's OK, because can ignore those if I need to. But I wouldn't expect major subtractions either. RFont.update()is critical and frequently used in Robofab-in-Fontlab. Once I add extra code to make update()work in Robofont the way it did in Fontlab, then I can't use that script in Fontlab anymore. - More broadly, an environment like Robofont that's built with a focus on scripting should always defer to the scripter. For instance, if I'm making valid update()requests in the script, why should Cocoa "ignore" them? OK, Cocoa thinks it will be slow. But why does Cocoa get to have an opinion? If it runs slow, that's my problem. Maybe I have my reasons for wanting it that way. It should be WYSIWYG — What You Script Is What You Get. There should never be situations where lines of script are getting silently ignored. (BTW, the animation is very exciting of course, but update()has a real practical function, which is to give visual feedback during multi-step operations. It is an excellent debugging and status-reporting tool.) I can't answer for RoboFont, but I can explain what is happening at the lower levels in defcon and defconAppKit. I can also give a little background on the history of the update method. First, the background: the update method in FontLab is purely a UI refresher. When you make a change to the data, the data is changed but the UI is not. For many scripters, this creates a pretty big problem because if update isn't called, the UI is out of sync with the data. That's bad. If you look at the RoboFab docs and examples, you'll see lots of things like # don't forget to call update!Those are there because we had lots of complaints. The update methods weren't part of RoboFog's scripting API and that's what we were trying to mimic. Almost all of the scripters were familiar with that API (and things happening there automatically) and that made the update calls quite foreign and a source of many complaints. We spent a lot of time trying to make the updates happen automatically, but we never got any responses to our requests to FontLab for information about the optimal times to refresh. For a very short period, we had update happening automatically whenever any data was changed. This was known as the OMG THIS IS SO SLOW version of RoboFab. To make the RoboFab API consistent, we implemented the update method in the base objects as: def update(self): pass It has been that way in NoneLab for a long time. When I wrote defcon, I wanted to do things in a modern way that allowed for code to be much more flexible and much faster. defcon uses the observer pattern (concept: implementation:) for keeping data and representations in sync in an abstract way. When you make a change to a defcon object, the object posts notifications through a font level notification dispatcher. Other objects that have subscribed to (object, notification)pairs will receive the notifications. It makes everything very lightweight and very fast. The various defconAppKit (an extension of vanilla) views use the notification system to be alerted of font object changes. When particular notifications are posted, defconAppKit notices and schedules things to be redrawn the next time Cocoa gives the views permission to redraw. Cocoa does this following its own rules. There are ways to hack into Cocoa to force it to redraw at a precise time, but those are frowned upon. I think this has more to do with the general drawing system that OS X uses than it is that Apple thinks that their code is much faster than everyone else. It's interesting that you say that this need to update the UI immediately is so critical. In all my years of working on and with RoboFab in FontLab I've never seen a script that needed to update the way that you describe. Do you have a lot of these kinds of scripts? Because .update()is a method that was added to RoboFab to work around FontLab UI bugs, I don't think that it's fair to assume that it should work the same way in an environment where those UI bugs don't exist. If you want to match the behavior of FontLab's .update()in RoboFont, you can put a test in your script for the enviroment the script is running in ( robofab.world.inFontLabor robofab.world.inRoboFont) and use view.display()if the script is running in RoboFont. I thought of a way that this could be done in the font and glyph objects. Here is the font object version: def update(self): document = self.document for windowController in document.windowControllers(): window = windowController.window() contentView = window.contentView() contentView.displayIfNeeded() (Not tested, but it should work. I think. Maybe.) Is this a good idea? I don't know. It could slow down lots of scripts for the sake of one script. works! but it will never make it into RF, sorry :) import time def update(font): document = font.document() for windowController in document.windowControllers(): window = windowController.window() contentView = window.contentView() contentView.displayIfNeeded() f = CurrentFont() g = f["A"] s = time.time() for angle in range(0, 360, 15): g.rotate(angle) update(f) print time.time() - s s = time.time() for angle in range(0, 360, 15): g.rotate(angle) f.update() print time.time() - s (with a font window open, glyph window open and Space Center open) For such a simple task it takes one 1 sec more to update. >>> 1.04617500305 >>> 0.0473890304565 So this is not a good plan unless you realllllyy like coffee or having days with 25 hours or when the sun is turning half speed.... if this is the case you can install a script during startup that add an observer to a fontChangednotification and updates all the possible windows and views. My understanding of why RFont.update()exists & how to use it was gleaned entirely from the Robofab docs & examples. Some Robofabbers may use it more, some less. But it is part of the standard Robofab-in-Fontlab scripting idiom. If you followed the Robofab docs, your scripts rely on it. (Tal, since you ask, one example of a script that "needs to update the UI immediately" is EVB's accent builder example on the Robofab site. () And I try to learn from the master.) As a matter of policy, having update()do nothing in NoneLab makes logical sense because there is no UI to update. Likewise, my comment is also one of policy: now that Robofab is in another UI environment, how should update()behave? Does it matter that it behaves differently than it did in the previous UI environment? Ben says no, because update()was designed to accommodate FL and I can test for FL in the script. A fair point, but there's another dimension to the problem. The update()command gives Robofab-in-Fontlab a nice modular division between the Robofab layer and the Fontlab UI layer. Everything gets encapsulated into the update()command. I don't have to worry about the specifics. Maybe this was an unintentional result, but to the extent that one of Robofab's goals is to insulate me from the FL object model, I always thought it was deliberate. Above, Frederik showed me how to work with view objects and view.display()to do my updates. That's fine as far as it goes, but it lacks modularity. I've got a script that would be happy if it could just be in the business of manipulating Robofab objects. Now it has to get into the business of manipulating Robofont UI objects too. As a scripter, it's not that I mind manipulating UI objects. It's just that ideally, I'd like to avoid mixing UI stuff with data stuff, because it won't scale. For instance, what happens when folks start releasing scripts with new UI widgets? Now my data-manipulation script has to get updated to work with those widgets too. (Tal, perhaps your proposed approach is forward-compatible in that way.) Nor am I saying that Robofont or defcon does it "wrong". Again, it's a policy question of how to expose the Robofont UI to scripts, whether to be consistent with FL, or whether to invent a 3rd idiom (i.e., require Robofab-in-Robofont scripters to take more of an interest in Robofont UI objects). Matthew: With all apologies, I don't think that this is a policy question. I think that we can agree that .update()in both FontLab and RoboFont and Glyphs (for all I know) updates the UI. Code with .update()works in both FontLab and RoboFont, with the result that at the end of a script, the UI is updated for the font or glyph that it is called on. In FontLab, it happens that if you call f.update(), FontLab will refresh the UI for each incremental change if it is called in a loop. This, from a speed of the application viewpoint, is a really dumb thing to do, as it slows everything down to molasses speed (see Frederik's timing and Tal's comment about when RoboFab was too liberal with .update()— and, if you've used UFO export in FontLab through RoboFab before the .update()s were taken out, you know that doing so could mean a nice coffee break). The only use of this 'feature' of FontLab, which you mention, that I can see would be for testing one's script. After the testing stage, one would just want their script to run, and run as quickly as possible. Frederik has demonstrated code that one could insert into a script for testing, much like how one inserts several print statements when testing a script, then takes them out when things are working. You pointed to Erik van Blokland's build accent script, which calls .update()so that FontLab will refresh the UI and show all the built accents. This script will work the same way in RoboFont, as .update()will also update the UI. Things work well in both applications. I believe, that what Tal, and for that matter, I, am curious about, is a example where a script depends on showing the UI update for each point in a loop, not just needing to update when all transformations are finished. I think that we can agree that FontLab isn't always the most consistent of applications, and that a view of consistency of RoboFab meaning that it needs to behave, bugs and all, 100% exactly like RoboFab in FontLab, even if the end result is the same, is both impractical and akin to asking every single web browser to behave just like IE6. The end result of a .update()is the same, which is all I think one can expect and ask for. If .update()'s end result was different in different applications, this would be a problem for RoboFab, but this is not the case here. Fair enough. At the moment, I don't have another script in my back pocket that illustrates the need for incremental UI updates. If I come across one, I will post it. Like I say, mostly I have used the feature for status reporting and debugging. As for update(), my only remaining question is when it actually makes a difference in a Robofont script. For instance, this code snippet (adapted from the EVB script) works the same way with or without the calls to update(). from robofab.world import CurrentFont f = CurrentFont() for k in ["A", "B", "C", "D"]: f[k].mark = 100 f.update() from robofab.world import CurrentFont f = CurrentFont() for k in ["A", "B", "C", "D"]: f[k].mark = 100 - mbutterick last edited by (How do I include a tag in a comment? Apparently it's something different than typing ) - mbutterick last edited by GAAAH (How do I include a pre tag in a comment? Apparently it’s something different than typing greater-than + pre + less-than) thanks for proving it yourself! ;) as stated in the documentation .update()only tells the UI that your object has changed. see off topic: I've just edited your post and added <pre>bla bla bla</pre>for none-editors and none-admins Matthew: My guess as to why it's working the same way (Frederik can confirm) is that RoboFont is smarter about updating the UI than FL is. You'd want to use .update()in the case you want to be absolutely sure the UI updates, and/or your script needs to run in both RoboFont and FontLab, and need it in there to force the FontLab UI to update. Best, Ben Thanks Ben. You impliedly make a good case that my goal of having FL & RF compatible scripts is impractical. There is something to be said for just rebuilding Robofont-optimized versions. As for update()in the middle of a script, my idiomatic use for this technique in Fontlab was when I was working with Robofab pens, specifically scripts that attempted to do pen operations on hundreds of glyphs at a pull. Of all Robofab operations, I found that pens were the most likely to awaken the FL crash monster. The traditional behavior of FL when it encounters a script error is to hang. So relying on a UI update at the end of the script to show me status didn't work, because it never got there. So I got in the habit of calling update()during the loops. This was slower, but when FL would hang, I could at least see how far it had gotten, giving some clues about why the script was failing, and whether the error was due to my own abuse of Robofab (which I could fix) or Fontlab's arbitrary refusal to continue (which I could not). Clearly, Robofont has a better work ethic about finishing scripts. Matthew: Two quick things: I don't think that .update()will slow down RoboFont, as you demonstrated it's smart about updating when need be, so having this in for FontLab won't impact RoboFont. Second, sometimes a quicker way to do what you wanted with update in FontLab is to just have a print statement for each iteration of a loop. You'll get a running list of what's been done, so you'll know what happens before a crash, even if the glyph your script is working on isn't visible in the font window. Best, Ben a quick tip if you a really, really want to debug in FL: redirect the stdout and stderr to a file instead if printing it into FLs output window, cause can FL can quit unexpectedly. import sys f = open(u"/Users/frederik/Desktop/FLlog.txt", "w") savedstdout = sys.stdout savedstderr = sys.stderr sys.stdout = f sys.stderr = f print "hello world" f.close() sys.stdout = savedstdout sys.stderr = savedstderr This will also work in RoboFont off course!! your scripts will still be exchangeable. another tip: visual debugging is in most cases a bad idea.... or you should make a .png, .pdf that you can review afterwards. Use DrawBot or the tinyDrawBot extension (will released when 1.2 is out) In all my years of working on and with RoboFab in FontLab I’ve never seen a script that needed to update the way that you describe. UFOCentral also relies on this technique, no? When I used it the other day, the glyphs and layers flashed before my eyes as I exported them. (Though I understand that UFOCentral is superfluous inside of Robofont.) The macro point is that stdout/stderr is useful for debugging only when you can describe the status accurately in text. For instance, plenty of times in FL I've used a pointPen to copy an outline from one font to another, only to find out it's been turned into crumpled space junk along the way. But as far as Robofab or FL was concerned, the pen operation reported no errors. Therefore, to rely on stdout/stderr only, you'd have to add in an extra step where you programmatically compare the expected and actual result, so the status can be reported accurately ("oops, you got space junk"). Sometimes that's easy to do (e.g., making a straight duplicate) but sometimes not (where there's a transform happening in between). Either way, you're adding new debugging code, which a) will slow your script (no big deal) and b) may itself have bugs in it (very big deal). For complicated pen operations, your debugging code would have to essentially reimplement the pen. Or you'd need to do something ritzy like apply your pen operation into the actual target glyph, and then also a buffer glyph, and compare the results. But it creates a spiraling need to debug the debugger. So what is the advantage of visual debugging? Like stdout and stderr, it works without creating collateral complications. Anyways, the vagaries of FL need not be hashed over here. My FL scripts all work fine — I've already absorbed those slings & arrows. When I get to the point where Robofont's update()is causing a more-than-theoretical problem, I will report back. In text.
https://forum.robofont.com/topic/82/equivalent-of-robofab-rfont-update/?lang=en-US&page=1
CC-MAIN-2021-49
refinedweb
3,304
65.22
June 15, 2011 by teal FOLLOW ME ON TWITTER! @TealMarchande Please Follow valentine one radar detector - August 18, 2011 @ 2:01 am That was a good blog post,You gain knowledge of new things each day. top online casinos - September 4, 2011 @ 4:01 am I’ve never heard of this before. I’ll make sure to check this out. strony internetowe - September 18, 2011 @ 3:23 pm. Lewis Monares - September 20, 2011 @ 9:22 pm Can I simply say what a relief to search out someone who actually knows what theyre talking about on the internet. You undoubtedly know the right way to bring a problem to light and make it important. More people have to read this and perceive this aspect of the story. I cant imagine youre no more standard since you undoubtedly have the gift. Jackqueline - September 30, 2011 @ 12:22 pm It! Arron Gran - October 3, 2011 @ 2:29 pm I just read a few other posts on here. Cool I came back again. Good reading, thanks. creation site web photographe - October 3, 2011 @ 3:30 pm A voir absolument Samantha Rodell - October 3, 2011 @ 7:12 pm I am really inspired together with your writing talents and also with the layout in your weblog. Is that this a paid topic or did you customize it yourself? Anyway stay up the nice quality writing, it is uncommon to look a nice blog like this one these days. cipki - October 4, 2011 @ 12:19 am I’m not sure where you’re getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for excellent info I was looking for this info for my mission. Shanae Mederios - October 4, 2011 @ 11:38 am I do agree with all the ideas you’ve introduced in your post. They are really convincing and can definitely work. Nonetheless, the posts are too short for starters. May just you please extend them a little from subsequent time? Thanks for the post. diablo 3 monk - October 7, 2011 @ 6:53 am Hi there there! This submit couldn’t be composed any much better! Reading through via this article reminds me of my prior area mate! He usually stored discussing this. I’ll ahead this short article to him. Fairly positive he’ll possess a great go through. Thanks for sharing! kutasy - October 8, 2011 @ 10:41 am web site. sex party - October 8, 2011 @ 3:11 pm Hi, i think that i saw you visited my website thus i came to “return the favor”.I am trying to find things to enhance my site!I suppose its ok to use a few of your ideas!! Tadalafil - October 17, 2011 @ 9:59 pm alloha spa & wellness - October 19, 2011 @ 2:36 am nicely? put! radar jammer - October 19, 2011 @ 7:30 am very nice post, i actually love this web site, carry on it Generic Viagra - October 21, 2011 @ 4:29 am This information allows the light source in which we are notice the truthfulness. This can be pretty awesome a and gives in-depth advice. Thanks this amazing attractive piece zabiegi spa - October 21, 2011 @ 5:43 am really wonderfull when to take viagra - October 22, 2011 @ 6:54 pm Is there any further information on it? sex im aargau - October 23, 2011 @ 1:02 am Hey there I wanted to write and say I love to read your Site! recommended dose tadalafil - October 23, 2011 @ 8:20 am This amazing site is the most very good site. spa & wellness - October 23, 2011 @ 6:49 pm Love the style! prezentacje maturalne - October 24, 2011 @ 9:15 pm Nice post! Thanks import chiny - October 24, 2011 @ 9:57 pm Very Good! spa w polsce - October 24, 2011 @ 9:58 pm wow! beautiful! merci upominki reklamowe - October 25, 2011 @ 2:00 pm This is damn good. biuro księgowe łódź - October 25, 2011 @ 8:49 pm Really awesome. wesela katowice - October 26, 2011 @ 1:23 am really wonderfull sklep akwarystyczny - October 26, 2011 @ 5:11 am Really awesome. Mee Mafnas - October 27, 2011 @ 1:59 am Im impressed, I need to say. Really hardly ever do I come across a weblog thats both informative and entertaining, and let me tell you, youve hit the nail on the head. Your weblog is crucial; the issue is one thing that not enough individuals are talking intelligently about. Im definitely pleased that I stumbled across this in my search for one thing relating to this problem. zabiegi spa - October 27, 2011 @ 2:05 am This is DOPE! Inspired smycze reklamowe - October 27, 2011 @ 6:28 am Great work!!! Loved every second! biuro rachunkowe łódź - October 27, 2011 @ 4:47 pm love it! Lindsey Buganski - October 27, 2011 @ 8:52 przeciski - October 28, 2011 @ 1:12 am This is DOPE! Inspired fotograf ślubny kraków - October 28, 2011 @ 5:57 am nicely? put! żeglarski sklep - October 28, 2011 @ 7:57 pm really wonderfull fazilitäten - October 29, 2011 @ 9:12 am really a tremendous web site. Ernest Tuccillo - October 29, 2011 @ 10:12 am Im impressed, I need to say. Pretty rarely do I come across a weblog thats each informative and entertaining, and let me tell you, youve hit the nail on the head. Your weblog is vital; the issue is one thing that not sufficient persons are talking intelligently about. Im definitely content that I stumbled across this in my search for something relating to this concern. fotografia ślubna łódź - October 29, 2011 @ 4:06 pm Great! fontanny czekoladowe - October 29, 2011 @ 6:22 pm Thanks for this post. I think it may be useful for my business, please write sth else about it. gendeng - October 31, 2011 @ 8:38 am An unputdownable discussion is worth account. I cerebrate that you should make more on this message, it might not be a sacred matter but generally fill are not enough to speak on such topics. To the succeeding. Cheers like your TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER!. krzesła producent - November 1, 2011 @ 10:25 pm This is DOPE! Inspired ugg boots sale - November 2, 2011 @ 6:04 am Very nice post. I just stumbled upon your blog and wanted to say that I’ve truly enjoyed browsing your blog posts. After all I will be subscribing to your rss feed and I hope you write again very soon! diosminex - November 2, 2011 @ 7:27 am Wonderful!!!!!! myp2p.eu football schedules watch live football on your pc - November 2, 2011 @ 11:49 am great web site yo have here by the way fronty meblowe - November 3, 2011 @ 12:10 am very inspiring. Pozycjonowanie stron w wyszukiwarkach - November 3, 2011 @ 1:58 am Love the grading Pozycjonowanie stron - November 3, 2011 @ 7:20 am Wonderful!!!!!! hotel katowice - November 3, 2011 @ 2:05 pm wow! beautiful! merci prezentacje maturalne - November 3, 2011 @ 2:45 pm Utterly beautiful. Filmy Download - November 3, 2011 @ 5:14 pm Interesing article Thank You very Much!!! MP3Million reviews - November 3, 2011 @ 7:55 pm I wanted to thank you for this great I definitely loved every little bit of it. I have you bookmarked your site to check out the latest stuff you post. Iomoio music downloads - November 5, 2011 @ 2:19 am I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your web site to look at the latest stuff you post. prezentacje maturalne - November 5, 2011 @ 2:25 am Delightful! Pozycjonowanie stron internetowych - November 6, 2011 @ 3:46 am love it! erotyka - November 6, 2011 @ 11:43 am It seems to me that I found the answer to many problems that the average web surfer can not solve alone – Sophie Filmy Komedie - November 6, 2011 @ 2:39 pm Very nice article Thank You very Much!!! prezent na urodziny - November 6, 2011 @ 3:25 pm Wonderful!!!!!! adwokat łódź - November 6, 2011 @ 3:47 pm So good! travel deals - November 7, 2011 @ 7:56 pm Thank you for taking the time to go about this, I must say i feel strongly about this and love learning extra for this topic. If doable, when you achieve expertise, would you mind updating your weblog with further info? It is very of great help for me. Real Estate Lewes Delaware - November 7, 2011 @ 11:50 pm Wow! This can be one particular of the most useful blogs We’ve ever arrive across on this subject. Basically Excellent. I’m also a specialist in this topic so I can understand your hard work. reklamy łódź - November 8, 2011 @ 1:03 am I love it! prace maturalne - November 8, 2011 @ 6:02 am Great work!!! Loved every second! Volkl Gotama - November 8, 2011 @ 8:45 am A very remarkable page you have mutual people. That is definitely will cause me both a general observe and the information regarding the patient. Your writing is incredibly décontracté and heavy. And the ways you utilize words and phrase is very wonderful also. Andree - November 8, 2011 @ 10:56 am I’ve gone ahead and added a hyperlink back to your webpage from one of my clients requesting it. I’ve used your web page URL: and blog title: TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER! to assure you get the proper anchor text. If you woud like to check out where your hyperlink has been placed, please contact me at: tomakil@live.fr. Thank you Web design Philadelphia - November 8, 2011 @ 11:19 am Thank you for every other informative web site. Where else may I get that kind of info written in such a perfect way? I’ve a project that I’m just now running on, and I’ve been at the glance out for such information. free penis enlargement methods - November 10, 2011 @ 4:11 pm I do agree with all of the ideas you’ve offered in your post. They’re very convincing and will definitely work. Nonetheless, the posts are too short for beginners. May just you please prolong them a little from next time? Thanks for the post. cell phone cases covers - November 11, 2011 @ 1:40 pm Thanks for ones marvelous posting! I quite enjoyed reading it, you are a great author.I will always bookmark your blog and definitely will come back at some point. I want to encourage you to ultimately continue your great writing, have a nice afternoon! dental Practice Edinburgh - November 11, 2011 @ 4:06 pm WONDERFUL Post. thanks for share.. more wait.. baby shower celebration foods food selection tips - November 11, 2011 @ 4:33 pm This internet website is truly a walk-through for all the info you wanted about this and didn锟斤拷t know who to ask. Glimpse here, and you锟斤拷ll absolutely discover it. sex filmy - November 12, 2011 @ 11:19 am I am positively surprised by this blog. A multitude of information clearly stated that I would make a regular guest here. Keep it up Berry Shintaku - November 12, 2011 @ 11:25 am Wow, there’s really so much to learn out there and one can get overwhelmed but when you know where to focus, it’s really all worth your time. Enjoyed your post! shemale, transwestyci - November 12, 2011 @ 6:25 pm I immediately liked this blog. Will be nice to come back here. Mary from gejownia.pl pozycjonowanie stron lodz - November 12, 2011 @ 6:28 pm Awesome work… download music for mp3 - November 12, 2011 @ 10:32 pm I thought it was going to be some boring old post, but I’m glad I visited. I will post a link to this page on my blog. I believe my visitors will find that very useful. distressed military cap - November 13, 2011 @ 12:19 pm There are a few attention-grabbing deadlines within this article but I have no idea of easily see every one of them middle to heart. There might be some validity however Ill take hold opinion till I check into it further. Good article , thanks therefore we would love extra! Added onto FeedBurner as nicely best makeup to cover scars - November 13, 2011 @ 12:57 pm I will surely foreward this post to all of my pals! Its very excellent and a very high-quality read! when did i get pregnant - November 13, 2011 @ 3:55 pm Thanks for making the honest seek to speak about this. I believe very powerful approximately it and desire to read more. If it’s OK, as you gain more complete wisdom, would you thoughts adding extra articles similar to this one with additional information? It might be extremely useful and helpful for me and my pals. R-134a - November 13, 2011 @ 9:31 pm Thank you for an additional vital post. Wherever else could anybody get that kind of data in this kind of a comprehensive way of writing? I have a presentation incoming week, and I’m on the lookout for such info. ugg on sale - November 14, 2011 @ 6:14 am You could certainly see your skills within the work you write. The sector hopes for more passionate writers like you who are not afraid to mention how they believe. All the time follow your heart. deals singapore - November 14, 2011 @ 9:35 am Thank you for discussing this brilliant articles on your website. I noticed it online. I might check to go back in the event you publish much more aricles. pozycjonowanie stron www lodz - November 15, 2011 @ 12:06 am yeah, cool! Thanks a lot canadian benefits - November 15, 2011 @ 12:48. strony www łódź - November 15, 2011 @ 1:23 am very inspiring. Pozycjonowanie stron www - November 19, 2011 @ 3:57 pm Great! Football News - November 25, 2011 @ 4:20 pm I’ve just found your site on Google. You did a great job 😉 swierzb - November 25, 2011 @ 5:51 pm Complete and very clear written! Thank you for this helpful information. duke nukem apk - November 25, 2011 @ 6:35 pm I got what you specify, thanks for putting up. Woh I am willing to bump this website through google. Thanks For Share TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER!. bronze windows - December 5, 2011 @ 4:47 pm Attractive section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently rapidly. Android Apps - December 9, 2011 @ 8:18 am I got what you designate, thanks for putting up. Woh I am gladsome to find this website finished google. Thanks For Share TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER!. Len Batson - December 13, 2011 @ 6:11 pm I definitely like studying a post that could make folks feel. Also, thanks for allowing me to comment! 3D Games - December 13, 2011 @ 8:45 pm Thanks a bunch for sharing this with all people you actually understand what you are talking approximately! Bookmarked. Kindly also talk over with my website =). We can have a link trade agreement between us! Watch Sherlock Holmes 2 Online - December 13, 2011 @ 9:05 pm Someone essentially help to make significantly posts I might state. This is the first time I frequented your web page and so far? I surprised with the analysis you made to create this particular publish extraordinary. Fantastic activity! cash for cars - December 14, 2011 @ 12:04 am Hi there would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot quicker then most. Can you suggest a good hosting provider at a honest price? Many thanks, I appreciate it! cash for junk cars - December 14, 2011 @ 1? benefactor offer - December 25, 2011 @ 11:38 am Hiya, I am really glad I have found this info. Today bloggers publish only about gossips and web and this is actually frustrating. A good website with interesting content, that’s what I need. Thank you for keeping this web-site, I will be visiting it. Do you do newsletters? Can not find it. used crome cleaner - December 25, 2011 @ 3:15 pm Outstanding post, you have pointed out some great details , I likewise conceive this s a quite very good internet site. Forex Guide - December 25, 2011 @ 4:49 pm Wohh just what I was seeking for, appreciate it for putting up. downloads - December 25, 2011 @ 8:31 pm I’m impressed, I need to say. very seldom do I stumble upon a blog thats both educational and entertaining, and let me tell you, youve hit the nail on the head. Your post is essential; the matter is something that not numerous of us are speaking intelligently regarding. i’m very happy that I stumbled across this in my explore for 1 thing relating to it. download game sepakbola gratis - December 25, 2011 @ 10:27 pm Thank you for a very informative blog. What else could I get that type of information written in such an ideal means? I have a challenge that I am simply now working on, and I’ve been on the look out for such information. Lona Walls - December 26, 2011 @ 8:56 am Love your blog! Sasha - December 26, 2011 @ 3:53 pm I really liked this. seo katalogi - December 26, 2011 @ 5:27 pm This is very interesting, You are a very skilled blogger. I’ve joined your feed and look forward to seeking more of your excellent post. Also, I have shared your site in my social networks! Angela - December 26, 2011 @ 7:43 pm Good day. I am wondering if you may be interested in doing a link swap? I see your blog: and my website are structured around the same subject matter. I’d really like to swap links or perhaps guest author a post for you. Here is my personal e-mail: julielienhart@live.fr. Please contact me if you’re even remotely interested. Thanks. Raleigh Photographer - December 26, 2011 @ 8:16 pm Hello there, I found your blog by means of Google even as looking for a similar matter, your web site came up, it seems to be great. I’ve bookmarked it in my google bookmarks. Internet Marketing Cape Town - December 26, 2011 @ 11:49 pm Excellent post. I was checking constantly this blog and I am impressed! Very helpful info specifically the last part I care for such info much. I was looking for this certain information for a very long time. Thank you and good luck. Lashonda Siewert - December 27, 2011 @ 10:36 pm Hey got nothing original this time, so all i am going to say that your website rocks, sad that I don’t have such writing talent Thanks again for taking the time to put this up. I definitely loved every bit of it. louis vuitton vernis bags - December 29, 2011 @ 5:40 pm I just added your RSS Feed on my RSS reader, it is so nice to read your blog. bandar bola online indonesia - December 29, 2011 @ 9:45 pm I am so happy to read this. This is the kind of info that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this greatest doc. Dario Cavazos - December 30, 2011 @ 2:05 am I couldn’t have said this better myself.buy diablo 3 gold Sony Ericsson CK15EUWH White Review - December 30, 2011 @ 8:02 am I’m still learning from you, while I’m improving myself. I absolutely love reading all that is written on your website.Keep the tips coming. I loved it! Nadene Cocca - December 31, 2011 @ 9:01 am Very interesting details you have noted, regards for putting up. Kathline Blanch - December 31, 2011 @ 6:41 pm Good write-up. I’m a normal visitor of your site and appreciate you taking the time to maintain the excellent site. I will be a regular visitor for a long time. tworzenie stron opole - December 31, 2011 @ 9:06 pm I always visit your blog and retrieve everything you post here but I never commented but today when I saw this post, I couldn’t stop myself from commenting here. Fantastic article mate! ps vita - January 1, 2012 @ 2:58 am Superb blog post, I have saved this web page so with any luck , I’ll discover a lot more on this subject in the foreseeable future! sex - January 1, 2012 @ 4:42 pm Hello. Very nice blog. Definitely I like and I will take in his example in my work. Yours – Olivia bosch wae283xl - January 1, 2012 @ 6:05 pm This is really interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your wonderful post. Also, I have shared your site in my social networks! kipper davis - January 1, 2012 @ 7:55 pm hey, your site looks sweet! thank you for sharing this information with us! Muay Thai - January 3, 2012 @ 10:28 pm I have to have functionality having to do with thanking you really around the pro tricks I have got generally taken pleasure in searching your blog post. We’re waiting for all the graduation akin to your college study very well as the entire process placement of feet wouldn’t are already utter with out arriving onto your blog post. Generally if i will be from a be an aid to friends, I’ll be glad which might help of what Ive came to understand from this level. uninstalling apps android - January 3, 2012 @ 10:42 pm I like the helpful info you provide in your articles. I’ll bookmark your blog and check again here regularly. I’m quite sure I will learn lots of new stuff right here! Best of luck for the next! Kyle Ransler - January 4, 2012 @ 9:04 am Hello There. I discovered your weblog the usage of msn. That is a very neatly written article. I will be sure to bookmark it and come back to read more of your helpful info. Thank you for the post. I’ll definitely return. dct3 - January 4, 2012 @ 10:00 am Hello There. I found your blog using msn. This is an extremely well written article. I’ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will definitely comeback. Edwina Godine - January 4, 2012 @ 12:30 pm Thanks for the article, it was interesting and compelling. I found my way here through Google, I will come back another time Kayce Burchette - January 4, 2012 @ 3:04 pm Just continue the rewarding work. link building - January 4, 2012 @ 7:30 pm I am starting up a new online blog directory and was wondering if I can submit your website? I’m hoping to mature my directory slowly by hand so that it retains good quality. I will make sure and put your website in the correct category and I’ll also use, “TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER!” as your anchor text. Make sure you let me know if this is ok with you by contacting me at: paulweill@live.fr. Thankyou web traffic - January 5, 2012 @ 2:12 am Awesome post! I will keep an on eye on your blog. Virgie Dunkle - January 5, 2012 @ 4:46 am I’ve learn a few excellent stuff here. Certainly price bookmarking for revisiting. I wonder how so much attempt you place to create this type of excellent informative web site. Senuke X - January 5, 2012 @ 7:40 am Heya! It appears as though we both have a passion for the same thing. Your blog, “TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER!” and mine are very similar. Have you ever thought of authoring a guest post for a similar blog? It will surely help gain publicity to your blog (my site recieves a lot of visitors). If you might be interested, email me at: gabriellelevy@yahoo.com. Thanks for your time liberty reserve - January 5, 2012 @ 6:34 pm Fantastic goods from you, man. TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER! great TEAL MARCHANDE » Blog Archive » FOLLOW ME ON TWITTER! informations. TechLifeForum - January 5, 2012 @ 7:26 pm I went over this site and I conceive you have a lot of wonderful info, saved to favorites (:. ansell lubricants - January 5, 2012 @ 10:17. sc2 strategy guide - January 6, 2012 @ 2:01 am very nice post, i certainly love this website, keep on it Photographer Raleigh NC - January 6, 2012 @ 3:53 am I want to convey my passion for your kindness supporting those people that require help with this subject matter. Your special dedication to passing the solution all through became especially important and have continually made workers much like me to get to their goals. Your warm and helpful guide entails a whole lot to me and substantially more to my peers. Thanks a lot; from each one of us. pozycjonowanie stron - January 6, 2012 @ 10:22 pm Whatˇ¦s Going down i am new to this, I stumbled upon this I’ve discovered It positively helpful and it has aided me out loads. I am hoping to contribute & help different users like its helped me. Great job. Hyun Aveles - January 7, 2012 @ 12:46 am perfect site. Owen Weitkamp - January 7, 2012 @ 1:12 am! new zealand business sale - January 7, 2012 @ 2:23 am Whats up Guru, what lure you to put up an article. This article used to be extraordinarily fascinating, particularly considering I used to be trying to find thoughts on this topic last Thursday. stron pozycjonowanie - January 7, 2012 @ 5:34 am Generally I do not read article on blogs, but I would like to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, very nice article. kaspersky discount 2012 - January 7, 2012 @ 8:43 pm Well I definitely liked studying it. This tip offered by you is very constructive for good planning. kasyno online - January 8, 2012 @ 12:14 am Thanks a lot for sharing this with all of us you really know what you are talking about! Bookmarked. Kindly also visit my web site =). We could have a link exchange arrangement between us! natural food diet - January 8, 2012 @ 5:17 am Couldn’t have said it better myself. forex goldmine - January 8, 2012 @ 5:31 am This is like my third time coming by your site. Regularly I do not make comments on, but I have to mention that this article really pushed me to do so. Really awesome article! how can I stop procrastinating - January 8, 2012 @ 10:13 am Love your blog! referencement conseil - January 8, 2012 @ 1:42 pm Hello. I am wondering if you’d be interested in doing a website link swap? I notice your blog: and my website are centered around the same topic. I’d really like to swap links or possibly guest author a write-up for you. Here is my personal contact: sarahhenel@live.fr. Make sure you contact me if you’re even remotely interested. Thanks for your time. forex - January 8, 2012 @ 2:51 pm Hey very cool blog!! Man .. Beautiful .. Amazing .. I’ll bookmark your blog and take the feeds also…I’m happy to find numerous useful information here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . . long purple bridesmaid dresses - January 9, 2012 @ 1:48 am After studing some of the articles on the blog now, and I truly like your way of blogging. I saved it to my bookmark website list and will be checking back soon. Cheers, Ben! Era Bobo - January 9, 2012 @ 10:49 am Well written article and directly to the point. Well done. ganar dinero en internet forex cargo - January 9, 2012 @ 11:19 am I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks, you cleared up some things for me! Voyage au vietnam - January 9, 2012 @ 3:45 pm I think this is one of the most vital info for me. And i am glad reading your article. But want to remark on some general things, The site style is great, the articles is really nice : D. Good job, cheers cadburys purple bridesmaid dresses - January 9, 2012 @ 4:16 pm Fantastic. I learn something new on different posts everyday. It will always be stimulating to read content from other writers. I’d prefer to share with the stuff on my site if you don’t mind. Naturally I’ll put a link on your blog, let me know if you’re interested! oil expeller suppliers - January 9, 2012 @ 7:11 pm I found your write-up occasionally, and this can be a really fantastic guide which convey quite a few data to us. I hope we are able to exchange one way links with you. Thomas Phothirath - January 10, 2012 @ 9:29 pm Hi there, just changed into aware of your blog via Google,my site is Cammie Tuorto - January 10, 2012 @ 11:10 pm I’m still learning from you, while I’m improving myself. I absolutely liked reading all that is written on your blog.Keep the tips coming. I liked it! Yasmin Pline - January 11, 2012 @ 12:28 am I savor, lead to I found exactly what I was taking a look for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye Jonsey - January 13, 2012 @ 8:06 pm I have really enjoyed reading your well written article. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. pakaian - January 14, 2012 @ 8:03 am I’m still learning from you, while I’m making my way to the top as well. I definitely love reading everything that is written on your blog.Keep the information coming. I enjoyed it! Mark - January 14, 2012 @ 10:34 am This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! Harriet - January 14, 2012 @ 10:48 am I’d like to have more info on this subject, can I ask you the sources you used to write your post? Jonsey - January 14, 2012 @ 12:51 pm I’ve read some good stuff here. Definitely worth bookmarking for revisiting. Newman - January 14, 2012 @ 2:36 pm. pozycjonowanie - January 15, 2012 @ 12:37 am I have recently started a website, the information you offer on this website has helped me tremendously. Thanks for all of your time & work. penis enlargement pills video - January 16, 2012 @ 5:03 am This is very interesting, You are a very skilled blogger. I’ve joined your feed and look forward to seeking more of your wonderful post. Also, I have shared your website in my social networks! Photography Raleigh NC - January 16, 2012 @ 5:27 am This is a great post and I really enjoyed reading it. I’ll have to check back soon to see what else is going on. Thanks! Sarah Glaspole - January 16, 2012 @ 8:16 am Looks like you have put a lot of effort in your blog, thank you for taking the time to write such useful information. Construction Software - January 16, 2012 @ 11:03 am This post made my brain tingly. You rock! ringing in ears - January 16, 2012 @ 1:44 pm. Wedding Photographer In Raleigh - January 16, 2012 @ 3:22 pm This is a great post and I really enjoyed reading it. I’ll have to check back soon to see what else is going on. Thanks! it sales leads - January 25, 2012 @ 12:11 am You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material. invest liberty reserve - January 25, 2012 @ 2:55 am Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is magnificent, let alone the content!. Thanks For Your article about FOLLOW ME ON TWITTER! – TEAL MARCHANDE . Rupert Derrig - January 25, 2012 @ 10:45 am This blog has a good content. I found this on Google search and I really enjoy reading this. I will add this to my favorites. Eusebio Beynon - January 25, 2012 @ 11:37 am This is the blog that I am looking for. The information I get were really helpful for my research. Thanks for posting a blog like this. fatherjohn3rd - January 25, 2012 @ 3:50 pm this was amazing. I dought if anybody else has the same information. thank you very much
http://tealmarchande.com/follow-me-on-twitter/
CC-MAIN-2017-26
refinedweb
5,528
74.29
Continuous Integration (CI) Best Practices with SAP – Generic Project Continuous Integration (CI) Best Practices with SAP – Generic Project Part 4.1 – Configuring the CI system for Maven-based generic Java project. This generic project outlines a CI process for a pure Java project without any deployment. The build tool is Maven, which must be installed on a local developer host. The general procedure is as follows: first, create a project in Gerrit together with the first branch, the main integration branch master. Clone the (initially empty) repository on a local developer workplace, commit the code and push it as a first commit to Gerrit. Next use Jenkins to configure a voter build, which builds the commit before it is merged into the master branch. Finally implement the CI build. Prerequisites - A developer workplace (PC) with the following installations: - Java JDK - Git - Maven - A running Git/Gerrit instance - A running Jenkins master and a Jenkins build slave - A running Nexus with at least one snapshot and one release repository Eclipse as development environment is commonly used but not required, and considered a prerequisite. Basic Project Setup Procedure Use a browser to access the Gerrit front end on port 8080. Log in as your admin user. Go to Projects > Create New Project. Enter the project name HelloWorldand select Create initial empty commit. This automatically creates the masterbranch. Enter Rights Inherit From: CI-Projects. Alternatively, you may follow the steps for command line-based creation as described in the Gerrit documentation: Create an initial clone of the project on your PC and check out the masterbranch. On your local PC, to push commits to Gerrit, add a commit hook into the <Git repository root>/.git/hooksdirectory. You can obtain this from http://<hostname of Gerrit>:8080/tools/hooks/commit-msg. Every developer who plans to do commits against Gerrit needs this hook. Add the initial project files into the Git workspace. For example, add the following files: <Git repository root>/pom.xml <Git repository root>/src/main/java/company/org/App.java <Git repository root>/src/test/java/company/org/AppTest.java The content of the files is available in the appendix. Create a commit and push: git add . git commit -m "Initial version of HelloWorld" git push origin master:refs/for/master In Gerrit, the commit should be listed under My > Changes. Assign the commit a Code-Review+2and select Submit. Now the commit is merged into the master branch. Jenkins Voter Build Configure a Jenkins voter build for this branch. The global configurations are already done, so now we only need to define the job. Procedure Open the Jenkins front end. Select New Item, then Maven project. Enter a project name, for example VO_HelloWorld_master_build. The name only identifies the job, that is, it plays a technical role. But keep in mind that over time you might have to differentiate many jobs by Gerrit project name, branch, or other purposes (such as using the prefix VOfor “voter build”). You may want to establish your own naming convention. In the general section of the project configuration, select Restrict where this project can be run and enter the label that you have assigned to the slave, in this case builds. In the Source Code Management section, select Git and enter the following data: Click on Advanced…: In the Build Triggers section, select Gerrit Event. In the Gerrit Trigger section, choose the server which you already have defined in Jenkins. Add a new trigger by clicking on Add > Patch set Created. In the Gerrit Project pane, enter HelloWorldas project name and masteras branch name, both with type plain. In the Build Environment section, select Delete workspace before build starts. This ensures that you always have a clean build without the risk that it is polluted by the build before. In the Build section, add clean verifyas Goals and Options. The Jenkins project is now ready to listen for Gerrit events. Jenkins Gerrit Trigger Plugin From the local sources on your PC, perform a small change, commit, and push it. Once the change reaches Gerrit, a Jenkins build is triggered. Depending on the build status, the code review is rated -1 or +1. You may want to review the change with +2 and press Submit to merge the change into the masterbranch. Jenkins CI Build The CI build reacts on new commits pushed into the branch in Git, that is, an integration with Gerrit is unnecessary. Instead, you can define a time schedule or manually trigger the build at any time. Procedure Open the Jenkins front end and go to New Item. The CI build differs from the voter build only in the details how it is triggered. Hence, enter CI_HelloWorld_master_buildas name, select Copy existing item and enter VO_HelloWorld_master_build. In the Source Code Management section, click on Advanced… and clean the field Ref spec. Enter masteras Branch Specifier. In the Build Triggers section, select Poll SCM and enter a pull frequency. In order to have immediate build results after a merge, every two minutes could be an appropriate value. When you submit a change into the masterbranch in Gerrit, you see this job start running after some time according to the pull frequency. Artifact Upload to Nexus In the current setup, the build results are stored only in the build node’s workspace. However, you may need to reuse them: you might add test steps or you might have other Maven projects that depend on this project. In most examples of our guide, we will use the Jenkins archiving feature to temporarily store artifacts instead of a snapshot repository in Nexus. The upload to Nexus is usually used by for released versions only. Nevertheless, we demonstrate here the Nexus upload on a snapshot version to demonstrate the principle. Procedure In your development project, add the following section into the project’s pom.xmlfile directly under the <project>node: <distributionManagement> <snapshotRepository> <id>nexus1</id> <url><snapshot repository url on Nexus></url> </snapshotRepository> </distributionManagement> The id nexus1refers to the credential entry in the maven installation’s settings.xmlon the Jenkins node machine. You can fetch the URL of the snapshot repository from the Repository overview page of the Nexus front end. In Jenkins, go to the build job of the project and open the Configure page. In the Build section, add clean deployas goals. When you do an additional commit on your project and push it, you should be able to see the artifacts in Nexus uploaded from the build. Appendix App.java package company.org.halloworld; public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } } AppTest.java package company.org.halloworld;() { assertTrue( true ); } } pom.xml <project xmlns="" xmlns: <modelVersion>4.0.0</modelVersion> <groupId>company.org</groupId> <artifactId>halloworld</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>halloworld</name> <url></url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <!-- <distributionManagement> <snapshotRepository> <id>nexusCIProcess</id> <url>http://<your nexus host>:8081/nexus/content/repositories/snapshots</url> </snapshotRepository> </distributionManagement> --> </project> Next Steps Updated 12/19/2017 Contributors Provide Feedback
https://www.sap.com/belgique/developer/tutorials/ci-best-practices-generic.html
CC-MAIN-2018-34
refinedweb
1,187
57.77
In perl, a closure is implemented as an anonymous subroutine. You can think of it as something of a function generator. sub greet { my $salutation = shift(); return sub { print "$salutation " . shift (). "\n"; }; } my $a = greet( "Hello" ); my $b = greet( "Bonjour" ); So now if you call &$a("World"), "Hello World" will print. If you call &$b("La Monde"), "Bonjour La Monde" will print. Closures are useful if you want to bind a particular value of a lexical variable to a function. The important bit in eric+'s program above is the `my' on the second line, which makes $whom a lexically-scoped variable. If it were changed to `local' (which introduces a new binding of a dynamically-scoped variable), the calls `&$a("World")' and `&$b("La Monde")' would produce warnings because no variable named `$salutation' would be in scope when they were called. Closures are common in functional languages; Perl is such a mongrel that it could be considered a functional language. An example (in Scheme) paralleling eric+'s example above is: (define (greet salutation) (lambda (whom) (display (string-append salutation " " whom "\n")))) (define a (greet "Hello")) (define b (greet "Bonjour")) (a "World") ; prints "Hello World\n" (b "la Monde") ; prints "Bonjour la Monde\n" Closure is not when your ex turns up at your apartment to collect some of their things they forgot to pick up before and you end up in bed together, waking up the next morning with the two of you in a state of serious emotional hangover Contrast (topological) interior. There's the box of memories I have which is basically a bunch of holiday snapshots. Stuff I did with friends. I look through them now and again, when I run out of images. Halfway up a mountain in a tent which is being washed away by heavy rain and held up by giggling shouting people in wet pyjamas, that kind of thing. Most of them have audio, mainly laughter tracks, background music. Some are spectacular. Some are just funny. Then there's the box I guess a lot of people have. The one with old letters. The one you keep at the bottom of a closet or in a drawer nobody uses. Under the bed is too obvious. I put them there and I almost never look at them unless I come across the box while in search of something else. When this happens, I am surprised at how little they move me. Sometimes I wonder why I keep all this old junk around. Is it necessary to have a record that you felt certain emotions, or did certain things? Does it just fill up space that could be used to store new material? Or is it a concrete lid covering the well of the vast black pit of nothingness that you might fall into, without it? A sample. Sometimes strangers bring surprises, and unlooked-for gifts. Gallant, he was. There went my preconceptions. Dark handsome American Jewish intellectual, I thought he was bound to be full of arse. We were talking about Baudrillard because I noticed the title of his book, and his face suddenly lit up and he said in mid-sentence: "Would you like a copy?" Startled, I nodded, and he got up, clambered over the table crushing us in, leapt off and disappeared in the direction of the bookshop. I looked at Jo, frowning puzzled: she grinned and said: "I think he likes you." Nobody had stolen me a book in so long. I carried it about for days, revelling in its clean shiny edges. Someone new to talk to. Then he went and spoilt it by inviting me out to dinner, a blatant request for more. I declined, not being vacant or interested. He pointedly sat on the other side of the coffee bar after that and ignored me. Angry with him for even asking, I ignored him back. All I wanted was someone to swap amusing banter with, catch the odd movie with. Casual, relaxed, pleasant. The kind of thing that keeps the days rattling along comfortably. He seemed to want mess and confusion and intensity. Yet I read an essay of his once: it was a surprisingly calm and orderly piece of work. Dry, even. Very unlike mine which back then were full of Sturm und Drang, passionate support or scathing denial. Pen picked steaming off the page, words charred into the whiteness. I often saw my head back then as a tindery dry place, the Australian Outback, maybe. Flames easily sparked and spreading like wildfire. I was not vacant, but I was not exactly engaged. Busy, obsessed, working all night sometimes, love switched to low maintenance. I felt at the time that I didn't understand sex. A short messy physical procedure, what's the big deal? Three years into a relationship, there was nothing to make me want to be bothered. Tiring. All that getting undressed and dressing up again. Having to work yourself up into it, wanting nothing better than to be left alone, to let out the irritated sigh which is pushing at the inside of your face, causing you to be wearing The Wrong Expression. Batter it down. Put on a smile, close your eyes, accept the role and play it. Wondering how much of his response is acting too. Wondering what happened to desire. I began to start fights about nothing, or about something in the past. Obvious now, when I look at it, what I was up to. Trying to trigger the intensity that leads to desire, desire being the element that connects the short messy physical procedure with something else. Thinking that if you could not read, it would still be possible to sit quietly looking at every page in a book, if you were required to. Idly noting: that black squiggle looks like a caterpillar, that one like a snake, this one like a bus queue full of people. But basically bored. Wanting it over, sneaking glances at the clock. Wondering what the point is. Tears on both sides and then violence. The passionate making-ups that I had unconsciously envisaged never happened: wrong kind of intensity. Too tired, too drained by the floods of fucked-up emotion weathering us, eroding our skin to red rawness. Friends noticing the black eye that was probably all my fault anyway, and saying nothing, but dragging me out to go clubbing. In clubs I would find myself searching the room for him. All the people somehow made the room seem emptier. Looking through the spaces between bodies, fidgeting in my seat, scanning, scanning for anything that might break the mould of boredom and disinterest. It's dried up and dead, he said. We should finish it. I thought so too, so why did I feel like screaming and begging to keep it? Separated. Ghost limb still present despite the public appearance of a neatly healed stump. Friends rallying round, slaps on the back, the chink of glasses. Saying what they think you want to hear. "Yer well rid I reckon luv. Game of pool, eh?" Keeps you going while you're stumbling around, stumpy. Like an artificial leg: fills the gap but doesn't do much for the neurological damage. Inside, attempting to find answers. Does desire always have to end, jesus god if something this perfect could go wrong then there's no hope for anything, blah de blah de blah in endless circles. Boring yourself sick. Bad things happen, we wonder why. Faced with them I find myself flipping through selections of approaches, looking for an action sequence. The Zen approach: these things happen and it's nobody's fault and you just have to calmly wait them through, get on with it, move on. The taking-all-the-responsibility approach: it's all my fault, if only I hadn't done x or y or z, I Must Change I Am So Crap. The blame approach: if only he had done x or y or z to make me want him. The chicken-and-egg approach: did all the x start the y? The irritable approach: aw hell it's all a load of bollocks now, forget it. But you never quite do, not until much later. These sequences replay endlessly but choppily, never finding the groove, the seamless perfectly mixed edit to unite the thread in magical flow. That would explain everything, provide closure, end the project. Then years later you open that box, and there's nothing in it but dry paper, crumpled drawings, old photos. You look with idle curiosity but no pain: perhaps a little nostalgia, for who you used to be, maybe. And realise that closure has just quietly taken place, when you were not looking: that this is how it works. neil's definition of a closure is accurate, but what's missing is the why? Programmers in languages that emphasize closures swear by them. A lot of programmers don't even know what they are, and maybe a larger number understand closures, but don't really understand their utility. Let me propose an expanded definition: A closure is a function and its environment that can be passed into another function The important part here is the environment which consists of all variables defined at the scope of the closure creation. The essential functionality is both a form of encapsulation and abstraction. Observe this Ruby example: def find_birthdays_in_range(min,max) birthdays = [ "1970-06-15", "1975-08-13", "1939-03-21", "2001-12-01" ] birthdays.find_all { |birthday| birthday > min && birthday < max } end So essentially there are 3 functions here that are called from within each other. The third and final one is the closure defined by the ruby block in curly braces, it accepts one parameter called birthday. For easy reference, refer to these function as follows: A : find_birthdays_in_range B : find_all C : anonymous block Now normally in a lexically-scoped language (almost all of them nowadays) a function can only access parameters passed into it directly. But in this case function C has access to variables defined in function A. That's where the encapsulation comes in, function B never knows anything about min and max. Without closures then function B would have to receive those variables as parameters, and in turn pass them to the anonymous block. But then the generality of function B would be destroyed—it would accept exactly 2 parameters and pass them through to function C. The problem is that those 2 parameters don't really mean anything to find_all. find_all is meant to be able to match members of an array by arbitrary criteria. Function C could just as well reference no variables or 20 variables in determining whether an element of birthdays matches its criteria, and then what? min max find_all Without closures it's not really sane to use this structure. Most likely in Java or PHP you would just make find_birthdays_in_range do everything itself. Instead of calling find_all on the array, it would loop through the array itself and gather the matching birthdays manually. There's really nothing wrong with that approach, but you end up writing a lot of the same looping and collecting code over and over. That's where the abstraction comes in. Closures give you the opportunity to write much more general functions. find_birthdays_in_range find_all can find members of an array that match literally any criteria you can express in code, and that's just a relatively basic function that uses closures. You can write any function to call a closure from within, thus generalizing the function. Some examples from the ruby standard library: In short, closures expand the power of abstraction available to functions. The sticker should say something like, "Warning: Do not under any circumstances listen to this song while depressed. Bodily harm could result." And then at the end of the song it should warn you again, just in case it made you depressed, to not under any circumstances listen to "Am I Alone In Here" next, or within six months of any relevant tragedy or psychological event or diagnosis. "Closure" is moving, like an ecstatic Opus Dei member drawing blood is moving; but "Am I Alone In Here" is such an amazing piece of artistry that people have been known to listen to the end and then wonder where they got that gun and how long it's been between their lips. Perhaps really good art sometimes does need a warning. Clo"sure (?, 135), n. [Of. closure, L. clausura, fr. clauedere to shut. See Close, v. t.] 1. The act of shutting; a closing; as, the closure of a chink. 2. That which closes or shuts; that by which separate parts are fastened or closed. Without a seal, wafer, or any closure whatever. Pope. 3. That which incloses or confines; an inclosure. O thou bloody prison . . . Within the guilty closure of thy walls Richard the Second here was hacked to death. Shak. 4. A conclusion; an end. Shak.. © Webster 1913. Log in or registerto write something here or to contact authors. Need help? accounthelp@everything2.com
http://everything2.com/title/Closure?showwidget=showCs621721
CC-MAIN-2016-26
refinedweb
2,189
73.17
This is part of a series I started in March 2008 - you may want to go back and look at older parts if you're new to this series. Where we left off last time, we'd just barely scratched the surface of what it will take to self-host the Scanner. This time we'll keep digging into that. I will skip or gloss over fixes to some bugs etc., and focus mostly on the bits that are filling in intentional omissions from earlier that are now finally coming back to bite us, with the exception of some particularly interesting (to me at least) bugs. One of the bugfixes were actually pushed out with the previous branch. See e6ae4ba - this is worth at least a cursory note as it got the order in which we determined the size of an object instance vs. where I actually counted up the number of immediately visible instance variables wrong. Ouch. By the time this version is out, I'll also have merged a bunch of fixes to make the code work with Ruby 1.9, finally. But back to the Scanner code. This part ended up a lot more convoluted than I'd planned. I've skipped over some of the details of my debugging, as it got tedious to write and probably twice as much to read, with lots of jumping back and forth. Th For the purposes of this series, I've added features/inputs/scanner4.rb which is a variation of the Scanner code and some minor test code that I will make work in this article. I'll walk through a few issues with it at the end. In scanner.rb we define Scanner::ScannerString. ScannerString is "just" a subclass of String that allows us to have the scanner attach a Position to a token, which again allows us to add position information to the syntax tree for error reporting and debugging. For this part we will lift ScannerString out of the Scanner class as embedded classes is not yet supported. The next issue is our lack of attr_accessor. So we end up with this: class ScannerString < String # Instance variables in inherited classes did not work def initialize @position = 0 # Note: It's still awkward to use "nil", so we cop out for now. end # "=" was not handled correctly for vtable thunks? def position= newp @position = newp end def position @position end end Compiling even this, however, proves a challenge, as per the inline comments above. The latter was just a trivial issue with the name handling. Test cases in 8cd9c18 and a one character fix (!) in 55b9d23 The former was trickier - I messed up in some subtle ways when I added the instance variable support that I missed by not testing with instance variables in sub-classes. I added a test case for this in e828033 In fixing this, I muddied things up a bit, and I've been too lazy to untangle the changes, as while tracking down these issues, I added some initial support for #inspect and getting hold of class names. We'll finish up that next, to not leave changes hanging. In ca6f420 there are some minor changes in GlobalScope that follows from the changes in ClassScope - I'll ignore those - read the commit. The meat is in ClassScope in scope.rb (and later we'll look at changes to compiler.rb): @@ -186,14 +194,17 @@ class ClassScope # # slot 0 is reserved for the vtable pointer for _all_ classes. # slot 1 is reserved for @instance_size for objects of class Class - CLASS_IVAR_NUM = 2 + # slot 2 is reserved for @name + CLASS_IVAR_NUM = 3 - def initialize(next_scope, name, offsets) + def initialize(next_scope, name, offsets, superclass) @next = next_scope + @superclass = superclass @name = name @vtable = {} @vtableoffsets = offsets - @instance_vars = [:@__class__] # FIXME: Do this properly + @ivaroff = @superclass ? @superclass.instance_size : 0 + @instance_vars = !@superclass ? [:@__class__] : [] # FIXME: Do this properly @class_vars = {} end The bump in CLASS_IVAR_NUM is due to adding Class#name as mentioned above. More interestingly we now rectify a long standing omission: The scope chain did not keep track of superclass. We could look it up separately as needed, I guess, but we did not do that either. We now pass in a scope object that represents the super class. We then assign @ivaroff to represent the offset that instance variables for this class start at. This bug is well into the "embarrassing" category. Without this, when we subclass a class, and add instance variables, the instance variables will get overlapping offsets, and overwrite each other. Oops. Lastly, we set @instance_vars to start with @__class__ if there is no super class provided, to guarantee that we have a place to stash the class pointer (we could alternatively do this by setting @ivaroff to 1 in the same situation). Next we ensure @ivaroff is included when we calculate the instance size, so we actually allocate enough memory for the instances too, unlike before (double-oops...) @@ -210,7 +221,7 @@ class ClassScope end def instance_size - @instance_vars.size + @instance_vars.size + @ivaroff end Lastly, we ensure we return the right offset from the instance pointer in ClassScope: @@ -239,7 +250,14 @@ class ClassScope offset = @instance_vars.index(a) add_ivar(a) if !offset offset = @instance_vars.index(a) - return [:ivar, offset] + + # This will show the name of the current class, the superclass name, the instance variable + # name, the offset of the instance variable relative to the current class "base", and the + # instance variable offset for the current class which comes in quite handy when debugging + # object layout: + # + # STDERR.puts [:ivar, @name, @superclass ? @superclass.name : "",a, offset, @ivaroff].inspect + return [:ivar, offset + @ivaroff] end This isn't quite enough. We also need to update compile_class in compiler.rb: First we obtain the pointer to the super class, and use that to properly initialize the class scope: @@ -635,7 +635,9 @@ class Compiler def compile_class(scope, name,superclass, *exps) @e.comment("=== class #{name} ===") - cscope = ClassScope.new(scope, name, @vtableoffsets) + superc = @classes[superclass] + + cscope = ClassScope.new(scope, name, @vtableoffsets, superc) Note that there's another shortcut here: Ultimately we need to compute this too, as people can do nasty stuff like dynamically picking a class, assigning it to a constant, and subclassing that, so even if we have something that looks like a class name, what we actually have is actually an expression that evaluates to the Class object of the class that should be the superclass. I don't remember if the parser will even allow that at the moment, and I'm not in the mood to fix even the "simple" case of someone assigning stuff to constants and expecting me to treat it as a class, so we'll continue to ignore this for now and stumble over it later. Then we fix up the assignment to the Class instance for the new class. The inline comment says it all, really: @@ -679,7 +681,17 @@ class Compiler compile_exp(scope, [:assign, name.to_sym, [:sexp,[:call, :__new_class_object, [cscope.klass_size,superclass,ssize]]]]) @global_constants << name - compile_exp(cscope, [:assign, :@instance_size, cscope.instance_size]) + # In the context of "cscope", "self" refers to the Class object of the newly instantiated class. + # Previously we used "@instance_size" directly instead of [:index, :self, 1], but when fixing instance + # variable handling and adding offsets to avoid overwriting instance variables in the superclass, + # this broke, as obviously we should not be able to directly mess with the superclass's instance + # variables, so we're intentionally violating encapsulation here. + + compile_exp(cscope, [:assign, [:index, :self, 1], cscope.instance_size]) + + # We need to store the "raw" name here, rather than a String object, + # as String may not have been initialized yet + compile_exp(cscope, [:assign, [:index, :self, 2], name.to_s]) But all of that is not enough to fix our test-case ( features/inputs/ivar.rb) as it turns out - now the instances variables of Foo are undefined in instances of Bar, since Bar#initialize does not call super (nor have we implemented support for super yet...). We need to patch #puts to handle our "fake" nils (that are still actual null values), which once again demonstrates that I need to make a decision on exactly what to do about this (in 10d7c6e): --- a/lib/core/object.rb +++ b/lib/core/object.rb @@ -49,8 +49,12 @@ class Object i = 0 while i < na %s(assign raw (index str (callm i __get_raw))) - raw = raw.to_s.__get_raw - %s(if raw (puts raw)) + if raw + raw = raw.to_s.__get_raw + %s(if raw (puts raw)) + else + puts + end Since parts of this made it into the previous commits. e977bfc adds test cases, and this: --- a/lib/core/class.rb +++ b/lib/core/class.rb @@ -40,6 +40,10 @@ class Class ob end + def name + %s(__get_string @name) + end + As mentioned earlier, we store the name "raw" to avoid bootstrap issues with String. Another insidious little bug reared its head when dealing with the debugging output. The method name needs to be the second argument, since the first argument is our "hidden" place to store any block that gets passed to a method: --- a/compiler.rb +++ b/compiler.rb @@ -522,7 +522,7 @@ class Compiler if !off # Argh. Ok, then. Lets do send off = @vtableoffsets.get_offset(:__send__) - args = [":#{method}".to_sym] + args + args.insert(1,":#{method}".to_sym) warning("WARNING: No vtable offset for '#{method}' (with args: #{args.inspect}) -- you're likely to get a method_missing") #error(err_msg, scope, [:callm, ob, method, args]) end With that out of the way, our failure to handle "send" can now easily be made to produce more useful output for things like this: class Foo end f = Foo.new f.bar As of 7fc23ae840 you get something like this, correctly identifying the class name and method: WARNING: __send__ bypassing vtable (name not statically known at compile time) not yet implemented. WARNING: Method: 'bar' WARNING: symbol address = 0x8a36750 WARNING: self = 0x8a36740 WARNING: class 'Foo' And a first pass on a default #inspect in 8c74cd6. Clearly adding cleaner support for string formatting also needs to go on the big list of outstanding items: def inspect %s(assign buf (malloc 20)) %s(snprintf buf 20 "%p" self) %s(assign buf (__get_string buf)) "#" end Like ScannerString, we'll lift Position out of Scanner. We also avoid using Struct, and so get to write a few lines extra. Thanks to the changes above, we now get semi-useful debugging output, and get the dubious pleasure of chasing down missing piece after piece. With my "scanner test in progress" it warned of a missing String#empty? used in Scanner#fill. I added String#empty in 334902c. Next up, I get a method missing for ==. On adding the class name to the method_missing output, I get Class#==, which makes no sense. But String#length is empty, so this represents garbage where we don't properly clear the return value for an empty method. I added a first pass at String#length in c3eac1f. Next up we're warned about Fixnum#getc?!? Turns out we call @io.getc in Scanner#get, and we stubbed out STDIN as 0 a while back... Changing it to IO.new (in 66e976f) suddenly gets us somewhere: My test code waits for input! echo Foo | /tmp/scanner4 gave me a "send warning" for Fixnum#chr which I added in 186986f Repeating this gave me method missing for String#[]. And here we'll spend a little bit more time, as there are (minor) complications ahead. First lets look at a not particularly inspired first version of String#[] in 7bc84e6: --- a/lib/core/string.rb +++ b/lib/core/string.rb @@ -16,6 +16,23 @@ class String %s(assign @buffer 0) end + def [] index + l = length + if index < 0 + index = l + index + if index < 0 + return nil + end + end + + if index >= l + return nil + end + %s(assign index (callm index __get_raw)) + %s(assign c (bindex @buffer index)) + %s(__get_fixnum c) + end + First of all, we need bounds checking. String#length currently counts, which is obviously stupid, but we'll sort that out later. It's really only the last 3 lines we care about here. How do we get a single byte out of our strings? Well, so far we can't easily do that - we haven't exposed any way of addressing single bytes. Above that's fixed by introducing bindex as a byte-oriented alternative to our 32-bit (or in theory pointer-sized - if/when we add a 64 bit target, it needs to be 64-bit) index primitive. All the code does is obtain the raw index value, use it to obtain the raw byte value, and then obtain a Fixnum (note, we're still following Ruby 1.8 behaviour here - 1.9+ returns a String -, which we probably should stop with, given that the compiler itself is now updated to support 1.9; but devil you know and all that). Apart from adding it to the @@keywords set in compiler.rb, we add this, which is a direct parallel to compile_index apart from not scaling the value, and the type we return. If we need more scales we might want to create a more generic version (also in 7bc84e6) + # Compiles an 8-bit array indexing-expression. + # Takes the current scope, the array as well as the index number to access. + def compile_bindex(scope, arr, index) + source = compile_eval_arg(scope, arr) + r = @e.with_register do |reg| + @e.movl(source, reg) + source = compile_eval_arg(scope, index) + @e.save_result(source) + @e.addl(@e.result_value, reg) + end + return [:indirect8, r] + end This again requires some changes to emitter.rb to add support for loading :indirect8: --- a/emitter.rb +++ b/emitter.rb @@ -234,6 +234,8 @@ class Emitter return load_address(aparam) when :indirect return load_indirect(aparam) + when :indirect8 + return load_indirect8(aparam) when :arg return load_arg(aparam,reg || result_value) when :lvar @@ -325,6 +327,13 @@ class Emitter movl(src,"(%#{dest.to_s})") end + def load_indirect8(arg) + movzbl("(#{to_operand_value(arg,:stripdollar)})", :eax) + # FIXME: gcc includes this second movzbl; why is it needed? + movzbl(:al,:eax) + :eax + end + This leads us further down the rabbit hole: A method missing for String#position.... Which should be Scanner#position, accessed via self.position in Scanner#get. I wish I'd taken better notes of how I tracked down this bug, but it involved lots of printf type debugging making use of our now available Class#name etc., as well as pouring over the asm output. The problem is actually triggered in Scanner#fill, which in my test version looks like this: def fill if @buf.empty? c = @io.getc c = c.chr if c @buf = c ? c.to_s : "" end end Looks innocent, because it is. However, the asm output is not so innocent and reflects how tricky getting register allocation right is. The below fragment reflects just @buf = c ? c.to_s : "". # RA: Allocated reg 'ecx' for c # [:lvar, 0, :ecx] movl -8(%ebp), %ecx testl %ecx, %ecx je .L189 Above we've loaded c and we're jumping to .L189 if false. Now we execute c.to_s: # callm :c.:to_s subl $8, %esp movl $2, %ebx pushl %ebx # RA: Already cached 'ecx' for c movl %ecx, 4(%esp) movl $0, 8(%esp) popl %ebx movl (%esp), %esi movl (%esi), %eax call *384(%eax) # Evicting self addl $8, %esp # callm c.to_s END jmp .L190 At the end, note that we're marking self as evicted from %esi where we put it. Now for the "else" part, that just returns an empty string: .L189: subl $4, %esp movl $1, %ebx movl $.L0, %eax movl %eax, (%esp) movl $__get_string, %eax call *%eax addl $4, %esp # RA: Allocated reg 'esi' for self # [:arg, 0, :esi] movl 8(%ebp), %esi Hang on? At the end, this reloads self into %esi, which in itself isn't a problem. The problem is that since the very next label, .L190, reflects a merge of two control flows, even though self was just reloaded, unless we know that self will be present in %esi when leaving the "if" arm above too, the code below is broken: .L190: movl %eax, %ecx # RA: Already cached 'esi' for self movl %ecx, 8(%esi) ... because it assumes self is cached. And in fact, it is totally broken: %esi will reflect the class of c, because of the c.to_s call that is the last part of the ternary-if arm above. There are several ways of fixing this, one of them being to try to prove which registers are safe across both control flows. The other, the brute-force approach, is to assume all bets are off and start afresh. The change is trivial, so you can see it in 549e091 echo Foo | /tmp/scanner4 Got: 70 (PEEK) WARNING: __send__ bypassing vtable (name not statically known at compile time) not yet implemented. WARNING: Method: 'comma' WARNING: symbol address = 0x8580510 WARNING: self = 0x85802e0 WARNING: class 'Scanner' Method missing: Class#== We don't have a method comma. So let's break out the debug output with ruby compiler.rb --norequire --parsetree: (defm position () (let (pos __env__ __tmp_proc) (assign pos (callm Position new (@filename (comma @lineno @col)))) pos ) ) The relevant part corresponds to: pos = Position.new(@filename,@lineno,@col) So let's add a test case to parser.feature: + | "Position.new(@filename,@lineno,@col)" | [:do, [:callm, :Position, :new, [:"@filename", :"@lineno", :"@col"]]] | | The problem here is in treeoutput.rb, which badly needs more comments... The code attempts to simplify the parse tree created by the operator precedence parser, in order to make it easier to work with later. The relevant part is this, which triggers on method calls etc.. I've included the one line fix as a diff. It's in 13368e0: elsif la and leftv[0] == :callm and o.sym == :call block = ra && rightv[0] == :flatten && rightv[2].is_a?(Array) && rightv[2][0] == :block comma = ra && rightv[0] == :comma - args = comma || block ? flatten(rightv[1..-1]) : rightv + args = comma || block ? flatten(rightv) : rightv args = E[args] if !comma && !block && args.is_a?(Array) args = E[args] if block @vstack << leftv.concat(*args) else @vstack << leftv + args end The hint to the location comes from seeing the "comma" reference. If we add a --dont-rewrite flag and re-run ruby compiler.rb as above, we get this: (assign pos (call (callm Position new) (comma @filename (comma @lineno @col)))) So the rewrite fails to rewrite the last part. The bug probably stems from forgetting that rightv in the above case refers to the entire argument list. The next problem up is a method missing for Class#==, which occurs in Scanner#get where I marked with "(1)": def get fill pos = self.position # (2) ch = @buf.slice!(-1,1) @col = @col + 1 # (1) if ch == "\n" @lineno = @lineno + 1 @col = 1 end So at (1), ch is of object Class. Since we get ch from @buf.slice!(-1,1) above, that's where we need to look. The immediately obviously reason is that String#slice! was not implemented at all. It is in 5133315 which I'm not in the mood to walk through (but do feel free to ask in the comments if anything is unclear) - it's virtually guaranteed to be possible to clean up. The only thing I want to mention is __copy_raw, which is an alternative to __set_raw that will copy the raw buffer instead of just setting the pointer: def __copy_raw(str,len) %s(assign len (callm len __get_raw)) %s(assign @buffer (malloc len)) %s(memmove @buffer str len) end In the above commit I've also included String#== as that is the "next one out" and quite obviously so from the earlier error. The one thing to worth noting about that, is that "!" is not implemented, and that I also added an Object#true as a workaround. A shameful hack. Next we need Object#nil?, because "!" does not work, and so a "!" occurrence in Scanner#get was changed to #nil? for the test code. Since we've already run into problems with register allocation, I'm not going to go into a lot of detail about the debugging here. Suffice to say that given that we're not actually calling "#position" on what should be a Fixnum, it was time to break out the assembly source, and look at what was actually being called. It was quickly clear that the wrong value was in the register. I decided it was time to add some rspec tests for regalloc.rb, and you can find the first set in 9bfee76. That didn't reveal anything, and I had to start digging into #with_register. The test case that reproduces the problem is in 8dcd18b together with the one line fix. The problem turned out to be that #with_register calls evict on a register found in the cache, and then hands the register out, without taking into account that evict put the register back on the free list. Next is another case of the wrong value being returned. Going over assembly output again, I could find no obvious register allocation issue. Next up was peppering some puts some_object.class.name around to see where the objects got confused, and this let to compile_return. This is likely indirectly a regression caused by the register allocation: As it turns out, previously, we've not used the return statement other than in cases where it was not strictly necessary, as the last computation left the result in %eax. But this is substantially less likely after introducing the register allocation. #compile_return simply did not ensure the result of the evaluation of its argument would be saved to `%eax: def compile_return(scope, arg = nil) - compile_eval_arg(scope, arg) if arg + @e.save_result(compile_eval_arg(scope, arg)) if arg @e.leave @e.ret [:subexpr] And there we are... I'll just briefly mention some remaining problems. First of all, I found a bug in string interpolation, that I'll likely fix separate from the following articles, unless it proves particularly interesting: def inspect # Works: # puts self.lineno # puts self.filename # FIXME: Seg faults # "line #{self.lineno}, col #{self.col} in #{self.filename}" # FIXME: Including self.lineno or self.col seg faults: "line #{@lineno}, col #{@col} in #{@filename}" end Secondly there's this: # FIXME: += translates to "incr" primitive, which is a low level instrucion @col = @col + 1 As above, I might fix that separately. For now I considered the workaround the most expedient way of getting further. Lastly there's this horrific piece: # FIXME: ScannerString is broken -- need to handle String.new with an argument # - this again depends on handling default arguments s = ScannerString.new r = ch.__get_raw s.__set_raw(r) This obviously needs to be fixed. The issue is that a proper fix it requires handling default arguments, as well as super so that ScannerString as a subclass of String can pass on the string argument rather than set it after the fact (I could have hidden the #__get_raw and #__set_raw bits in ScannerString, but that would just have obscured the problem) Next we'll deal with the issue above, of default arguments and super. Then in the following part, we'll be looking at the next step towards compiling a test program that uses the compiler code to parse s-expressions, which will be to get Scanner#expect to work.
https://hokstad.com/compiler/36-scanning-for-problems
CC-MAIN-2021-21
refinedweb
3,855
72.26
package aglo; public class test { /** * Describes a : * 5 Line 5 column snake-like algorithm * (0,0)(4,4)- Line 1 and countdown 1 Difference between rows 4 * (1,0)(4,3)(0,1)(3,4)- Line 2 and countdown 2 Difference between rows 3 * (0,2)(2,4)(1,1)(3,3)(2,0)(4,2)- The first 3 rows and countdown 3 Difference between rows 2 * (3,0)(4,1)(2,1)(3,2)(1,2)(2,3)(0,3)(1,4)- The fourth row and countdown 4 Difference between rows 1 * Section 5 behavior segmentation line * According to the above description, obtain the following algorithm */ /** * Description of second : * dao Variable functions : * The main calculation downward diagonal coordinate values . * For example, :5 Line 5 columns * { (0,0) -- Known as line 0 (1,0)(0,1) -- Known as line 1 (0,2)(1,1)(2,0) -- Known as line 2 (3,0)(2,1)(1,2)(0,3) -- Known as line 3 }--- All coordinates on the diagonal (0,4)(1,3)(2,2)(3,1)(4,0)--- Here called diagonal 4 { (4,1)(3,2)(2,3)(1,4) -- Known as line 5 (2,4)(3,3)(4,2) -- Known as line 6 (4,3)(3,4) -- Known as line 7 (4,4) -- Known as line 8 }--- Downward diagonal all coordinates dao The maximum value of the variable is line * Column Get all the coordinates of the diagonal values by dao variables and temp Variable functions */ /** * @param irow Line * @param icol Column * @param sheLength Sections snake segment, which is line with diagonal */ public void sheAglo(int irow,int icol,int sheLength){ int row = 0,col = 0; int ban = (sheLength-1)/2+1; int array[][] = new int[irow][icol]; int m = 1,num = ban - 1; int dao = irow*icol; for(int i=0;i<ban;i++){ row = col = i; int temp = dao-i;// The first n rows downward diagonal values from dao-i Start if(i%2==0){ // Handling double-row /** * (0,0) * (0,2)(1,1)(2,0) * Characteristic is the increment, decrement column rows */ while(col>=0){ System.out.print("["+(i-col)+"]["+(col)+"]("+m+"),"); if(i!=ban-1){// This is the diagonal System.out.print("["+(i-col+num)+"]["+(col+num)+"]("+(temp++)+"),"); } array[i-col][col] = m; dao--; col--; m++; } }else if(i%2!=0){// Handle single-line /** * (1,0)(0,1) * (3,0)(2,1)(1,2)(0,3) * Characteristics are diminishing, incrementing column rows */ while(row>=0){ System.out.print("["+(row)+"]["+(i-row)+"]("+m+"),"); if(i!=ban-1){ System.out.print("["+(row+num)+"]["+(i-row+num)+"]("+(temp++)+"),"); } array[row][i-row] = m; dao--; row--; m++; } } num--; System.out.println(); } } public static void main(String args[]){ test test = new test(); test.sheAglo(6,6,11); } } The algorithm can only support the rows, columns, the same matrix. References 1: In describing the algorithm before the 5 * 5 to see the following table: The above table is easy to see that law. Is the upper left corner of the first cell from the beginning (starting 1), and then extend the upper right corner to bottom left diagonal. Starting with the next to last, then top to bottom. Start by number in ascending order. That is a slash on each of several groups of figures were as follows: 1,234,567,891,011,121,314 15 16 17 1,819,202,122,232,425 As the first top to bottom (1 can be seen as top to bottom), from bottom to top, much like a snake, therefore, the digital form can also be known as the Snake matrix. Now with a method (or function), method parameter is a int type, that n, method returns a two-dimensional array, said to number of forms received from Relay. In fact, the algorithm is not complicated, just were obtained from 1 to n ^ 2 in each number corresponding to the two-dimensional array of coordinates on it. Acquire a 5-line 5 of this form, the calculated above corresponds to the coordinates of each array (starting position is 0). From the above we can see a pattern from the standard. Half the upper left corner of the form (with diagonal boundaries) of the horizontal and the vertical axis starting at 0, each group by one, until the border to form (n - 1), and is alternating, that is, even line is the column increase, decrease row, row + column = group index. The bottom right corner of the 4 groups although the figures are rows, columns are alternating growth, but decreasing the row or column is always from the (n - 1) started (for this example, starting from 4), while increasing the row or column is always from the index - n + 1 start, which index the index of that group. An algorithm which can be drawn. To achieve the code below: public static int[][] getGrid(int n) { int[][] array = new int[n][n]; int row = 0, col = 0, m = 1; // Used to control the parity group, false indicates that even groups ,true Represents a singular group boolean isRow = false; // i Represents the index of the current groups, from 0 Start for (int i = 0; i < (2 * n - 1); i++) { row = i; while (row >= ((i < n) ? 0 : i - n + 1)) { // If the processing is the lower-right corner of the table of figures, the row or column up n-1 if (row > (n - 1)) row = n - 1; col = i - row; if (isRow) array[row][col] = m; else // Use the row into columns , The col into line array[col][row] = m; m++; row--; } // Switch parity group isRow = !isRow; } return array; } Another algorithm The algorithm needs to achieve the above cycle of N * N times we can generate serpentine matrix. But a closer look, you can also change what the algorithm slightly, so that cycle times reduced to N * N / 2. We had learned in school to use Gauss's method, 1 +2 +3 +...+ 100, 1 + 100 = 101,2 + 99 = 50 +51 = 101 ,..., 101, so the result is 101 * 50 = 5050. Very convenient. Our algorithm also could use a similar approach. Carefully observe the figures above 5 x 5 table was found, calculate the upper-left corner of the matrix after each number, can directly access a location in the lower right corner the number of degrees. For example, in (0,0) position 1, may apply to the (4,4) position 25, (1,2) position of 9 can be (3,2) position of 17. We found that the number of each and all of the 26. And they coordinate the relationship is (row, col), (n - row - 1, n - col - 1). Therefore, as long as get the upper left corner of the half matrix, we can draw the other half of the matrix lower right corner. If n is odd, the diagonal middle of a number (in the 5 * 5 matrix of 13) with the corresponding number is its own. Well, we look to improve the algorithm implementation: public static int[][] getGrid1(int n) { int[][] array = new int[n][n]; int row = 0, col = 0, m = 1; int number1 = (n * n / 2 + n * n % 2); int number2 = n * n + 1; boolean isRow = false; // number1 Indicates that you want to calculate the snake-like matrix in the largest numbers, for 5*5 The number is for the matrix 13 for (int i = 0; m < number1; i++) { row = i; while (row >= 0) { col = i - row; if (isRow) { array[row][col] = m; // Fill and m is the number that corresponds to another array[n - row - 1][n - col - 1] = number2 - m; } else { array[col][row] = m; // Fill and m is the number that corresponds to another array[n - col - 1][n - row - 1] = number2 - m; } m++; if(m >= number1) break; row--; } isRow = !isRow; } return array; } Although the above algorithm will cycle times reduced by half, but increased the calculation of each cycle, so the algorithm does not increase the overall efficiency. As for the use of algorithms which can be based on actual conditions. If you want to output n = 10 the number of forms, you can use int [] [] grid = getGrid (10) or int [] [] grid1 = getGrid1 (10), will get the same result. Output grid and grid1, see if it is the result of the following: Source: References 2: Matrix it can say a few snake, snake-like matrix of several types, this is one of the following: 1267 35813 491 214 10,111,516 It was such a matrix has attracted a few days, of course, I think this is the most like "snake" in Kazakhstan serpentine matrix. Then, write some code yourself, can be considered to achieve this effect, but the algorithm is too complicated for the above for loop sets a for loop, look at all his halo, and then surf the Internet and write a few masters, and finally found following this very simple, unfortunately do not know Who is this big cow. . Realization is very simple and clear, I want to say is that this not only to achieve N * N of the square, slightly transform can achieve N * M matrix, This irregular serpentine also fun Ha ~ The following are the three Figure 4 * 4 squares, 5 * 3 matrix and 3 * 5 matrix, followed by two good Kanma \ (^ o ^) / ~ The following code is attached, of course, I write not brought, and, not embarrassed about. . . . . 01 # include <iostream> 02 using namespace std; 03 const int MAX = 20; 04 05 int main () 06 ( 07 int m, n; 08 int a [MAX] [MAX]; 09 cout <<"Enter matrix of rows and columns:" <<endl; 10 cin>> m>> n; 11 12 int i, j, s; 13 i = j = 0; 14 s = 1; 15 a [i] [j] = s + +; 16 while (s <= m * n) 17 ( 18 / / shift to right 19 if (j <n - 1) 20 j + +; 21 else 22 i + +; 23 a [i] [j] = s + +; 24 / / lower left 25 while (i <m - 1 & & j> 0) 26 a [+ + i] [- j] = s + +; 27 / / Down 28 if (i <m - 1) 29 i + +; 30 else 31 j + +; 32 a [i] [j] = s + +; 33 / / upper right 34 while (j <n - 1 & & i> 0) 35 a [- i] [+ + j] = s + +; 36) 37 for (int i = 0; i! = M; + + i) 38 ( 39 for (int j = 0; j! = N; + + j) 40 printf ("% 3.0d", a [i] [j]); 41 cout <<endl; 42) 43 return 0; 44) Source: # more-129 <! - Page --><!-- page end ->
http://www.codeweblog.com/snake-algorithm-java-implementation/
CC-MAIN-2016-44
refinedweb
1,722
54.49
Newbie Here Edit: This is not homework, I am a chemical engineering student and a math minor. I'm doing programming on the side to help me automate certain calculations later in my career. Also always had a healthy interest in programming. I just read the not doing homework for people sticky at the top and want to throw out there i'm not a computer programming student. I'm creating a program to create list of prime numbers code. It has taught me a good amount about recursions statements and how while statements can be used to maximize performance for given recursion limits. My problem is I can only search a range of ~ 1000 numbers before the recursion limit is reached. I know there is some basic improvements I can do but my current concerns: 1. The program recurs the program Prime(x) with program Prime(x+1) to check the next x value across the interval [x,x+970]. Finding all prime numbers over that interval. However, I can't find out how to define the upper bound x+970 since recurring Prime(x+1) increases the upper bound. So how can I create a fixed upper bound with only one variable being inputted, x. 2. Is their a way to have the program run for the interval clear the stack, than run the next interval [x+971,x+970+971] if an interval greater than the recursion limit was desired? Till a single number is too large for the platform I would expect there to be a way around the recursion limit. This is one of my first independent programs and I just couldn't find good answers to these questions. def Prime(x): n=2 [B] if x > 972:[/B] #My upper limit is 972 and my lower limit is x, print "end" #how do I make the upper limit a function of x elif x == 1: # when I have to recur Prime(x+1)? Prime(x+1) elif x == 2: print (2) Prime(x+1) elif x <= 0: print ("Number must be a positive integer") else: while n < n+1: if n > int(x/n): print(x) break elif x%n==0: break else: n=n+1 Prime(x+1) Edited by ChaseRLewis: n/a
https://www.daniweb.com/programming/software-development/threads/235518/need-helping-writing-prime-number-code
CC-MAIN-2017-17
refinedweb
380
67.89
Original article was published by Bob Rupak Roy on Deep Learning on Medium Hi there, how are you doing, i hope it’s great! In my last article we used Multi-variate LSTM that is multiple inputs for LSTM to forecast a Time Series data. This time we will use take one step further with step wise forecasting. For this example we will forecast 3 months. The article was originally found in ‘machine learning mastery’ by Jason. What we will try to achieve here is to simply the complex steps with different settings and understanding to get a clear picture about the concepts to quickly solve our day to day time series problem. But before that let me repeat in brief what is LSTM Long-Strong-Term Memory (LSTM) is the next generation of Recurrent Neural Network (RNN) used in deep learning for its optimized architecture to easily capture the pattern in sequential data. The benefit of this type of network is that it can learn and remember over long sequences and doesnot rely on pre-specified window lagged observation as input. In keras this is referred as stateful and involves settings the “stateful” argument to “True” in LSTM layer What is LSTM in brief? It is a recurrent neural network that is trained by using Back-propagation through time and overcomes the vanishing gradient problem. Now instead of having Neurons, LSTM networks have memory blocks that are connected through layers. The blocks of LSTM contains 3 non-linear gates that makes it smarter than a classical neuron and a memory for sequences. The 3 types of non-linear gates include a.) Input Gate: decides which values from the input to update the memory state. b.) Forget Gate: handles what information to throw away from the block c.) Output Gate: finally handles what to be in output based on input and the memory gate. Each LSTM unit is like a mini-state machine that utilizes a ”memory” cell that may maintain its state value over a longer time, where the gates of the units have weights that are learned during the training procedure. There are tons of articles available in the internet about the workings of LSTM even the math behind LSTM. So here I will concentrate more for a quicker practical implementation of LSTM for our day to day problems. Let’s get started. First is data pre-processing step where we have to give structure the data into supervised learning that is X and Y format. In simple words it identifies the strength and values of the relationship (positive/negative impact and the values derived is call quantification of impact) between one dependent variable(Y) and series of other independent variables X For this example we have a retail sales time series data recorded over a period of time. Now as u know supervised learning requires X & Y independent and dependent variable for the algorithm to learn /train, so we will first convert our data into such format Assume we have sales data. What we will do we will first take the sales data(t) in our first column than the second column will have the next months(t+1)sales data that we will use to predict. Remember X & Y independent and dependent variable format where we use Y to predict the data. Now we will replicate the same if we have more columns. And since we are predicting for the next 3 months we will take t, t+1,t+2 Let me show you the dataset how it will be. Now since we have our data ready to train our model using lstm we will straight away move on to the full code to make it quick and easier to understand its components. from pandas import DataFrame from pandas import Series from pandas import concat from pandas import read_csv from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from math import sqrt from matplotlib import pyplot from numpy import array#a.) convert time series into supervised learning problem def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): n_vars = 1 if type(data) is list else data.shape[1] df = DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)] # forecast sequence (t, t+1, ... t+n) for i in range(0, n_out): cols.append(df.shift(-i)) if i == 0: names += [('var%d(t)' % (j+1)) for j in range(n_vars)] else: names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)] # put it all together agg = concat(cols, axis=1) agg.columns = names # drop rows with NaN values if dropnan: agg.dropna(inplace=True) return agg #b.) create a differenced series def difference(dataset, interval=1): diff = list() for i in range(interval, len(dataset)): value = dataset[i] - dataset[i - interval] diff.append(value) return Series(diff) #c.) transform series into train and test sets for supervised learning def prepare_data(series, n_test, n_lag, n_seq): # extract raw values raw_values = series.values # transform data to be stationary diff_series = difference(raw_values, 1) diff_values = diff_series.values diff_values = diff_values.reshape(len(diff_values), 1) # rescale values to -1, 1 scaler = MinMaxScaler(feature_range=(-1, 1)) scaled_values = scaler.fit_transform(diff_values) scaled_values = scaled_values.reshape(len(scaled_values), 1) # transform into supervised learning problem X, y supervised = series_to_supervised(scaled_values, n_lag, n_seq) supervised_values = supervised.values # split into train and test sets train, test = supervised_values[0:-n_test], supervised_values[-n_test:] return scaler, train, test #d.) Define the LSTM network',metric=["accuracy"]) # fit network for i in range(nb_epoch): model.fit(X, y, epochs=1, batch_size=n_batch, verbose=1, shuffle=False) model.reset_states() return model #e.) forecast with an LSTM, def forecast_lstm(model, X, n_batch): # reshape input pattern to [samples, timesteps, features] X = X.reshape(1, 1, len(X)) # make forecast forecast = model.predict(X, batch_size=n_batch) # convert to array return [x for x in forecast[0, :]] #f.) evaluate the persistence model def make_forecasts(model, n_batch, train, test, n_lag, n_seq): forecasts = list() for i in range(len(test)): X, y = test[i, 0:n_lag], test[i, n_lag:] # make forecast forecast = forecast_lstm(model, X, n_batch) # store the forecast forecasts.append(forecast) return forecasts #g.) invert differenced forecast def inverse_difference(last_ob, forecast): # invert first forecast inverted = list() inverted.append(forecast[0] + last_ob) # propagate difference forecast using inverted first value for i in range(1, len(forecast)): inverted.append(forecast[i] + inverted[i-1]) return inverted #h.) inverse data transform on forecasts def inverse_transform(series, forecasts, scaler, n_test): inverted = list() for i in range(len(forecasts)): # create array from forecast forecast = array(forecasts[i]) forecast = forecast.reshape(1, len(forecast)) # invert scaling inv_scale = scaler.inverse_transform(forecast) inv_scale = inv_scale[0, :] # invert differencing index = len(series) - n_test + i - 1 last_ob = series.values[index] inv_diff = inverse_difference(last_ob, inv_scale) # store inverted.append(inv_diff) return inverted #i.) evaluate the model with RMSE def evaluate_forecasts(test, forecasts, n_lag, n_seq): for i in range(n_seq): actual = [row[i] for row in test] predicted = [forecast[i] for forecast in forecasts] rmse = sqrt(mean_squared_error(actual, predicted)) print('t+%d RMSE: %f' % ((i+1), rmse)) #j.) plot the forecasts def plot_forecasts(series, forecasts, n_test): # plot the entire dataset in blue pyplot.plot(series.values) # plot the forecasts in red for i in range(len(forecasts)): off_s = len(series) - n_test + i - 1 off_e = off_s + len(forecasts[i]) + 1 xaxis = [x for x in range(off_s, off_e)] yaxis = [series.values[off_s]] + forecasts[i] pyplot.plot(xaxis, yaxis, color='red') # show the plot pyplot.show()# load the dataset series = read_csv('sales_year.csv', usecols=[1], engine='python')# configure n_lag = 1 n_seq = 3 n_test = 10 n_epochs = 1500 n_batch = 1 n_neurons = 50#prepare data scaler, train, test = prepare_data(series, n_test, n_lag, n_seq) #fit model model = fit_lstm(train, n_lag, n_seq, n_batch, n_epochs, n_neurons)#forecasts forecasts = make_forecasts(model, n_batch, train, test, n_lag, n_seq)#inverse transform forecasts and test forecasts = inverse_transform(series, forecasts, scaler, n_test+2) actual = [row[n_lag:] for row in test] actual = inverse_transform(series, actual, scaler, n_test+2)#evaluate forecasts evaluate_forecasts(actual, forecasts, n_lag, n_seq)#plot forecasts plot_forecasts(series, forecasts, n_test+2) First we will call all the important libraries then a) we will define function to convert times series into supervised learning problem. b) The next step is to convert the time series data to Stationary. And our ‘sales_year.csv’ data is not stationary. This means that there is a structure in the data that is dependent on time. We can see there is a increasing trend in the data Stationary data is easier to model and will very likely result in more skillful forecasts. The trend can be removed from observations, then use for forecasts later we can scale it to the original value for prediction. We can easily remove a trend by differencing the data with diff() function from pandas that is the observations from the previous time step (t-1) is subtracted from the current observation(t). This will give us a series of difference. c.) Now its time to normalize/scale the data. LSTMs are a bit sensitive to wide spread scale of data. Even in all deep learning methods scaling the data range of -1 to 1 before fitting it to our algorithm is good practice that helps the algorithm to work faster and effectively. And yes scaling the data will not lose its original meaning from the data. We also call this as Normalization using MinMaxScaler pre-processing class function. Even the default activation function for LSTMS is the hyperbolic tangent (tanh) which outputs values between -1 and 1 which is the preferred range for the time series data. Then we will split the data into train and test. d.) Its time to deploy LSTM. By default an LSTM layer in keras maintains state between data within one batch. A batch of data is a fixed-sized number of rows from the training dataset that defines how many patterns to process before updating the weights of the network. By default State in the LSTM layer between batches is cleared. Therefore we must make the LSTM stateful. This gives us fine-grained control over when state of the LSTM layer is cleared LSTM network expects the input data(X) to be [samples, time steps, features] format. batch_input_shape=(n_batch, X.shape[1], X.shape[2]) The batch size of 1 must be used since we require prediction to be made at each time step of the test dataset. And the number of neurons also called memory units or blocks. Then we have 1 output layer Dense(1). In the compiling network, we must specify a loss function and optimization algorithm to calculate the loss and weight. This is just our regular LSTM stuffs that we have learn from our previous chapter. Now e.) and f.) are the functions to predict the next 3 time sequence then g.) and h.) are to inverse the forecast value to our original data set value. Remember we have scaled value with MinMaxScaler and then differenced series to remove the trend ‘Stationary’ Finally i.) we will calculate the Root Mean Square Error RMSE to understand the accuracy level and at the same time j.) we will plot our 3 month forecast Running the code will give you the plot and the RMSE score. Output: t+1 RMSE: 194.077577 t+2 RMSE: 293.865938 t+3 RMSE: 334.348398 We can notice that RMSE does not become progressively worse with each forecast. This is because that t+2 is easier to forecast than t+1 We can notice that RMSE does not become progressively worse with each forecast. This is because that t+2 is easier to forecast than t+1 The plot also depicts the model needs improvement over the LSTM network. I hope I’m able to simply the concept. There’s plenty of rooms for improvement let me know if you are able to improve the model. My alternative internet presences, Facebook, Blogger, Linkedin, Medium, Instagram, ISSUU and my very own Data2Dimensions Also available on Quora @ Have a good day!
https://mc.ai/multi-step-lstm-time-series-forecasting/
CC-MAIN-2020-45
refinedweb
2,030
55.34
Not logged in Log in now Recent Features LWN.net Weekly Edition for December 5, 2013 Deadline scheduling: coming soon? LWN.net Weekly Edition for November 27, 2013 ACPI for ARM? LWN.net Weekly Edition for November 21, 2013 Opera M2 is being touted as a "revolutionary" mail client, and it is certainly different from other mail clients. The most important differences are very tight integration with the browser, and the lack of traditional mail folders. All mail is stored in a flat database, and different views are used instead; this is basically taking the virtual folder concept to its extreme: everything is a virtual folder. The implementation of this in M2 is very well done, however, and the mail client tries to do as much as possible automatically. Note: Although some of the screenshots are from the first preview of version 7.50 the review has been updated to account for new features in the second preview. M2 ships with a number of default virtual folders divided into categories: The idea of all this is to help you easily keep an overview of your current e-mail communication, and M2 automatically adapts the "Active contacts" and "Active threads". This works very well in practice and while the other virtual folders could be created in other mail clients this automatic adaptation is unique to M2. The tight integration with the browser part of Opera means that the mail view is just another side panel along with bookmarks, contacts, notes and transfers. The actual message index and mail view, as well as the composer, opens as tabs just as normal web pages; if you are already used to the very well done Opera interface, navigation is a snap. Mouse gestures also work for M2 pages. In short, M2 is in many ways revolutionary and makes it easy to take advantage of next generation mail client features without having to do much manual setup. Mail import: M2 imports from Outlook Express and Netscape on Windows, but not under Linux unfortunately. One solution might be to import the mail under Windows and copy the M2 mail store to Linux; note that I have not tried this. Account setup: Selecting "New account" from the Mail menu starts a wizard for setting up an account, and makes this process very easy for both POP and IMAP servers. The dialog only asks for the a minimal amount of information, but does not have the option of automatically querying the server for supported authentication options. Create filters / virtual folders: Since M2 does not have traditional folders there is no need for traditional filters; instead a virtual folder is created. M2 supports the most important message fields, but the selection is more limited than Evolution or KMail. There is no option to search on message size, labels or attachments (you can argue these are already supported, since they have their own virtual folders, but still it could be useful to include them in custom views) or date. There is, however, support for specifying AND/OR on a per-rule basis. Regex matching is supported, but the expressions must be written manually. Notable is the support for creating sub-filters; such filters can be set to only include messages in parents, and search rules can thus be inherited. Since messages can also be assigned to virtual folders (analogous to the copy function in traditional mail clients) even if they do not match the search criteria, it is easy to use this to simulate normal mail folders, but with more advanced functionality. Also, the "Spam" folder as well as all virtual folders can be set to learn from messages added and removed from the folder; one supposes this uses a Bayesian approach similar to the buckets found in the POPFile spam filter. Again a very useful feature as there is no need to create complex rules; simply drag messages to the folder and M2 will assign similar messages there automatically. Address book: Right-clicking on a message and selecting "Add contact" adds the sender to the contact list. The contact list is accessed as a sidebar, and the quick find makes it easy to locate individuals. There is no support for grouping, however, and only basic information can be entered on each contact. Double clicking on a contact views all messages involving him/her, and the contact is also added to the "Active contacts". Clicking the compose button opens a composer tab. Searching: One of the main features of M2 is the very quick search facility. Simple word searches can be created using the "Start search" field, but there is also the option of more traditional searches. Selecting "Search" from the mail menu brings up the search dialog, which is quite limited compared to other mail clients; it is apparent that this is only meant as a last resort. You can only search on one header field, but an option for only searching the last year or month is present. Selecting "Each word" instead of "Entire phrase" enables Google-style searching on each word, with the option of putting "-" in front of words to exclude them. The search can be limited to a single virtual folder and optionally its sub-folders. Note that these searches are significantly slower compared to the close-to-instantaneous other searches in M2, especially when searching a large number of messages. It is clear that this feature is not meant for frequent use. Reading messages: Double clicking any virtual folder opens its messages in a tab. The message index includes by default the most common columns as well as status, size, attachments and label. Using the "View" drop-down box it is possible to set several view options, like thread messages, only display recent messages, turn off display of mailing lists, only view messages matching at least one filter, and also several options relating to the display interface. Buttons on the top gives easy access to common functions such as reply and forward. There is also a quick find field for quickly finding messages. Another. Composing messages: The composer opens in a new tab and is very straight-forward. It is easy to add contacts from the address book, header fields can be shown/hidden with the "View" drop-down box and there is a separate area for dropping attachments. The message can be sent or saved as a draft for future editing. There is no support for writing HTML mail, however, nor is there any signing/encryption support. The last item might be a show-stopper for some people, but it is planned for a future M2 version. IMAP: M2 tries its best to support IMAP well, although it is not a perfect fit with M2's concept of a heavily indexed flat database. Messages are indexed as they are downloaded, however, but there does not seem to be support for server-side searches, which somewhat limits its usefulness. With that said, the IMAP support works, and if you choose to download message bodies as well as headers, you will get all the benefits of M2's search features. If you want a folder structure on the IMAP server you will have to organize it yourself, however. Encryption: Currently not supported, but apparently planned for an unspecified, later version. A workaround is to use a proxy server doing the signing/encryption. Notes: Review of Opera 7.50 Posted Feb 26, 2004 15:34 UTC (Thu) by remmy (subscriber, #4400) [Link] Posted Feb 26, 2004 15:49 UTC (Thu) by remmy (subscriber, #4400) [Link] Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/72947/
CC-MAIN-2013-48
refinedweb
1,267
58.62
The QCache class is a template class that provides a cache based on QString keys. More... #include <qcache.h> Inherits QPtrCollection. List of all member functions. A cache is a least recently used (LRU) list of cache items. Each cache item has a key and a certain cost. The sum of item costs, totalCost(), never exceeds the maximum cache cost, maxCost(). If inserting a new item would cause the total cost to exceed the maximum cost, the least recently used items in the cache are removed. QCache is a template class. QCache<X> defines a cache that operates on pointers to X, or X*. cache and reimplement newItem() if you want deep copies. When removing a cache item, the virtual function QPtrCollection::deleteItem() is called.. Constructs a cache whose contents will never have a total cost greater than maxCost and which is expected to contain less than size items. size is actually the size of an internal hash array; it's usually best to make it a prime number considers all Unicode letters. Removes all items from the cache and destroys it. All iterators that access this cache will be reset.. Returns the item associated with key k and associated cost, c. Returns TRUE if it is successfully inserted; otherwise returns FALSE. The cache's size is limited, and if the total cost is too high, QCache will remove old, least recently used items until there is room for this new item. The parameter p is internal and should be left at the default value (0). Warning: If this function returns FALSE (which could happen, e.g. if the cost of this item alone exceeds maxCost()). Sets the maximum allowed total cost of the cache to m. If the current total cost is greater than m, some items are deleted.
http://doc.trolltech.com/3.0/qcache.html
crawl-002
refinedweb
300
75.4
. In this example, the code and the screenshot do not agree. Single quotes are used around the values of the attributes we are asked to add in the code but double quotes appear in the screenshot. As either single or double quotes are acceptable for attributes, either can be used but IE will display whichever you use in the code ordinarily. Also, the How It Works for this example on Page 43 describes adding the first attribute without quotes and then receiving an error message in IE as the parser finds this error - this step is not described in the Try It Out section. Thanks to Howard for spotting this. The screenshot on page 49 is incorrect and does not represent how the file cd4.xml will look when viewed with Internet Explorer 5 or later. It is the one on page 47 repeated. The correct screenshot (named cd4xml.jpg) is available within the code download for this book. It shows the inclusion of the and elements. Thanks to Silhone Sung At the top of page 84 we give a list of namespaces and introduce them as having been seen before in the chapter. In fact, only the pers namespace has been seen before. The text surrounding the list can be reworded to read: Imagine we choose to create three namespaces for Serna Ferna Inc: We could instead create one namespace which the company would use for all of its XML document types. Or, conversely, we could break down or namespaces down further, perhaps splitting the <person> document type into multiple namespaces. Why did we choose three? The correct URL for the download of Xalan for Java is: Thanks to Shannon Bain for spotting this. The second paragraph on page 94 incorrectly states that the template shown on page 93 will be applied for any elements named "given". In fact it should be "quantity". The sentence should read: In this case, the template will be applied for any elements. The explanation of the example given to illustrate the use of the <xsl:value-of> element does not agree with the example code. The code uses the <quantity> element, whereas the explanation uses <first>. The correct explanation should read: In other words, if the XSLT engine finds: <quantity>16</quantity> it will output 16, and if it finds: <quantity>121</quantity> it will output 121 In the 'Associating Stylesheets with XML Documents Using Processing Instructions' section, there is an erroneous backwards reference to CSS. At this stage in the book we haven't covered this in detail (please see Chapter 11 where this discussion does take place). The sentence that begins 'However, an XSL stylesheet...' should read: However, an XSL stylesheet can also be associated with an XML document using a processing instruction, like this: The formatting of the last 2 words on the page should have been the other way around. At present, the word axis is formatted to indicate that it is the name of an axis when, in fact, the name of the axis is attribute. Thanks to Jeff Wofford for pointing this out. In both code fragments in the <xsl:apply-templates> section of the page, the <xsl:apply-templates> elements are missing the closing slash required to make the fragments well formed XML. In the first fragment, the element should read: <xsl:apply-templates/> and in the second fragment, the element should read: <xsl:apply-templates The line is missing from the top of the ElemsToAtts.xsl stylesheet created in stage 4 of the Try It Out example. Although the stylesheet will still work in MSXSL, it is important to note that it may not work elsewhere as the omission of this line makes the it not well formed. Thanks to Jeff Wooford for spotting this. The code for order.xml is shown on pages 99-100, but it's easy to miss as it's not used in any Try It Out example until we get to this page. Also, when you run the example on page 131 with order.xml, you'll notice that there are some errors on the page. The command to run the example should be >msxsl order.xml defaulttemplates.xsl in both cases, rather than >msxsl order.xml defaults.xsl When you run the code the first time, the resulting output will include Company A, rather than Customer A, as this is the data contained in order.xml. When you run the code the second time, the resulting output will include Customer: Company A, rather than Customer: Customer A, as this is the data contained in order.xml. n step 3, the command to run the file should be: >msxsl order.xml defaulttemplates.xsl and the results should show: Company A rather than Customer A In step 4, the command to run the file should be: >msxsl order.xml defaulttemplates.xsl and the results should show: Customer: Company A rather than Customer: Customer A The code for the <xsl:choose> example does not match the text. The code shows the use of the <salary> element rather than the <number> element discussed. The code should read: <xsl:choose> <xsl:when text=number[number(.)... <xsl:when text=number[number(.)... </xsl:choose> Thanks to Marianne Hazlewood for spotting this. On page 123 the stylesheet AttsToElems.xsl is shown. This stylesheet is reshown on page 140, however there is a difference. In the last template of the stylesheet on page 123 the local-name() function is used, but in the last template of the same stylesheet on page 140 the name() function is used. This should still work but the name should not have changed from page 123. Thanks to Michael O' Sullivan for bringing this to our attention The first line of code on page 194 should read: <!ATTLIST catalog type NMTOKENS #IMPLIED> not <!ATTLIST catalog type NMTOKEN #IMPLIED> Thanks to Don Foster The value 05-07-1995 has been given as a valid example of date datatype value. This is incorrect because the date datatype uses the format CCYY-MM-DD. The correct example should be 1995-05-07 Thanks to Matt Howell The second of the examples showing valid code according to the element declaration earlier in the page contains an error - the attribute name, gender, is missing. It reads: <"Weird Al" Yankovic</artist> But it should read: <artist gender="male">"Weird Al" Yankovic</artist> Page 293 shows the following code snippet: <artist title="Mr"> <name:first>Alfred</name:first> <name:middle>middle</name:middle> <name:last>Yankovic</name:last> </artist> The namespace prefix of name: used here is incorrect. This namespace prefix is declared in the root element of the instance document as n: and not name: so this code snippet should be: <artist title="Mr"> <n:first>Alfred</n:first> <n:middle>middle</n:middle> <n:last>Yankovic</n:last> </artist> Note that this also means the very last sentence at the bottom of the page needs the reference to the 'name' prefix changed to n. In other words this last sentence should read: 'therefore we must qualify them with the n prefix we declared in the root element of our instance document'. Thank you Michael O' Sullivan for bringing this to our attention. Unfortunately the first screenshot on this page is a repeat of the second one. The first screenshot should show the text DemoElement rather than null. In the Try It Out section beginning on page 352 the java listing in step 2 fails to include the statement: import org.xml.sax.helpers.XMLReaderFactory; This results in a compile time error. This is corrected in the full listing that follows on page 354 - 355 and in the bandreader.java file available from the code download. In step 4 a semi-colon is missing from the end of the statement: XMLReader readerObj = XMLReaderFactory.createXMLReader ("org.apache.xerces.parsers.SAXParser") This results in a compile time error. This is also corrected in the full listing that follows on page 354 - 355 and in bandreader.java available in the code download. Thanks to Nat Thompson for pointing out these omissions. The second code block on the page does not correspond with the first. It shows the use of em in a container relationship, instead of i . The code should read: <style> h1 i {color:red} </style> Also, the reference to <em> in the following sentence should be to <i>. In the first diagram on the page, which shows the CorporateCustomer table, the third field name is incorrect. The diagram shows company_name, but should show company_address. Unfortunately, the latest release of Tomcat, Tomcat 4.0.2, has changed XML parsing capabilities and class loading methods from the release that was current at the time the book was written. This means that if you have Tomcat 4.0.2 you will need to carry out some extra steps in order to run the address book application sucessfully (this is because the code was designed to run with an earlier version). If you don't carry out the extra steps, you will recieve internal server errors when trying to run the application. You will need to: *Install Tomcat as instructed in the book, including setting the JAVA_HOME environment variable. *Copy the xsl.war file to the webapps directory, as instructed in the book. *Start Tomcat to enable unpacking of the .war file. *Stop Tomcat. *Within the Tomcat files, move xerces.jar from common/lib to server/lib (i.e. there shouldn't be a copy of xerces.jar in common/lib anymore and there should be one in server/lib). *Within the case study application files move crimson.jar and saxon.jar from xsl/WEB_INF/lib to common/lib in the Tomcat files (i.e. there shouldn't be copies of crimson.jar and saxon.jar in xsl/WEB_INF/lib anymore and there should be copies of them in common/lib). *Start Tomcat again. *Type into your browser and the application should start fine. Related Books XML Resources
http://www.wrox.com/WileyCDA/WroxTitle/Beginning-XML-2nd-Edition.productCd-0764543946,descCd-ERRATA.html
crawl-002
refinedweb
1,665
72.56
GPy with Hologram.io SIM Should the Pycom GPy using a Hologram SIM card work today with LTE CAT-M1 in the US (Georgia)? I’m trying to run the example app (updated on 4/16/18) listed below and the program never gets past the “attach to cell network” stage..4 - 4/15/18") print("disable MicroPython control of LED") pycom.heartbeat(False) pycom.rgbled(WHITE) print("instantiate LTE object") lte = LTE(carrier="verizon") print("delay 4 secs") time.sleep(4.0) if lte.isattached(): print("LTE was already attached, disconnecting...") lte.disconnect() lte.detach() print("resetting modem...") lte i = 0 while True: # get EPS Network Registration Status: # +CEREG: <stat>[,[<tac>],[<ci>],[<AcT>]] # <tac> values: # 0 - not registered # 1 - registered, home network # 2 - not registered, but searching... # 3 - registration denied # 4 - unknown (out of E-UTRAN coverage) # 5 - registered, roaming r = at('AT+CEREG?') r0 = r[0] # +CREG: 2,<tac> r0x = r0.split(',') # ['+CREG: 2',<tac>] tac = int(r0x[1]) # 0..5 print("tac={}".format(tac)) if lte.isattached(): print("Modem attached (isattached() function worked)!!!") break if (tac==1) or (tac==5): print("Modem attached!!!") break i = i + 1 print("not attached: {} secs".format(i)) if (tac != 0): blink(BLUE, tac) else: blink(RED, 1) time.sleep(1) print("connect: start a data session and obtain an IP address") lte.connect() i = 0 while not lte.isconnected(): i = i + 1 print("not connected: {}".format(i)) blink(GREEN, 1) time.sleep(1.0)) - mattliddle last edited by Hi. I know this may be a little late, but I have some code that enables LTE-CATM1 connection through hologram and to send a message into their socket. I would also recommend not specifying the carrier because Hologram.io takes care of that. Here is my code: Also note that hologram.io working with Python requires that you send a bytearray in ASCII format. At least from my testing, that's the only way I could get it to work. import socket import time import pycom from machine import RTC from network import LTE from network import WLAN HOST = "cloudsocket.hologram.io" PORT = 9999 DEVICE_KEY = "ABCDEFG" #generated on hologram's portal for each SIM card. TOPIC = "TOPIC1" # # Need to use global variables. # # If in each function you delare a new reference, functionality is broken lte = LTE() #(1) #") #pycom.rgbled(0x00FF00) #time.sleep(.5) #pycom.rgbled(0x000000) break print('.', end='') time.sleep(1) #") # Program starts here. try: lte = getLTE() print(lte) s = socket.socket() print(s) dns_records = socket.getaddrinfo(HOST, PORT) print("got dns_records") print(dns_records) message = "Hello World!" for record in dns_records: try: s.connect(record[-1]) print("connected") data = '{"k": "%s", "d": "%s", "t": "%s"}' % (DEVICE_KEY, message, TOPIC) s.send(bytes(data, 'ascii')) print("sent") result = s.recv(8).decode() print(result) s.close() break except Exception as err1: try: s.close() except: pass print(err1) continue except Exception as err: print(err) try: s.close() except: pass finally: endLTE() One thing I haven't been able to do yet is send a message to the hologram dashboard. If you have been able to send messages, would you mind helping me out? Here is the code that I've been using to connect with the Hologram Socket (In my real code I use the devicekey I got from the Hologram Dashboard): s = socket.socket() s.connect(socket.getaddrinfo('cloudsocket.hologram.io', 9999)[0][-1]) s.send({"k":"ABCDWXYZ","d":"Hello, World!","t":"TOPIC1"}) print(s.recv(4096)) s.close() It seems to run just fine until the s.send() line. It hasn't been able to send any messages to Hologram yet. I'd really appreciate any help! Hello, I was able to successfully connect to LTE with the help of this example: I only needed to change a few things. - changed "telstra.internet" to "hologram" in the getLTE() function. - I also deleted "band=28 dl-earfcn=9410" in the getLTE() function because the GPy can scan multiple bands ( (see lte.attatch section)) - As a minor detail I changed au.pool.ntp.org to us.pool.ntp.org because I am in the USA. @wgtthompson I found this to be the case as well. Just hung at the lte instantiation until i started resetting it after declaring it even if using the same carrier as before. I do not believe the source code that you see in github is the code we are actually running currently. The reason I say that is I noticed extensive changes made to the modlte.c code a few weeks ago, and I have not seen any indication that an update has been made available to download. - wgtthompson last edited by wgtthompson I've noticed that setting a carrier other than verizonsuch as LTE(carrier='at&t')or LTE(carrier='standard')results in my modem not being able to connect to any carrier, ever. Setting the carrier back to verizondoes not fix it. A reset does not fix it. A power cycle does not fix it. The only way I've found that fixes this problem is to re-flash the modem firmware. I really don't see why this is even a constructor argument. Looking at the source code for modlte.c, it looks like it is setting the test conformance mode using the AT command AT+SQNCTMin the INIT phase of the modem. The AT manual for this modem specifically cautions for this command that "The change will be effective after the device’s reboot." I don't see a device reboot occurring in the code. It looks like the carrierargument is modifying a modem setting that won't take effect until a modem reboot. This is an undocumented part of the LTEAPI. ''' Changing carrier from the current setting in the modem. The carrier value is stored through power cycle by the modem. If the carrier setting is changed then a reset needs to follow for the value to take effect. ''' lte = LTE(carrier=NEW_VALUE) lte.reset() # cycle modem for new carrier to take effect # ... now use the object as normal... - wgtthompson last edited by To get the program to work, I had to set the carrier to "verizon" in the LTE function call lte = LTE(carrier="verizon") Hologram states that their SIM works with multiple carriers. I don't understand how that works if I'm having to specify the carrier in the initialization. We need Pycom and Hologram to clarify what is the correct method to initialize the LTE object and what carriers can we expect to connect to. - wgtthompson last edited by wgtthompson The example (dated 4/20/2018) works for me when the modem connects to an AT&T service. It never works if the modem decides to connect to a Verizon service. I am using a GPy and a Hologram SIM. I can tell which service because the Hologram dashboard shows the service for a specific session. For AT&T, the modem waits to attach for about 10-20 sec. While waiting to attach, the signal quality starts at +CSQ: 99,99(RSSI known) and transitions to +CSQ: 20,99(RSSi known). The registration state starts at +CEREG: 2,0and changes to +CEREG: 2,2. The modem then transitions to attached, then connects, and works like a charm. For Verizon, the modem never attaches (I let it loop for an hour once). While waiting to attach, the signal quality will oscillate between +CSQ: 99,99(RSSI unknown) to +CSQ: 20,99(RSSi known) roughly ever loop. The registration state starts at +CEREG: 2,0and then changes to +CEREG: 2,4 Anybody got thoughts? Note: the example I used has date 4/20/2018 in the code and is posted by @tlanier. I did not use the 4/15/2018 version in his/her original post. I did not experience any lock ups during the trip. Basically I would occasionally plug the unit into the car's USB port and run the test program posted on 4/20/18. I experienced the lock ups when developing the test program trying to find something that would work. I think the exception handling code added helped. As soon as we determine that coverage is good enough, I will do more extensive programming with the unit. Also I was hoping to get some feedback as to when the code changes to the cell connectivity code made on GitHub would be available for download and testing. @tlanier, thanks for the update. Do the results from your road trip mean that your system is no longer locking up on the LTE(carrier="verizon") line? If yes, can you share how it was resolved? Last weekend I drove the device from LaGrange, GA to Fairhope, AL (about 270 miles) . During the trip I spot checked CAT M1 connectivity. It worked everywhere except when I reached Fairhope where it did not work even though I had 3-4 bars on my cell phone (which also uses Verizon). We are still looking for a coverage map from the carrier detailing where CAT M1 coverage should be expected. - ChrisGammell last edited by @rwall If it requires that we do something other than set the APN, I assume that the development process baked in some special magic to get around some restriction on the Verizon side of things (understandable if it was due to the relatively new Sequans chipset). I would be curious if any other SIMs have been tried other than ours and Verizon's. For now, I'm left at the same stage as others of "waiting for updates from the LTE team". I had missed Nathan's question about rebuilding the firmware. I did not, I simply used the latest block of code that tlanier had posted. I verified it connected to the Verizon tower and to our cloud and then got pulled away onto something else. Fun new feature on our dashboard, you can see live usage data and tower location for pro plan stuff. Has there been any additional progress on this issue? If not, is it possibly due to carrier="verizon" and using a hologram SIM effectively being mutually exclusive (emphasis on “effectively”). My understanding is that the carrier assignment optimizes the modem configuration for operation on a specific cellular network (Verizon in this case). However, operating on the Verizon network as a Verizon customer vs operating on their network through a MVNO may be very different. The most obvious is being on a home network vs roaming. In addition to functional implications, are there additional constraints based on Hologram’s contractual relationship with Verizon that may be playing a role in this issue? If I recall correctly from an old Hologram discussion, network operators like Verizon impose constraints on VMNO users such as requiring different timeouts on data connections. Question: did you rebuild your firmware from the changes just made to the code on Github? No, that's why I asked the questions: When can the next update be expected? How will we be notified that the update is available (the web site just has a link to the update program with no version number displayed)? @chrisgammell said in GPy with Hologram.io SIM: I verified it's working on mine as well, thank you for sharing the code Out of curiosity, did you rebuild your firmware from the changes just made to the code on Github? - tealbrains last edited by @tlanier I have made the same observation about the unit locking up, I am using the WDT to take care of that, hoping that they will solve the issue in the near future. It does not happen that often, see my other post : . Glad to see you got it working in the end! The program is now connecting to google.com successfully. I'm still having trouble with the unit locking up on the LTE(carrier="verizon") line at times. The chip/development environment gets in a crazy mode where I have to reset/power down/restart Visual Studio Code in unknown combinations to regain control of the chip. The Hologram.io dashboard is TERRIFIC!!! You can see data usage and the actual data that passes across the network. I love it!!!.6 - 4/20/18") # input("") # r = input("Enter anything to abort...") # allow opportunity to stop program # if r != "": # sys.exit(0) print("disable MicroPython control of LED") pycom.heartbeat(False) pycom.rgbled(WHITE) print("instantiate LTE object") lte = LTE(carrier="verizon") print("delay 4 secs") time.sleep(4.0) print("reset modem") try: lte.reset() except: print("Exception during reset") print("delay 5 secs") time.sleep, 5) time.sleep(2)) print("get address") addr = socket.getaddrinfo('', 443) print(addr) print("connect to {}".format(addr[0][-1])) s.connect(addr[0][-1]) print("GET 50 bytes from google") s.send(b"GET / HTTP/1.0\r\n\r\n") print(s.recv(50)) # receive 50 bytes print("close socket") s.close() try: lte.disconnect() except: print("Exception during disconnect") try: lte.dettach() except: print("Exception during dettach") # end of test, Red LED print("end of test") while True: blink(GREEN,5) time.sleep(1.0) It WORKED!!! The problem I'm having now is after I run the program once successfully the program will hang in the "lte=LTE(carrier="verizon") line at the start of the program. Unfortunately you can't reset the modem without instantiating the LTE object and instantiating the object is what gets hung up. There needs to be some command to say let's start all over and reset everything.
https://forum.pycom.io/topic/3021/gpy-with-hologram-io-sim/82
CC-MAIN-2019-51
refinedweb
2,254
66.94
Vim memo Personally, I don't mind using SublimeText, which is my editor of choice for a while. But I'm also curious about commandline editors since many people taut their ability to code over the network. You could forward X or remote in using some other way and still use Sublime, but let's see how if goes. I started working on this Vim setup when I got a new MBP recently. Figured, I can try something new. So, this post is more of a personal memo written by a total newbie, which is what blogs are all about. caveat emptor. In general though, the configuration is mostly inspired by yuroyoro-san's blog post from a couple years ago. various non-vim things dotfiles The setup described in this post is checked into eed3si9n/dotfiles. It is encouraged to fork other's dotfiles, but I wanted to understand what settings I'm bringing in, so I wrote mine from scratch. The general idea of the dotfiles is that it will be checked out to ~/dotfiles/, and contains files like zshrc. These root-level configuration files are then symbolically linked under the home directory as ~/.zshrc. Terminal.app I haven't had a need to use iTerm2 on Mac. Maybe Terminal.app had some limitations in the past, but it seems ok. Another reason to stick to Terminal.app is that I'm a fan of TotalTerminal. homebrew Zsh The shell for this machine will be Zsh. For Mac, see How to use Homebrew Zsh Instead of Max OS X Default. $ brew install zsh $ chsh -s /usr/local/bin/zsh In terms of configuration, zshrc is used just to load other zshrc.* files: ## basic [ -f $HOME/dotfiles/zshrc.basic ] && source $HOME/dotfiles/zshrc.basic ## aliases [ -f $HOME/dotfiles/zshrc.alias ] && source $HOME/dotfiles/zshrc.alias case "${OSTYPE}" in # MacOSX darwin*) [ -f $HOME/dotfiles/zshrc.osx ] && source $HOME/dotfiles/zshrc.osx ;; # Linux linux*) [ -f $HOME/dotfiles/zshrc.linux ] && source $HOME/dotfiles/zshrc.linux ;; esac ## color [ -f $HOME/dotfiles/zshrc.color ] && source $HOME/dotfiles/zshrc.color zshrc.basic One of the reasons to use Zsh is for better tab completion, so we can enable that here. I'm also making the prompt look like that of Bash. ## auto comp autoload -U compinit compinit ## prompts PROMPT="[%m:%~]$ " ## vi bindings bindkey -v ## history related HISTFILE=$HOME/.zsh_history HISTSIZE=10000 SAVEHIST=10000 setopt hist_ignore_dups setopt share_history autoload history-search-end zle -N history-beginning-search-backward-end history-search-end zle -N history-beginning-search-forward-end history-search-end bindkey '^r' history-beginning-search-backward-end bindkey '^f' history-beginning-search-forward-end The hello world example of tab completion is listing out the options for ls: $ ls -[tab] -1 -- single column output -A -- list all except . and .. -C -- list entries in columns sorted vertically -H -- follow symlinks on the command line -L -- list referenced file for sym link .... Pretty cool. Another interesting feature is that it's able to share the history across multiple sessions and run a search through it. So suppose you ran some one-liner git command, and after a bunch of other commands you wanted to rerun the git command. $ git[Ctrl-R] Zsh will display the last entry in the history starting with the string git. There are tons of other things you can configure in Zsh, like more standard defining aliases for ll type of things. Before we move on, I'm going to mention that a lot command line tool configuration is about figuring out what keyboard bindings to use. We have basically a finite amount of reasonable keyboard shortcuts, yet seemingly endless number of features coming from all ends. For Zsh, running bindkey command without arguments display the currently bound keys: $ bindkey "^A"-"^C" self-insert "^D" list-choices "^E"-"^F" self-insert "^G" list-expand "^H" vi-backward-delete-char .... tmux tmux is a terminal multiplexer. See further explanation from Zanshin.net's My Tmux Configuration and thoughtbot.com's A tmux Crash Course: It allows you to have multiple virtual consoles open in a single terminal window. Moreover, you can detatch and attach to a tmux session without ending it, allowing you great flexibility when working on remote servers or machines. In many respects it is just like GNU Screen, but is distributed under a BSD license. On Mac you should be able to grab it from Homebrew: $ brew install tmux To start a session, run tmux from the shell: $ tmux new -s <session-name> I'm using Ctrl-T as the prefix to start tmux commands. In tmux terminology, window is basically a tab, and pane is like a split screen. Ctrl-T ccreates a new window Ctrl-T qdeletes the current pane Ctrl-T " "moves to the next window Ctrl-T ssplits window horizontally Ctrl-T vsplits window vertically Ctrl-T $renames the current session Ctrl-T ddetaches from the current session Ctrl-T (h|j|k|l)moves to the pane in the direction Ctrl-T Ctrl-Tmoves to the next pane Ctrl-T (1..9)moves to the window Ctrl-T }swaps the current pane Ctrl-T Ctrl-arrowmoves the current window in the direction # map vi movement keys as pane movement keys bind h select-pane -L bind j select-pane -D bind k select-pane -U bind l select-pane -R We will also bind arrow keys with modifier later. Powerline Next, I'm adding a cool statusline using Powerline. This requires Python, so install it. $ brew install python This installs Python 2.7.6. Even thought the documentation says install powerline with --user, on Mac doing so results to and error, so install it without --user: $ pip install git+git://github.com/Lokaltog/powerline Downloading/unpacking git+git://github.com/Lokaltog/powerline .... To point to the packages define SITE_PACKAGES environment variable in zshrc.osx: export SITE_PACKAGES=/usr/local/lib/python2.7/site-packages/ Now we can add the following line to tmux.conf: source $SITE_PACKAGES/powerline/bindings/tmux/powerline.conf One cool thing about a tmux session is that it keep running in the background even if your terminal is no longer connected. So you can use Ctrl-T $ to rename the current session, and then do the following to disconnect, list the sessions, and attach back. $ tmux detach $ tmux ls $ tmux a -t vim-memo To get more info about tmux, see tmux cheatsheet. Vim Vim is a text editor. On Mac you can grab Vim using homebrew. For a plugin we would need Lua support: $ brew install vim --with-lua There are a lot of key bindings to go through around Vim. It doesn't help that I'm adding plugins because I then would need to remember the key bindings I'm setting for them as well. plain vim things There are some nice resoure for learning vim I've only read a few chapters of Practical Vim, but it already changed my thinking on Vim. Coming from other editors, it's easy to think of Insert mode as the main mode, and the rest of the modes are there for other operations. On the contrary, vim's resting state is Normal mode. The analogy used by Drew Neil is that a painter does not rest with a brush on the canvas. This applies true to programming activities like navigating through code and pondering about it. The fact that Normal mode is the resting state gives equal keyboard opportunities to searching and moving. It also lets us think about the act of inserting a text in a chunked way. In a vim way, the act of typing something into a buffer is going to Insert mode => type something => coming back to Normal mode. This mini-program is automatically stored inside vim that can be recalled using " .". Similarly, search within the current line can be repeated using " ;". val foo = "method("+arg1+","+arg2+")" Given a line of code like the above, Tip3 explains that we can search for " +" using f+, overwrite it with " +" using s + Esc, and then repeating the process by typing ;. three times. navigating between the windows I can't list out all the feature included in Vim, but one of more helpful things to know is :help command. You can pass an argument like :help window to find all about windows. Because of plugins and just for programming in general, we'd need to deal with split windows, which I was not familiar with. Similar to tmux, there's a prefix and a subcommand that follows it: Ctrl-W ssplits the current window horizontally Ctrl-W vsplits the current window vertically Ctrl-W q(or :q) closes the current window Ctrl-W (h|j|k|l)changes the focus to the window in the direction Ctrl-W (arrow)changes the focus to the window in the direction vimrc Similar to zshrc, vimrc is split into multiple scripts for better organization. " basics source $HOME/dotfiles/vimrc.basic " extra source $HOME/dotfiles/vimrc.extra " indentation source $HOME/dotfiles/vimrc.indent " moving source $HOME/dotfiles/vimrc.moving " searching source $HOME/dotfiles/vimrc.search " status line source $HOME/dotfiles/vimrc.statusline " neobundle source $HOME/dotfiles/vimrc.bundle " plugin settings source $HOME/dotfiles/vimrc.plugins " unite source $HOME/dotfiles/vimrc.unite " colors source $HOME/dotfiles/vimrc.colors To find out the existing key bindings, use one of the following ex commands: :map :nmap :imap :vmap Shougo/neobundle.vim NeoBundle is a Vim plugin manager. All I have to do is name the github project name, and it takes care of the rest. This is one of the many Vim plugins written by Shougo who also calls himself the Dark Lord of Vim. Shougo/unite.vim The unite.vim plug-in can search and display information from arbitrary sources. Here are some blog posts introducing unite.vim: - Unite.vim, the Plugin You Didn't Know You Need - Replacing All The Things with Unite.vim - Vim Ctrlp Behaviour With Unite). So the first thing I wanted to do using unite.vim was to emulate Ctrl-P functionality in SublimeText. Ctrl-P and Ctrl-N are actually frequently used key bindings for previous and next, so I'm going to define spacebar as the prefix for unite.vim, and use <space>f for files. " Unite let g:unite_enable_start_insert = 1 nmap <space> [unite] nnoremap [unite] <nop> let g:unite_data_directory = '~/.unite' call unite#filters#matcher_default#use(['matcher_fuzzy']) call unite#filters#sorter_default#use(['sorter_rank']) " File searching using <space>f nnoremap <silent> [unite]f :<C-u>Unite -no-split -buffer-name=files -profile-name=buffer -auto-preview file_rec/async:!<cr> Because I'm using -no-split here the list of files will be displayed in the current window. This is considered more Vim, because Vim is a modal editor. Pressing enter would take the default action, which in this case is opening the file. Pressing tab shows more actions like displaying the file in a split window. Building on this, we can define some useful commands like grepping using the silver searcher. if executable('ag') let g:unite_source_grep_command='ag' let g:unite_source_grep_default_opts='--nocolor --nogroup -S -C4' let g:unite_source_grep_recursive_opt='' elseif executable('ack') let g:unite_source_grep_command='ack' let g:unite_source_grep_default_opts='--no-heading --no-color -C4' let g:unite_source_grep_recursive_opt='' endif " Grepping using <space>/ nnoremap <silent> [unite]/ :<C-u>Unite -no-quit -buffer-name=search grep:.<cr> " Yank history using <space>y let g:unite_source_history_yank_enable = 1 nnoremap <silent> [unite]y :<C-u>Unite -no-split -buffer-name=yank history/yank:<cr> " Buffer switching using <space>s nnoremap <silent> [unite]s :<C-u>Unite -no-split -buffer-name=buffers -quick-match -auto-preview buffer:<cr> " Buffer and recent using <space>r nnoremap <silent> [unite]r :<C-u>Unite -no-split -buffer-name=mru -quick-match buffer file_mru:<cr> " Bookmark using <space>b nnoremap <silent> [unite]b :<C-u>Unite -no-split -buffer-name=bookmark bookmark:<cr> " Add bookmark using <space>x nnoremap <silent> [unite]x :<C-u>UniteBookmarkAdd<cr> " Everything using <space>a nnoremap <silent> [unite]a :<C-u>Unite -no-split -buffer-name=files buffer file_mru bookmark file:<cr> " Help using <space>h nnoremap <silent> [unite]h :<C-u>Unite -no-split -buffer-name=help help:<cr> autocmd FileType unite call s:unite_settings() function! s:unite_settings() let b:SuperTabDisabled=1 imap <buffer> <C-j> <Plug>(unite_select_next_line) imap <buffer> <C-k> <Plug>(unite_select_previous_line) " Double tapping <Esc> closes unite nmap <silent> <buffer> <Esc><Esc> <Plug>(unite_exit) imap <silent> <buffer> <Esc><Esc> <Plug>(unite_exit) endfunction Shougo/neomru.vim Unite.vim is extensible via other Unite plugins, which are themselves Vim plugins. One of them is neomru.vim for most recently used files. tsukkee/unite-help unite-help is an unite source for help files. All of Vim features are documented as helpful text files, and this allows me to look them up using <space>h. For example, to look up key bindings on window commands, I can type <space>h and on Unite enter :wincmd. This tells me that I can make the current window by wider <C-w>10>. Shougo/vimfiler Vimfiler is a file explorer. Not sure how much I would need it, but I use SublimeText's file navigation sidebar enough that I figured I'll have something similar. Here's how to display a file explorer in a split window on by typing backslash e: " vim.filer {{{ if neobundle#is_installed('vimfiler') " Enable file operation commands. let g:vimfiler_safe_mode_by_default = 0 let g:vimfiler_as_default_explorer = 1 nnoremap <silent> <Leader>e :<C-U>VimFiler -buffer-name=explorer -split -simple -winwidth=35 -toggle -no-quit<CR> nnoremap <silent> <Leader>E :<C-U>VimFiler<CR> " .... endif " }}} Inside the vimfiler: ?displays help adisplays the list of actions Ncreates a new file Kcreates a new directory Shougo/neocomplete.vim neocomplete provides keyword completion system by maintaining a cache of keywords in the current buffer. I also tried YouCompleteMe, but it didn't work as well. Shougo/neosnippet.vim neosnipplet provides snipplet support. It also integrates with neocomplete. The actual snipplet templates are available from neosnippet-snippets. You can check out what's in scala.snip: $ cat ~/.vim/bundle/neosnippet-snippets/neosnippets/scala.snip | less snippet match abbr match {\n case .. => .. match { case ${1} => ${0} } .... Here's from the keybinding recommended in the README: " neosnippet {{{ if neobundle#is_installed('neosnippet.vim') " Plugin key-mappings. imap <C-k> <Plug>(neosnippet_expand_or_jump) smap <C-k> <Plug>(neosnippet_expand_or_jump) xmap <C-k> <Plug>(neosnippet_expand_target) endif " }}} If I open a .scala file, and type match<Ctrl-k> it expands into a match-case. Shougo/vimshell.vim vimshell is a shell written purely in Vim script. Apparently having a shell running inside the editor can come in handy. For one thing, text can now be yanked back from the REPL without going through some contraption: Now we can define a keyboard shortcut to start it up quickly. " vimshell {{{ if neobundle#is_installed('vimshell') nnoremap <silent> <Leader>s :<C-U>VimShell -buffer-name=shell -split -toggle<CR> let g:vimshell_user_prompt = 'fnamemodify(getcwd(), ":~")' endif " }}} Similar to file explorer, backslash s will now toggle a shell window. While the integrating shell with Vim could be interesting, it's really not the same as running Zsh. Also, even for just running sbt, I noticed that up arrow key is bound to something else so history completion of sbt didn't work. Shougo/vimproc.vim vimproc is also required to use vimshell. There's a manual step required to install this plugin, but it should be taken care of as the following NeoBundle entry: NeoBundle 'Shougo/vimproc', { \ 'build' : { \ 'windows' : 'make -f make_mingw32.mak', \ 'cygwin' : 'make -f make_cygwin.mak', \ 'mac' : 'make -f make_mac.mak', \ 'unix' : 'make -f make_unix.mak', \ }, \ } This requires you have GNU make on the path as make. About arrows Vimmers often say "don't use arrows." This makes sense because you're basically giving up on using mouse/trackball/touchpad type of device, and you don't want to be using arrows 1000 times to get around 1000 lines of code. Vim needs to navigate based on other sementics like page, block, or by searching for some keywords. Having said that, arrows combined with modifiers are pretty convenient way to navigate outside of the text editting context, like switching between windows. We have three navigation that we care about: - tmux windows - tmux panes (split window) - Vim windows (split window) Configuing the arrows correctly requires some knowledge into all of the layers that we introduced. Here are some of the links that helped me: - How do I find out what escape sequence my terminal needs to send? - How to get shift+arrows and ctrl+arrows working in Vim in tmux? - Where do I find a list of terminal key codes to remap shortcuts in bash? When you hit an arrow key with some modifier, Terminal.app needs to know what sequence of character it needs to send to Zsh. One of the convention is "xterm style", which is: <Esc> + "1;" + <modifier key> + ("A" | "B" | "C" | "D") Where <Esc> is \033, <modifier key> is: - 2 <Shift> - 3 <Alt> - 4 <Shift-Alt> - 5 <Ctrl> - 6 <Shift-Ctrl> - 7 <Alt-Ctrol> - 8 <Shift-Alt-Ctrl> and - A <Up> - B <Down> - C <Right> - D <Left> with the exception of <Alt-Left> and <Alt-Right>, which are given <Esc>B and <Esc>F. Not all mappings are present in the default Terminal.app setting, but we can add them manually: Next, this setting is needed in tmux.conf to forward them into Zsh running inside: # pass through Shift+Arrow set-window-option -g xterm-keys on Now we can also configure tmux window and pane movements: # control arrow to switch windows bind -n C-Left previous-window bind -n C-Right next-window # prefix control arrow to move windows bind -r C-Left swap-window -t -1 bind -r C-Right swap-window -t +1 # use ctrl-shift-arrow keys without prefix key to switch panes bind -n C-S-Left select-pane -L bind -n C-S-Right select-pane -R bind -n C-S-Up select-pane -U bind -n C-S-Down select-pane -D To move between the Vim windows, here's vimrc.moving: " moving " Use Shift-arrows to select the active split! noremap <silent> <S-Up> :wincmd k<CR> imap <S-Up> <Esc><S-Up> noremap <silent> <S-Down> :wincmd j<CR> imap <S-Down> <Esc><S-Down> noremap <silent> <S-Left> :wincmd h<CR> imap <S-Left> <Esc><S-Left> noremap <silent> <S-Right> :wincmd l<CR> imap <S-Right> <Esc><S-Right> if &term =~ '^screen' " tmux will send xterm-style keys when its xterm-keys option is on execute "set <xUp>=\e[1;*A" execute "set <xDown>=\e[1;*B" execute "set <xRight>=\e[1;*C" execute "set <xLeft>=\e[1;*D" endif This allows you to move between Vim windows using <Shift>-arrow keys in both Normal and Insert mode. These may be flagged as a newbie keybinds because I'm leaving my hands off the home position, but so far I'm finding them handy. Ctrl+S to save Another keybinding that's newbie-like but I find it useful is Ctrl-S for saving files. " map <C-s> to :update noremap <silent> <C-S> :update<CR> vnoremap <silent> <C-S> <C-C>:update<CR> inoremap <silent> <C-S> <C-O>:update<CR> Powerline Since we've put in Powerline for tmux, we're using it for Vim too. I added this at the end of vimrc.bundle: set rtp+=$SITE_PACKAGES/powerline/bindings/vim sickill/vim-monokai A lot of the experience on SublimeText comes from Monokai. vim-monokai is a port to Vim color scheme. derekwyatt/vim-scala For Scala syntax support I'm using Derek Wyatt's vim-scala. Combined with Monokai, it looks like this: kana/vim-smartinput vim-smartinput is a plugin for automatically completing the parens and quotes like SublimeText tyru/caw.vim caw.vim aka comment anywhere, is a plugin for commenting out lines of code. " caw.vim {{{ if neobundle#is_installed('caw.vim') nmap <Leader>c <Plug>(caw:I:toggle) vmap <Leader>c <Plug>(caw:I:toggle) endif " }}} I'm assigning backslash c to toggle commenting and uncommenting. MattesGroeger/vim-bookmarks vim-bookmarks is a plugin for managing bookmarks. It works like visual marks, except you can manage bookmarks by the working directory. mmtoggles bookmark mnjumps to the next bookmark in the buffer mpjumps to the previous bookmark in the buffer summary This was a personal memo on listing out links and settings. Much of the credit goes to people like yuroyoro and Shougo. I'm not sure how long it would take for me to get comfortable enough to make Vim my main editor, but at least I wrote this post using Vim.
http://eed3si9n.com/vim-memo
CC-MAIN-2019-18
refinedweb
3,447
55.54