text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringlengths 9
15
⌀ | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
---|---|---|---|---|---|
Old thread: >>61776941
What are you working on, /g/?
>>61784776
Dumb cat
>>61784776
getting a job
>>61784776
Smart cat
>>61784776
cat
>>61784892
Oh Shit Got To Poop
>>61784776
/dpt/ - Daily pooinloo thread
After learning several languages and not liking them, I am overcome with the desire to make my own language.
How do I overcome this common malaise?
well, I don't know shit about compilers or machine logic anyway, my gripes are mostly syntactical ones.
Why couldn't early programmers do a sensible thing and leave all the performance features a programming language in the machine code domain, with syntax being a parser/interpreter layer of abstraction for the end programmer? All languages would just compile to intermediate binary code, which then would be optimized and compiled into machine code by a unified compiler.
Then we could even do freaky shit like syntax being defined by the local settings of the IDE, so every programmer could use his own syntax, even within the same project on the same codebase.
I guess you could still make a syntactical wrapper around C or something.
what lightweight laptop would you recommend for some 2d and low poly 3d gamedev?
as long as it can run ide/blender/unity/ue4 that would be great.
Discuss.
(reposting from last thread)
I FUCKING HATE WEB DEV AKA WEBSHIT REEEEEEEEEEEEE
BUT IT'S THE ONLY VIABLE PLATFORM TO ACTUALLY MAKE SHIT ON OTHER THAN MOBILE WHICH IS EVEN GAYER REEEEEEEE
>>61785000
Not enough
>>61784986
>After learning several languages and not liking them
Which languages?
>>61785011
C/C++ and Python, mainly
>>61784902
rude
>>61785000
No one can beat Stroustroup in book thikkness. That's why he's the king.
Common Lisp is the only good language.
Too it's dynamically typed and there's no good implementation.
>>61785000
You can only write so much about something as featureless as C
>>61785011
I've written in C, Python, Pascal, JS, ADA and C#.
As weird as it sounds, I liked Pascal the best, but it has lots of problems of its own. I think the way it internally uses pointers, but abstracts the mess away with function parameter flags is great. But the way it treats arrays and loops is clunky as fuck.
ADA was hell to work with, I think they went too far in a few places with the safety and verbosity. But unique closing blocks for each type of block such as (endif, endfor, etc) is also a great idea.
>>61785103
>unique closing blocks for each type of block such as (endif, endfor, etc)
Worst idea ever
>>61784988
please respond dev-kuns
>>61784988
maybe try agdg?
Can one just fork GCC and modify the parser only as to change the syntax without altering the inner workings of the language itself?
>>61784776
That's a cute kitty
I think Rust made a mistake by abandoning many C/C++ conventions for no reason. Is it hard for people to start using a new syntax? Yes, very hard.
I've been wondering about ways to hide audio messages in innocent music clip videos.
Basically I'd like to merge two audio streams A and B in such a way that a youtube viewer would hear a lightly distorted stream A, and a program could decode it to stream B in realtime. And this method would have to survive youtube's reencoding, so it should be signal methods and not bit based methods.
I have found some papers which I find relevant.
A WAVELET DOMAIN LSB INSERTION ALGORITHM FOR HIGH
CAPACITY AUDIO STEGANOGRAPHY
Any particular ideas on this?
>>61785184
GCC can compile many languages and has many targets.
You should see how to add new GCC frontend, might not even require modyfing GCC itself.
>>61785103
These are all Algol-type languages. Try ML-like (Ocaml or F#), Haskell and Lisp (Racket or CL).
>>61785001
>>>/g/wdg
damn... i just did and they sent me to g
>>61785184
you can't do anything with GCC's source except for compiling it
Started learning Python today as my first scripting language. This is surprisingly fun and rewarding.
>>61785193
It is not very hard to learn a new syntax. You're just retarded.
>>61784289
Its not off the shelf, its a cheap Chinese knockoff
What would you suggest learning with? I have a lot of time soon
Trying to get the hang of it before starting a programming course in September.
Today I realized that in C# 'Console' is the same class as any other and WriteLine is a method like any other.
Believe it or not, it makes things (i.e. understanding the concept of classes and methods) much clearer for me.
>>61785386
cool
>>61785184
It's possible, you can modify the parser so that *your* concrete syntax would generate the same AST as the correspondent standard C's syntax. After that you can just reuse all the immediate code generations and backends of GCC.
But of course it's not practical especially if you just have silly gripes with an ancient language's syntactic quirks. You'd have an easier time defining new CPP's macros to implement your own """syntax""". That was how Stroustroup originally implemented C++ and that was why C++ started out shit and only gets worse as time goes by, because its originator is a fucking hack.
>>61785386
Yeah, but keep in mind that you're typically using static methods on Console, like Write, which allows you to call a method that belongs to a class without creating an instance of that class to use. Those are going to work a little differently, and be designed differently, than non-static methods made to work on a unique instance.
>>61785193
Rust's syntax borrows a lot from ML's family, so yeah it's easy for me. But if you can't even handle something as trivial as the syntax differences how could you handle its completely different type system? Just man the fuck up my anon-kun.
>>61785563
I rather have problems with the user interface design that the syntax encapsulates. It seems most syntax is the way it is to appease the parser and the compiler, not to appease the programmer or achieve some kind of usability goals.
It's just poor interface design and I don't like it aesthetically. My idea is that the syntax should be a concise and internally consistent design language for controlling the compiler behavior.
>>61785619
perhaps he's fine with it but is worried that these choices will restrict its popularity
>>61785169
It's easier for the parser though, as silly as it sounds the ``dangling ifs'' was an actual parser implementing problem.
>>61785651
Nah, beside the lexer, the parser is just the tiniest and most trivial part for pretty much every compiler (even toy ones) in existence. C's syntax being this way is just solely of historical reason.
>>61785651
>controlling the compiler behavior
You don't control the compiler behavior with syntax though. Most of the code generation, static analysis, IR rearrangement and optimization, backend code generator's interfacing and linking have nothing to do with the language's syntax.
Syntax is not anything complicated, it's just that once you defined a concrete syntax it's really hard to make posthoc changes. That's why languages like Scheme and Lisp are so valuable.
>>61785721
>>61785770
Question is, why is something so superficial also so tightly embedded into the language that it can't just be changed on the fly.
Why isn't there an intermediate parser output or something.
Damn, I'm so smart with my hindsight.
>>61785822
>Why isn't there an intermediate parser output or something
There are, they are call abstract syntax tree, IR code and backend code. The problem is there are already a fuckload of softwares written in the old ``surface'' syntax that wouldn't build anymore if you just nonchalantly changed it.
In languages where you can directly access and modify ASTs like the Lisp languages, you can change the syntax to suit your taste, especially if you have reader macros like in Common Lisp.
>>61785619
I'm skeptical that Rust will be the next big thing. So like others I think I won't make that huge time investment. It would be easier if the syntax was C/C++/Java like.
>>61785992
stay left behind then punk
>>61785898
Hol up, what if you like, build your codebase into the intermediate language and store it as that, with IDEs or whatever interface just decoding it into your syntax of choice?
Damm, I'm so smartta
inheratance is a worse form of composition
>>61785822
A lot of bigshot compiler implementations of other languages reuse GCC's and LLVM's code generation as their backend, so yeah alternatively you could make your own language and do just that.
>>61786078
It's called decompilation and if you have ever looked at a decompiler's output, you'll realize you aren't that smart after all.
To be honest I feel like I'm talking with a clueless sophomore with too much confident in himself or something. Just learn that damn undergrad compiler course before trying to reinventing the wheel for the 2^64th time ``please''.
>>61786121
>clueless sophomore with too much confident in himself
Unironically the correct description of 90% of /dpt/fags
>>61786121
lmao I bet decompilation is just a problem of implementation, especially from an intermediate binary stage
it's just that nobody was smart enough to do it right
before me
my iq is one of the hifhest
>>61786190
Ok.
:^)
I have just found out there existed sanic hegehog videos games on android, and I couldn't resist looking inside since android reverse engineering is easy and fun.
So it's implemented in a x86 library on top of openGL ES, symbols are present, and java decompilation gives signatures of JNI entry points.
So I'm sure a sufficiently dedicated autist could dlopen that library and wrap that into a Linux desktop game without great difficulty.
What is the Klossiest programming language/ framework?
>>61786307
Probably Ruby!
>>61786307
I just saw her in a youtube ad selling some premade webshit app.
I think she gave up programming because it's too hard.
>>61786307
Must be this
>>61786361
>I think she gave up programming
she never started. its just propaganda.
>>61785037
Read SCIP, if you find scheme boring you need another profession.
>>61786361
>>61786373
Kut her some fucking slack, she's not even 25 yet.
>>61785011
Try Rust!
>inb4 HURR DURR SJW
It's open source, no SJWs control it.
I've misjudged Python like so many others
>>61786526
in what way?
>>61786502
>It's open source
/g/ should fork it and make it not shit then
Call it /g/ust
>>61786538
Let's call it /g/arbage then, for the lack of a garbage collector means its eternal reign as the shittiest language in existence!
>>61786421
She is 25 and some days.
>>61786267
Hello Christian.
I am garbage collector pilled now.
Trying to manually manage your memory is like trying to manually optimize your code. Why bother if the compiler/GC is going to do it a million times more efficient than you? Wasted effort.
>>61786612
Use Rust and have the compiler do it for you at compile time without any overhead!
>>61786533
nah jk
>>61786586
>make it not shit
Why are you on 4chan when you lack the reading comprehension of a 12 year old
Underaged b&
>>61786656
>make it not shit
Because it's impossible for /g/ to make anything equally or less shitty.
>>61786598
>i missed karlie's birthday
I really fucked up, /g/.
>>61786653
based
Is there a way to automatically organize source files in VS?
Like when my function definitions are not in the same order as the header declarations?
No spectrum comments.
>>61786370
The fruits of liberal faggotry.
Why is it bad to sizeof() a char?
>>61785274
Keep at it
>>61786927
it's always 1, i do it anyway because it's more readable
>>61785274
Good for you anon, have fun with snek
>>61786927
Is guaranteed to be 1, so it's pointless. It just clutters up code.
Trying to write some I2C bare-metal code for an STM32 platform. I'm really considering switching to an OS, does anyone know an extra lightweight one who's been ported to Cortex-M ?
>>61786983
Why? Making a special condition check for char will clutter up your code
>>61786930
>>61786978
Day 1 of self-study, burned through 2 chapters of Matthes' book on Python. At page 70 of 562. Going to take a break for a while, then get at least one more chapter in today. This is going swimmingly. If I keep up this solid pace, I'll be done before the month is over!
Thanks for the well-wishes!
>>61787033
>special condition check for char
What special condition?
It's almost always blatantly obvious that what you're allocating is a string, even without the sizeof(char).
Typical uses would be// Functionally equivalent to strdup
char *dup = malloc(strlen(str) + 1);
strcpy(dup, str);// Functionally equivalent to asprintf
int len = snprintf(NULL, 0, "%d%d%d", a, b, c);
char *str = malloc(len + 1);
sprintf(str, "%d%d%d", a, b, c);
A sizeof(char) doesn't add anything meaningful.
>>61784986
>Then we could even do freaky shit like syntax being defined by the local settings of the IDE, so every programmer could use his own syntax, even within the same project on the same codebase.
Sounds cool at first, but do you trust pajeet to come up with his own syntax that makes sense to others? It would make collaborative programming an absolute clusterfuck.
>>61784988
Maybe check out an X or T-series Thinkpad. As long as you get an i3 or higher, it should do the job.
>>61785274
You picked a good choice, anon.
>>61786307
>>61786316
The banner on her coding camp's website has a Ruby extension. Good guess.
>>61787157
>Sounds cool at first, but do you trust pajeet to come up with his own syntax that makes sense to others? It would make collaborative programming an absolute clusterfuck.
Well, it wouldn't matter, since the actual source code would be in binary, displaying it in a given syntax would just be a local user decompilation stage. You just open the binary source and your IDE translates it to the syntax of your choice.
>>61787214
LLVM :)
>>61787234
LLVM has the Fatal Flaw of not being invented by me.
>>61787256
Just fork LLVM then? That's the point of FOSS, just take credit for it.
>>61787119
>What special condition?
For getting the byte size of an arbitrary variable, which is the whole point of sizeof. The whole point is that sizeof works with any object. If I'm writing a function to validate an arbitrary variable, I'm not going to write a break case just for a char type.
>>61787214
So the Git repo or whatever source control would have a preset syntax too, but could then be decompiled when it's cloned to the user's local? Might be an interesting way to add my own syntactic sugar to the language. Or could a Java programmer use this to make C# "look like" Java, assuming someone takes the time to make a syntax tree for them.
>>61784776
I have to use some baby IDE called BlueJ for a dumb intro to programming course.
Now I not only have to program in Java, but I have to program clicking on stuff.
It's so fucking braindead.
>>61787408
See no reason the Git repo wouldn't contain the intermediate binaries, with each user just choosing a pre-set or user-defined display syntax like one would choose a color scheme on a website.
>>61787363
>size of an arbitrary variable
Keep doing that then. You're taking this argument out of proportion. It's not a case of "Don't ever do this, it's completely terrible and can break everything", it's just a preferred style thing because it could be pointless. If a sizeof(char) or something gets generated by a macro or whatever, it's not anything to even be bothered about.
I think taking the size of a variable directly is always appropriate (and preferable to taking the size of a type directly), even if the variable is a char. It allows you to change things later, like changing the string a wide string or something easily later.
The argument is really against cases where you're allocating a string or "raw" data in terms of bytes and putting a sizeof(char) in the malloc expression.
>>61787489
Or if there's a problem of browser bloat or PC performance, store several decompiled versions in most common syntaxes or whatever.
Wait, this is getting dumb.
>>61785037
Try Go or Ruby!
What's a good IDE for learning C? I don't want it to autocomplete, just to run stuff without having to go into terminal/commandline and use gcc
I already know Java and Python, so it's more specifically learning C and lower level language material than learning to program, to be clear.
Gonna learn nodeJS so I can get a memejob and hopefully escape the pajeets of my javashop. What's a good free html editor? Or at least a cheap one?
>>61787595
>without having to go into terminal/commandline and use gcc
The command line is honestly the best way.
Just set up a simple build system (plain makefiles work fine), and compiling your program is as simple as typing 'make'.
>>61787630
vim
>>61785193
I don't understand how Rust syntax is different? I've only learnt a bit of Rust and it doesn't seem to be much different at all. I actually like Rust because it has a lot of my favourite features which appear in other languages.
>>61787630
Literally any text editor. Sublime will do fine, Atom or VSCode if you don't mind a heavier editor that looks better out of the box.
>>61787055
what IDE is that?
>>61787673
I meant more like a modern GUI builder. Surely we must have moved on from the mid 2000s?
For higher level languages like python, is it bad practice to change a variable's type
for example
a = 1>61787595
If you absolutely need an IDE, then Code::Blocks or Qt Creator will do okay.
Otherwise, I highly recommend learning with the command line. I remember when I was working on my Bachelor's being in a networking class where we had to write a program that would snoop on connections passing through it and filtering the data, and displaying results in a TUI using curses. At least a few of the students had no clue why it was that they were running into errors not finding certain symbols from curses when "they included the right header files." They were apparently unaware of the role of the linker and how to link a third party library.
I honestly can't find the ability to respect people who neither understand nor desire to understand their build process. If you want to be a C programmer, you should know the basics of how your compiler and linker work, and know how to use a build tool. Once you understand how everything works, it's really as simple as just typing make all the time.
>>61787426
what college?
>>61787873
It's bad practice for any programming language to do that.
>>61787942
>>61787873
Dynamic typing was a mistake.
>>61787992
What's the idea behind dynamic typing?
Is it really that hard to declare your variables before using them?
>>61787899
R-Ruby senpai, .... why d-don't you learn .... R-Rust! I-I started l-learning it and i-it is .... v-very comfy!
>>61787740
It's Geany.
Very pleasant experience so far. Looking forward to continuing with it.
>>61788067
I have actually learned a bit of it. It's a nice language, though it is missing a few features I'd like to see in it as a systems language. But given that they just added untagged unions, I'd say they're probably not done adding features. I'm not sure if I'd use it as a primary programming language, but I've been keeping tabs on it and watching its development.
>>61788032
I will never understand why in javascript you have to define a variable with var instead of a real data type or just omit var entirely
>>61787873
Please don't do that.
>>61788190
Well, I would imagine it would help with scope. Say we declare some variable foo in global scope. Now we assign foo to something else in a function scope. Are we mutating the global variable or starting a new variable? If we declared it with var, we'd be making explicit that this is a new scope, would we not?
That said, I'm not JavaScript expert. I've played around with it, but never used it for much and never delved deep into the language. Web programming isn't my thing.
>>61788190
All data is data, just ones and zeros that can't be distinguished without knowing what it is already. Assembly itself has no data types either.
JS, in it's shitty introduction to the world, never had the bright idea to allow easy use of data types like int or double, despite almost every other language already having that feature.
For why you need var itself, i assume >>61788233 is probably correct, since it still needs to be called for scope reasons.
Found this little snippet on Stack Overflow.// These are both globals
var foo = 1;
bar = 2;
function()
{
var foo = 1; // Local
bar = 2; // Global
// Execute an anonymous function
(function()
{
var wibble = 1; // Local
foo = 2; // Inherits from scope above (creating a closure)
moo = 3; // Global
}())
}
Looks like I was right.
>>61788256
>despite almost every other language already having that feature.
Yes, well, its creator was a big fan of Lisp, the father of dynamic typing.
>>61788419
>globals
absolutely disgusting.
>>61787426
Like clicking on your majestic cherry blue keyboard
>>61788436
They have their purpose, but should be used sparingly. Personally, I like Ruby's approach: using symbols on the variable name to indicate the scope. $foo is a global, @foo is an instance variable, and foo is a local variable. @@foo should be avoided in favor of a class level instance variable.
>>61788478
>They have their purpose,
no they dont.
What is a good way too learn Python? I bought "Learn Python the Hard Way" but a friend said the author's a hack for making me use Python 2 and Notepad++
>>61788497
I take it you've never done concurrent programming?
>>61788497
You're right instead of globals you should use the singleton pattern (TM) or alternatively pass a handler to every single class.
>>61788553
Pearson Publishers, Starting out with python is the best if you have never programmed before. Yes, Zed Shaw is a cunt.
Mark Lultz learning python is okay but lacks substantial exercises, so maybe give that a miss.
>>61788553
Literally just start writing shit in your spare time for the purpose of learning the language. Read the hitchhikers guide to python, and effective python, and really any book. Nothing wrong with learning 2.7 but you should save yourself the trouble and just skip to 3.x
>>61788606
>you need globals for concurrency
wow ruby, you become more of a baka every day
>>61788630
It's not that one NEEDs it, it's just that it makes the problem of sharing data a lot easier.
>>61788691
use a language with modules.
>>61788629
Listen to this. Python 2 is just not worth learning anymore unless you have to for work. Generator functions introduced in 3 are so useful.
Learning linear regression with python. I ended up wasting a lot of time on an aside in matplotlib: you can draw a line of best fit pretty easily for 1D linear regression by just runningplot(X, Yhat), but a drawing a plane of best fit for a 2D linear regression is more challenging, sinceplot_surface(X1, X2, Yhat)for mplot3D takes data in as 2D coordinate matrices instead of just a list of points.
>>61788695
what's that?
>>61788843
whats what?
Realistically speaking, if someone with a great github portfolio has an anime avatar, are they automatically unemployable?
>>61788843
Nothing really desu. Basically a language where static is default.
Modules are a pain in the ass and don't really add any value. They just end up discouraging you from making new files.
>>61788860
modules in languages
>>61788130
I've been using Geany for a couple years. I like it.
>>61788695
Namespacing data doesn't make it any less global in practice. Incidentally, Ruby does have modules. Nonetheless, there are still some times when it might make sense to make a global, and it would honestly be silly just to make a module to act as a container for it.
>>61788868
Only if the avatar is cute.
Is this a linked list in Rust?use IntList::{Node, Empty};
// This program defines a recursive data structure and implements methods upon it.
// Recursive data structures require a layer of indirection, which is provided here
// by a unique pointer, constructed via the `Box::new` constructor. These are
// analogous to the C++ library type `std::unique_ptr`, though with more static
// safety guarantees.
fn main() {
let list = IntList::new().prepend(3).prepend(2).prepend(1);
println!("Sum of all values in the list: {}.", list.sum());
println!("Sum of all doubled values in the list: {}.", list.multiply_by(2).sum());
}
// `enum` defines a tagged union that may be one of several different kinds of values at runtime.
// The type here will either contain no value, or a value and a pointer to another `IntList`.
enum IntList {
Node(i32, Box<IntList>),
Empty
}
// An `impl` block allows methods to be defined on a type.
impl IntList {
fn new() -> Box<IntList> {
Box::new(Empty)
}
fn prepend(self, value: i32) -> Box<IntList> {
Box::new(Node(value, Box::new(self)))
}
fn sum(&self) -> i32 {
// `match` expressions are the typical way of employing pattern-matching,
// and are somewhat analogous to the `switch` statement from C and C++.
match *self {
Node(value, ref next) => value + next.sum(),
Empty => 0
}
}
fn multiply_by(&self, n: i32) -> Box<IntList> {
match *self {
Node(value, ref next) => Box::new(Node(value * n, next.multiply_by(n))),
Empty => Box::new(Empty)
}
}
}
>>61788909
So I'm fine with an ugly grandma avatar?
>>61788890
>modules and globals are the same things
Alright, heres your last (you)
>>61788909
there was a guy who used to post here that is programmer god
and his github has this picture
>>61788936
No, you are only employable if your avatar is cute!
Cleaned up my pretty printer a bit. Next step is adding unions.
>>61788868
All you have to do is
>Dye your hair any tone of cool colors
>Identify as a pneumosexual unsigned turboxir
>Have a github that does pull requests on random projects
>Your only contribution should exclusively be renaming "problematic" variable names or comment into safe space mellow words
Now you're hired by Google, all you have to do to keep your free allowance is pretend to do something twice a year
>>61788982
when i wrote my compiler i printed my AST with dots
likeroot
..program
....class
.......id(gcd)
>Senior / Lead NodeJS Developer
>£100,000 - £120,000 per annum
This is modern C++constexpr auto x =*
(f1 | f2)--[1_p - U - 6_p]--(f3)
(f4)--[2_p , 5_p]--(f5)
(f6)--[3_p - _ - 4_p]--(f7);
If you don't know what this does then you don't know C++
>>61789092
>If you don't know what this does then you don't know C++
I'm not sure I want to
>>61789092
Pattern matching on a bunch of functions?
>>61789092
why would anyone want to know what this garbage does
>>61789092
I'm glad I don't desu.
I feel dirty when I write a quasiquote, let alone doing shit like that.
>>61789092
>If you don't know what this does then you don't know C++
Like everything else in that godforsaken language, some feature some other language had that somebody somewhere wanted so they implemented a half-functional, never-going-to-be-used version of it so they can say "YEAH BUT SEPPLES CAN DO IT TOO!!!!!!" no matter how arcane or hacked together it is.
>>61788944
A module's name is globally accessible, and typically its members are too. A variable kept in a module might not be called a global variable, but for all practical purposes, it is one. Using a singleton has the same effect. All you're doing is adding an extra step to accessing a variable that is accessible from any function with a shared state.
>>61788925
>>61788982
Post your other monitor
>>61789092
Not knowing the types of any of these variables, nor knowing the definition of the _p user defined literal, it is impossible for anyone to know what that code does from just that snippet.
>>61789292
Well if you insist
⣰⣾⣿⣾⣶⣶⣷⣷⡄
⢠⣸⣿⣿⣿⣿⣿⣼⣻⣯⠷⣕⡄
⢰⣿⣿⣿⣿⣿⣧⡵⣝⣿⣽⣵⡼⠰
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦
⢻⣿⣿⣿⣻⣻⣻⣻⡿⡿⡿⣿⡰⠐
⢀⣬⣿⣿⣿⣿⣿⣿⣿⣿⠛⢐⠐
⣾⣿⣿⣶⣦⣿⣿⣿⣿⣿⣿⣿⣿⣿⣰
⢤⣽⢿⣻⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣷⣧⡀
⢠⡠⣖⣶⣶⣿⣾⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣿⣿⣿⣦⡀
⣜⡻⣿⣾⣿⡿⡿⣠
⢐⠶⣕⠦⢀
⢂⣿⣿⣿⣿⣿⡺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠐
⢢⣻⣿⣿⣿⡧⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠐
⡳⣿⣿⣿⣇⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠐
⠘⢮⢻⢿⣿⡜⣞⡿⣿⣿⣿⣿⣿⣿⣿⣟⡰
⠑⡳⣶⣳⡣⠒⠩⣐⣰⢛⡛⣿⣿⣿⠰
⢈⣞⡿⡁⢀⠪⢻⣿⡯⡀
⠐⠦⠮⢨⢨⡑⡈⡂⡑⠡⠡⡁⡃⢅⣑⡩⡩⠭⠫⠫⠣⠦
⠰⣀⠒⠒⢠⢠⢀⠐⢐
Is this valid C? Because I tested it and it works.#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
int *arr = malloc(sizeof(int) * 10);
int *d = arr;
for (i = 0; i < 10; i++)
*(arr++) = i;
for (i = 0; i < 10; i++)
printf("%d\n", d[i]);
return 0;
}
>>61789456
dumb karenposter
>>61789456
No. You're writing out of the bounds of the memory allocated to you. Your code isn't segfaulting out of luck. Malloc could theoretically return a region close to a page boundary where you'd get burned.
>>61789456
looks about right, but you forgot to free arr
>>61789501
How is it allocating to out of bounds memory?
>>61789501
not him, but how so? arr is only incremented after writing i, so there's never an out of bounds write
>>61789456
Looks like valid C to me.
>>61784776
>jquery
>>61789521
t. NEET
>>61789521
It's a cat; it doesn't know any better.
>>61784776
>setTimeout
>hard coded URLs
>setting height in JS
>ES5
>>61789501
dumb rustposter.
>>61787055
Consider this:# every time you "add" strings, they get copied, so this is a big waste of resources and time. BUT, this
message = person.title() + " " + "has" + " " + str(beans) + "beans!"
# is the same as this
message = " ".join((person.title(), "has", str(beans), "beans!"))
# or this, if you like C syntax
message = "%s has %s beans!" % (person.title(), beans)
# there's also str.format, but if you're running a newish version it's basically obsoleted by these (also called format strings)
message = f"{person.title()} has {beans} beans!"
>>61789521
>>61789537
what's wrong about that?
>>61789514
>>61789513
Oh fuck I misread. Yeah it's fine.
>>61789501
>Malloc could theoretically return a region close to a page boundary where you'd get burned.
Could it give you a region close to a page boundary? Yes. Would it burn you? No. You likely wouldn't even notice the performance hit from the kernel having to swap pages in and out.
>>61789619
I'm pretty sure he was implying that the page won't be mapped to anything.
>>61789619
I thought he was moving down the array twice desu.
I almost always use array syntax for pointers so I saw 2 ++'s and alarm bells started ringing desu. 10 elements is also small enough that if there was the error I imagined there being, it probably wouldn't crash.
Also page boundary crossings are so overblown. God forbid if I get a cache miss there's a little more indirection once every 4096 bytes.
>>61789591
jquery is a big download you'll use 5% of (check axios for ajax)
setTimeout will make a nightmare of your application state when used with animations - if you have to do that, use Promises so you know when they're done
Hard coded URLs are sloppy and create a surface to introduce 404s (that code would break if the site was deployed to /asdf/ instead of /)
Use flexbox instead of setting height in JS, or at least add a window resize hook
ES5 is high school tier
>>61784776
Where does /g/ go to look for part time work?
>>61789721
There's a good bridge near me I beg/hook under
>>61789721
the grocery store
>>61789721
>inviting 60 more people to your gold mine
c++ or python better
>>61789765
Totally different uses. Python is scientists and C++ is video game devs.
>>61789456
You probably already know this, but in the general case, if you write the first loop like thisfor (i = 0; i < 10; i++)
arr[i] = i;
it will be easier for the compiler to optimize.
>>61789778
It also has less mutation going on so retards like me are less likely to misread it.
>>61789775
so which one is better
>>61789862
Totally different uses. Python is scientists and C++ is video game devs.
>>61789878
so which one is better
Guys how do I convince my boss to move back to Java after he decided to move to Scala? The compile times are killing us
>>61789892
Totally different uses. Python is scientists and C++ is video game devs.
>>61789775
Python, since it can do everything it's intended to do just fine with a okay syntax and no real major fuckups
C++ can do only half of each of those.
>>61789905
pooe on his chair
>>61789905
>The compile times are killing us
explain
>>61789905
tell him the compile times are killing you
STOP ABANDONING MEEEEEEE
>>61789946
I have done, he just says they won't be so bad in the next version of the language
>>61789928
It was a metaphor
>>61789974
do people here actually use c or is it a meme like gentoo
ok, say I want my job to be something like this:
i like to solve difficult problems and learn skills, but I'm not an entrepreneur with original ideas. I'd like to realize someone's idea for an application with my own skills (which I don't have yet but you get what I mean). that's what a programmer/"software engineer" does, right? also what language would you learn for this type of programming job?
>>61789989
I use C
>>61789989
It's part of /g/ fedoracore.
>>61790010
i see
>>61785213
Why
>>61789913
Oh yeah I agree. Getting a job in the game dev industry is retarded. And you shouldn't use C++ if you're indie; C++ is used because "industry standard" not because it's the right tool for the job. You can really feel the resentment game engine designers like Mike Acton have for C++.
>>61789990
>that's what a programmer/"software engineer" does, right?
Most software engineer roles are very tedious. You are expected to do the same frontend/backend/sql shit every day for the rest of your employment.
I think you are looking for more of a "research assistant" position. If you land an intellectually-stimulating job with only a bachelor's degree, you've hit the jackpot.
please make your next app a cli app and help put an end to gui tyranny
>>61790039
>tinder app in the terminal
>>61789989
I'm learning it right now to do some linux stuff
>>61790010
As far as I'm concerned, C *is* programming.
>>61790039
>wanting to be limited by cli
>>61790084
Writing a compiler in assembly is programming
I have now begun the process of reprogramming my taste buds.
>>61790087
I'd prefer everything to run in emacs but I don't think most people are ready for that yet.
>>61789975
So be rational. If it's amounting to like 15 minutes of your day, time your coffee run with a build. If it's taking a lot more, then tell your boss it's going to affect how productive your team is until that next version addresses your concern.
>>61790117
d-do you have a test case for semen? I can provide the sample~
>>61790029
Well, that's disappointing if true...
>>61789801
Retards like this? >>61789501
>>61790295
No that guy eats paint I'm not that retarded anon.
What is the programming equivalent of this?
>>61790361
C#
somebody please post the "Microsoft Certified Solutions Expert" image
>>61790156
If I needed that, I am more than capable of producing it myself. Anyways, the whole idea is to get myself used to not drinking something super sweet with every meal, like soda or fruit juice. And I'm going to try and replace it with possible bitter things like black coffee and unsweetened tea.
>>61790123
Emacs hurts my hands.
>>61790376
try tap water, it's still a little sweet
>>61790376
>Emacs hurts my hands.
Have you tried using a more ergonomic keyboard and/or evil mode?
>>61790361
>monkeys
It's Java, no doubt about it.
>>61790417
Jaba dev, can confirm.
>>61790376
why do americans always drink so much sugar water?
>>61790027
If you're an indie developer, the best language to learn now is Java.
Can someone explain to me why callbacks are considered asynchronous in various javascript frameworks? I keep seeing them say the meme catchphrase "functional programming" and I don't remember lisp being considered an innately asynchronous or parallel language.
>>61790393
Honestly, tap water has not much real taste. Although if you freeze it into a solid bottle of ice and let it slowly melt, it's pretty delicious.
>>61790399
>different keyboard
I use a laptop. I'd rather not use a USB keyboard, and I don't want to add another criterion on for my already picky needs for laptops.
>>61790454
Because sugar is arguably more addictive than cocaine, and it's everywhere here. We grow a fuckload of corn in the mainland, which we turn into syrup since people can only eat so much actual corn.
>>61790477
Java is gross. Don't use it unless you need it for Android or for some enterprise job.
>>61790539
They are "functional programming" in that you're passing functions around, using functions in interesting ways, whatever (a callback is just a function that runs after another function returns)
Functional programming is a much broader category, and you're right, not necessarily async
>>61790571
Fuck off tripidiot.
>>61790571
>I use a laptop.
Oh shit. Why? They're terrible for you.
>Because sugar is arguably more addictive than cocaine
You could try replacing it with a healthier habit. Do you like hot peppers?
New trippie coming through, please be nice to me!!!
More girls in coding, yay!!! (ᴗ)
>>61790589
How new are you?
>>61790599
Jessica is a unisex name
>>61790571
>freeze it into a solid bottle of ice and let it slowly melt
i can't stand cold stuff (or really hot stuff either)
lukewarm or bust
>>61790599
pls sex me
>>61790586
Then how do async callbacks in nodeJS work? Is a new thread somehow spun up every time a callback is called? They keep saying you don't have to wait for a function to return because asynchronous but I'm beginning to think no one actually understands what it's doing and they're just shitposting because I keep seeing the same stupid console.log example in the explanations.
>>61790599
>girl on /g/
Nice try :^)
>>61790611
>if a tripfag attention whores for long enough then it's not a bad thing that they're attention whoring
???
i will never understand this retard logic
>>61790571
disregard this i suck cocks
>>61790632
Ruby has a decent amount of programming knowledge from what I've seen
>>61790650
Xhe's a complete autist outside of /dpt/ though, every time I look at the board there's some post by Ruby responding to either blatant sarcasm or obvious trolls and generally dragging the quality of the board down by enabling these sorts of shitposts.
>>61790679
Well that's because /dpt/ is the best part of /g/ by far.
>>61790598
>Why?
Because I don't want to be confined to a desk and every tablet that doesn't have Surface Pro in its name is terrible.
>hot peppers
Honestly I hate them, although cayenne pepper's alright in small amounts.
>>61790599
So what programming languages do you know? What's the most interesting thing you've programmed? Also, niceness needs to be earned. This is 4chan, not Reddit.
>>61790616
That is an odd taste. Cold makes everything better.
>>61790641
At least bother to spell everything right including the A at the end and the ! before Sempai.
>>61790571
Why do you produce so much corn? I heard that you have tight control over how much sugar can be important and the government buys any excess sugar is produced. Corn syrup sounds like such a disgusting substitute for sugar.
>>61790722
>Corn syrup sounds like such a disgusting substitute for sugar.
You have no idea, if you ever go to America stay far away from anything containing """"sugar""". I'm not a big fan of soda in the first place, but boy American coca-cola was a new low. Tastes like literal shit, no wonder anyone with any sort of functioning tastebuds over there imports sugary drinks/food from 1st world countries that actually use sugar.
>>61790621
Look up "node event loop". There's a queue of callbacks, and each time the loop runs it goes through the queue, running any callbacks it can, and leaving the ones that can't execute yet in the queue.
Let's say your main thread does these two things (in shitty pseudocode):get_data_from_server().then(process_that_data());
console.log('i just ran');
First, node reads line 1. It sees that get_data_from_server runs asynchronously, and it adds process_that_data() to the callback queue.
Next is line 2. We print the message to the console.
Finally, we get the data back from the server (because doing this took longer than executing line 2). So we run the callback now, and remove it from the queue.
>>61790722
We grow so much fucking corn because it's just what grows in this climate, and we clearly have buyers (soda companies). Anyways, corn syrup sucks, but cane sugar isn't that much better.
>>61790722
Midwest here, there is nothing wrong with growing a metric fuckton of corn
>>61790803
You have sugar cane in Florida. Why does your government fucking claim they believe in shit like free market, yet does protectionist bullshit over sugar plantations or basically any product?
>>61790819
What is point of growing corn? Can't you grow something else like pumpkins or cows or some shit?
>>61790722
The united states has had a communist agricultural system since the great depression. The farm czars have decided that corn is worthy to be produced.
Also the farm czars set the price of sugar. The price of sugar in the US is higher than market value.
Corn syrup is pretty close to sugar desu. It's dissolved in water and instead of sucrose you have fructose + glucose but otherwise it's the same as sugar.
>>61790571
>tap water has not much real taste
Tap water has the realest taste.
>>61790833
Corn is more suitable than pumpkins and cows because it's more vertical and needs less space. But yeah sugarcane would be way better but fucking farm czars.
This is definitely not me being biased because I live in Texas where sugarcane grows really well. It grows well all along the south. Hot as fuck + humid as fuck = sugarcane.
>>61790833
Corn is love, corn is life
Welcome to the cornfields motherfucker
>>61790833
Because it's a bullshit government and nobody likes it. Seriously, it's almost a national pastime to bitch about the government.
>>61790833
>Can't you grow something else like pumpkins or cows or some shit?
Oh yeah, that's another reason to grow so much corn: feeding livestock. And yeah, we raise a lot of cows here.
>>61790839
Isn't sucrose just fructose and glucose?
Employed Haskell programmer reporting in
>>61790769
Okay, I see. That's actually pretty simple. The fact that there's a queue for the callbacks pretty much explains everything. Not sure why a million blogs can't just explain it so straightforward and transparently.
Thanks anon
>>61790904
Sucrose is those two bound together along a glycosidic bond. They taste a little different but about the same thing.
Don't do the fallacy of composition anon. Sugar is made out of carbon and water but you aren't going to be able to replace it by sticking coal and water in a blender.
>>61790955
>you aren't going to be able to replace it by sticking coal and water in a blender
Sounds like that's Ruby's end goal.
>>61790833
>yet does protectionist bullshit over sugar plantations or basically any product?
Because almost every other government has protectionist bullshit over everything too and it gives them an advantage over a nation that doesn't have any such policies. I swear libertarians are as bad as commies. It doesn't work in practice because the world is bigger than your backyard.
>>61790930
I am also employed, and am also a Haskell programmer
>>61790930
And where are you employed, Anon? What is your job title?
>>61790981
Nah, my end goal is to make things that taste bitter not taste bitter to me, and to stop craving sugar.
>>61790985
The farming practices of the USA are not protectionist at all. It's just good old fashioned corruption. Big corn lobbies congress. Congressmen protect big corn. Congressmen magically end up with money, speeches with outrageous fees, free dinners, free golfing trips, etc.
>>61791011
So things like broccoli?
How do I make my game engine/framework not require hamachi just to connect to each other (peer to peer).
Other than hosting a web server obviously
>>61791163
Just wondering if there's any way other than port forwarding or VPN or server
>>61791107
Broccoli isn't bitter at all. It's pretty damn good.
>>61791185
You still need a server but you can do:
The server doesn't need to host the game though. I think this is what hamachi is.
>>61791290
Yeah I meant that one of the players/clients would host a lobby from their computer (which wouldn't have a public IP)
I'll give that a read thanks
>>61791011
> What is your job title?
Cock sucker.
>>61788130
Thanks dude
>>61791372
What you do is you setup a server just for holepunching that redirects users to the player's local lobby. It's basically running your own hamachi but probably better because making users download hamachi to use your program to its fullest is shit desu.
>>61791384
I ain't judging, if you can make an easy living off the fact that you happen to be gay then good for you
>>61791410
Yeah that's what I figured.
Just sucks because I'm poor lmao.
Thanks :)
r8 muh m8kefile.RECIPEPREFIX = >
.PHONY: all executable objects dependencies\
clean-executable clean-objects clean-dependencies clean
EXECUTABLE = gdraw
COMPILER = g++
CFLAGS = -g -c -O0 -Wall -Wextra -Werror -Wold-style-cast -std=c++14
DFLAGS = -MM -o [email protected]
LFLAGS = -o $(EXECUTABLE)
LIBS = -lGL -lGLU -lglut -lm
LANGUAGE = cpp
SOURCES = $(wildcard *.$(LANGUAGE))
OBJECTS = $(patsubst %.$(LANGUAGE),%.o,$(SOURCES))
DEPENDENCIES = $(patsubst %.$(LANGUAGE),%.d,$(SOURCES))
all: executable
executable: $(EXECUTABLE)
objects: $(OBJECTS)
dependencies:
> @:
$(EXECUTABLE): $(OBJECTS)
> $(COMPILER) $(LFLAGS) $(OBJECTS) $(LIBS)
%.o: %.$(LANGUAGE)
> $(COMPILER) $(CFLAGS) $<
%.d: %.$(LANGUAGE)
> $(COMPILER) $(CFLAGS) $(DFLAGS) $<
.PRECIOUS: $(DEPENDENCIES)
clean-executable:
> rm -f $(EXECUTABLE)
clean-objects:
> rm -f *.o
clean-dependencies:
> rm -f *.d
clean: clean-executable clean-objects clean-dependencies
-include $(DEPENDENCIES)
>>61791394
No problem.
>tfw feeling welcomed from becoming part of /dpt/ in one day of learning Python.
>>61791440
You could probably get away with using your home Internet connection desu. A domain name should cost like 20 bux a year.
The amount of data that such a server needs to send is really really fucking minimal. And if not you can get away with a really low bandwidth server. There's severs that are a dollar a month.
What happens if use your home desktop as a web server?
>>61791512
Yeah I don't have a home internet connection lol.
Situation is complicated.
But I'll be looking at hosting in a few months.
>>61791495
>g++
>-std=c++14
>-lGL
>-lGLU
>-lglut
>cpp
0/10 kill yourself
So in line 8, the middle statement is supposed to check something, right? what does s[i] check?
>>61791660
It checks if the current char is 0 ('\0')
>>61791495
>C++
>Non-standard names for standard variables
It's shit.
>>61791660
'\0' which is equivalent to "null" which is falsey, terminating the loop.
>>61791660
cool beans
Working on Minecraft clone. Added polymorphism to the right click action.(define slab-upgrades `((,stone-slab ,stone) (,grass-slab ,grass)))
(define permeable (list air water))
(define (slab-player-place! kind world state x y z side . extras)
(if (and (equal? side TOP) (equal? (finite_getblock world x y z) kind))
(place-block! world (cadr (assoc kind slab-upgrades)) state x y z)
(let* ((coords (getneighbor_coords x y z side))
(replaced (apply finite_getblock world coords)))
(if (equal? kind replaced)
(apply place-block! world (cadr (assoc kind slab-upgrades)) state coords)
(if (member replaced permeable)
(apply place-block! world kind state coords))))))
(make-block-class stone-slab player-place!: slab-player-place!)
(make-block-class grass-slab player-place!: slab-player-place!)
And this is the class if you're wondering:(define* (make-block-class
block-kind
(break!: break! dumb-break!)
(place!: place! dumb-place!)
(player-place!: player-place! dumb-player-place!)
(update!: update! dumb-update!)
(update/now!: update/now! dumb-update/now!))
(let ((rtn
(lambda (proc . args)
(case proc
((update/now!) (apply update/now! block-kind args))
((update!) (apply update! block-kind args))
((place!) (apply place! block-kind args))
((break!) (apply break! block-kind args))
((player-place!) (apply player-place! block-kind args))))))
(hash-table-set! block-class-table block-kind rtn)
rtn))
>inb4 oop memes
It just werks for things that are actual objects. Like blocks in a minecraft clone.
>>61791914
I hope you're a fursecutor.
How do we stop this?
>Node.js Emerging as the Universal Development Framework for a Diversity of Applications
>>61792033
By putting the javascriptlets out of business.
Invest heavily into wasm. After that's done, replacement "full stack" technology that isn't javascript.
>>61792033
Write to the editor and tell them that they misused the word diversity.
string calibornifier() {
static vector<string> const canon = {
"YALDABAOTH",
"YALDOBOB",
"YOLOBROTH",
"YODELBOOGER",
"YOGURTBONER"
};
string prefix = canon[rand()%canon.size()];
string suffix = canon[rand()%canon.size()];
return prefix.substr(0, prefix.find('B')) + suffix.substr(suffix.find('B'));
}
// YOLOBONER
// YALDOBOOGER
// YODELBAOTH
// YOGURTBOB
>>61792086
This seems overengineered.
>>61785213
At firsthought this is what I'dd do:
The encrypted audio has to a lot shorter then the other one
You strech the short audio so it fits the long ones length with some function in the form g(1/n * x)
Add the signals together, the distortion should be low, bc of the transformation
To extract, do it in reverse:
Subtract original audio from the one that has a meseage
Aply a function in the formnof g^-1(n*x)
You should have the original meseage audil
>>61785213
You could vocode the audio reducing the amount of data you need drastically, then embed the output channels as low frequency elements of the waveform, as humans are insensitive to low frequencies.
Vocoders are proven technology for low quality signals. Not to mention the output is going to sound like kraftwerk too so that's a bonus.
>>61785213
Whatever you're doing would have to make it past the psycho-acoustic model yt uses to compress the audio channels. Depending on the source material, I don't think there's enough bandwidth for you to do it in the audio channel.
However, you also have a video channel, which has a lot more bandwidth. You could perturb parts of the image stream, watermark-style, to send a low-bandwidth, redundantly-coded side channel. I don't know how much bandwidth you could get out of such a scheme, but with both the audio and video channels perturbed, it just might be sufficient for a tightly compressed mono voice channel.
>>61791966
Your program is shit if it isn't programmed in Rust.
>>61792351
I'd rather it be shit than programmed in Rust desu.
But if you wanna write a rust program that can dynamically load both compiled executables and source code and invoke a repl that can touch the program state, be my guest anon.
>>61791966
cool
>>61791966
Very nice.
Are you procedurally generating the map?
>>61792526
The terrain generation is very simple and currently just 2 dimensional pink noise. Anything below the noise value is grass and anything below block that isn't grass is water.
I've mostly been focusing on adding technical features. I'm not too worried about creating a profound terrain generator right now since doing that wouldn't improve the underlying engine.
>>61785103
Ada is the shit, at least for embedded / safety stuff. I much prefer Ada to C for writing code that could kill someone due to bugs.
>>61792551
>anything below block that isn't grass is water
Anything below y=64 that isn't grass is water. Augh.
>>61787003
Why not use the HAL? You don't need an rtos for i2c on a cortex-M.
>>61792657
I've been studying Python, and it's going well.
I made some parts more complicated for the purpose of reinforcing what I'm learning, and everything is still running fine. Though, I'm having trouble figuring out how to capitalize all items in a list. Would someone please give me some advice? I had to resort to adding the 'title' method to each item in advance instead of as a group.
>>61792558
>Ada is shit
FTFY
>>61792676
Have you not learned how to iterate over items in an array/list?
How do static and inline relate in C? Why would I declare a function that is inline but not static? Are there problems with defining static inline functions in header files?
>>61792797
>Why would I declare a function that is inline but not static?
You have a function that is called from many other files and overhead from the function call is limiting speed
>>61792797
>Why would I declare a function that is inline but not static?
Non-static inline functions are really weird. Actually, extern inline, "plain" inline and static inline all have slightly different semantics.
- static inline
Inline the function in this translation unit; no external symbol is produced.
- "plain" inline
Create an alternative implementation of an external function for this translation unit; no external symbol is produced, and the which function gets called (the inline or external function) is unspecified.
MAYBE this could be used to create a faster/more efficient version of some function (perhaps with less error checking?), but the functions should semantically be the same.
The standards committee probably were trying to create more useful functionality when they thought this up, but it's really just unnecessarily confusing.
- extern inline
Inline the function in this translation union, but also generate a normal symbol that other translation units can use.
>Are there problems with defining static inline functions in header files?
No, it's perfectly fine. Overdoing it can lead to long compile times and possibly executable size bloat.
An inline function really should at max 3 lines long.
>>61792758
I've been able to capitalize everything else so far. I'd clarify, but my post keeps getting detected as spam, and don't know what to do to circumvent it. Refer to the last line in the picture in my last post, and imagine I want to add a title method to it. That's been breaking it.
>>61792888
Cheers, that clears it up nicely.
I have two programs in the same git repository, a server and a client. They have some shared data they need to load, but then they also have files that are different (like config files).
I would like to make a directory for that shared data and create a symlink out of each program's run directory to it. But mklink on Windows seems to have some problems, mostly that it requires admin privileges. What could I do not to duplicate the data by copying it into the run folders of both applications?
>>61792941
>I would like to make a directory for that shared data and create a symlink out of each program's run directory to it.
Just put it in some well-known location and read it from there. That's what a normal program's installation does.
New thread:
>>61792971
>>61792971
>>61792971
>>61792960
I don't want the installation to put anything outside of the program's own directory, and I don't want to have to intall it after every build while debugging, so I need the paths to be relative to the run directory.
>>61792981program/
├── client/
│ └── prog
├── server/
│ └── prog
└── shared_data
>>61792997
But that's not the structure the program will be distributed in, so once the actual shipping build is made, all the relative paths will be different.
>>61793025
Or programs*, rather. In the shipped form, I want each one of the two programs to have their executables in the root directory, and then a separate data folder. And they're distributed separately.
>>61792941
Why not environment variables or command-line flags to override what will ship?
>>61793037
I do use those to for example set LD_LIBRARY_PATH on Linux to the current directory. But I can't really think of a way to move link data directory into the run directory with those.
>>61793077
Well, it seems like you can create directory junctions without admin privilieges, so guess I'll use those.
How do you reverse-sort a list temporarily in Python? This is what I have so far, but I'm unsure of how to add the reverse argument in this case:
color_list = ['red', 'blue', 'green']
print("Here is the original color list:")
print(color_list)
print("Here is the temporarily sorted color list:")
print(sorted(color_list))
print("Here is the original color list once more:")
print(color_list)
>>61793250sorted(color_list)[::-1]
>>61793294
So it's:print(sorted(color_list)[::-1])
If I want to print that, right? That's what I just did, and it seemed to work. Though, the:[::-1]
segment looked strange to me. The book just stated that temporary reverse-sorting could be done, but not how. Would you please explain that part for me briefly?
>>61793360
It's list slicing.list[x:y:z]returns a new list where x is the starting index, y is the ending index, and z is the increment between indices.list[3:9:2]would get a new list comprising of the 3rd, 5th, 7th and 9th elements of the old one.list[::-1]uses default values of x and y (the final and first elements) and goes down in steps of 1.
>>61793378
That makes perfect sense, thank you! I've snipped a picture of this for future reference.
Why isn't web dev considered programming? What's the logic?
>>61790477
How come?
>>61793619
>>>/wdg/
And don't use php, peasant
>>61793406
If you only need an iterator, though, there's always reversed().
>>61793619
Because front-end is mostly decorating and UX.
And back-end is just connecting wires.
>>61790027
>Mike Acton
How can a guy that looks dawny not be retarded?
>>61789721
>part time work?
Is there other kinds of work? | https://4archive.org/board/g/thread/61784776 | CC-MAIN-2020-45 | refinedweb | 9,933 | 72.76 |
31 July 2012 14:40 [Source: ICIS news]
TOKYO (ICIS)--Japan’s total domestic sales of fuel oils rose by 2.5% year on year to 14.3m kilolitres in June, as many of the country’s nuclear power plants remain shut after the earthquake and tsunami of 11 March 2011, official data from the Ministry of Economy, Trade and Industry (METI) showed on Tuesday.
Among the total, sales of Bunker B and Bunker C fuel oils, some of which is used for electricity, increased 44% to 2.09m kilolitres in June from the same period a year earlier, according to METI’s preliminary report on petroleum statistics.
Imports of Bunker B and Bunker C more than doubled year on year to 588,232 kilolitres, the data showed.
Domestic sales of naphtha, however, declined by 3.2% to 3.27m kilolitres in June from the same time the previous year, while imports fell by 6.8% to 2.07m kilolitres, according to the ministry.
Meanwhile, ?xml:namespace>
The country imported 15.4m kilolitres of crude oil in June, a 6% increase from the year-before period, according to METI.
Imports of crude oil | http://www.icis.com/Articles/2012/07/31/9582594/japans-june-domestic-fuel-oil-sales-rise-by-2.5-year-on-year.html | CC-MAIN-2014-49 | refinedweb | 193 | 75.61 |
This.
What is Java anyhow?
We should probably delve into what exactly Java is. This isn’t a simple question and could quite quickly lead us down the proverbial rabbit hole. Instead, I’ll focus on the most important points.
Java is a programming language
In English we know that sentences start with capitol letters and end with periods, question marks, or exclamation points. We know the basic sentence structure of “subject verb noun”. Sentences can be collected together to communicate complex messages. This is the syntax of English. All human languages have their own syntax.
All programming languages also have their own syntax. Java code is written in Java’s syntax. Unlike spoken languages, a programming language’s rules are very strict. In English, a missing comma isn’t the end of the world. The reader can usually intuit what a writer is trying to communicate, even if their grammar isn’t perfect. However, computers do not have intuition. They require very precise and particular instructions, communicated in exactly the right manner. Missing even a single semicolon in Java will prevent your program from working at all.
The programming language Java is the syntax you use to tell the computer what you want it to do.
This is an example of the most basic Java program. When compiled and run (more on this in a bit) it will print out the words “Hello, world!”.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world!"); } }
This file must be named HelloWorld.java for it to compile.
What is a compiler?
Computers only speak one language: Binary. Ones and zeros. That’s it. A CPU receives instructions in binary and does exactly what the instructions tell it to do. Unfortunately, humans don’t speak binary. Perhaps we could memorize it?
Back in the dark ages of programming, this is essentially what programmers did. Mnemonics, known as assembly code, were created that humans could more easily memorize. A programmer would write assembly code and later manually translate it to binary.
No mere mortal wants to manually translate assembly code to binary. Good programmers are often lazy, and so eventually programs were created to automatically translate assembly code into binary instructions. These were the first compilers.
A compiler takes source code written in a programming language and translates it into binary code. Over time, compilers matured and added features that led to modern programming languages.
But, there’s a catch! Different CPUs speak different binary languages! This means that we need different compilers for different CPUs. Mix in the complexities of supporting different operating systems, and it becomes very difficult to write a program that is cross platform. A cross platform program is one that can be run on multiple operating systems and CPU architectures.
This is why there so many applications that only run on one platform. An application written to run on iOS on an iPhone can’t work on Android, much less Windows.
The Java compiler
The Java compiler is a compiler. Surprise! As with any compiler it translates Java source code into binary instructions.
The command line program we use to compile java code is is javac. This can be executed on the command line like this:
The result of running the Java compiler on a .java file is a new file with the same name, but with a .class extension. The .class file is what contains the binary code.
The Java compiler comes with the Java Development Kit, which must be downloaded and installed before Java programs can be compiled and run.
However, unlike traditional compilers that write binary instructions for a particular CPU and OS, the Java compiler writes its own dialect of binary called Java bytecode. Java bytecode isn’t created for any particular CPU or OS. By itself, Java bytecode is useless. We need something else to make it useful.
The Java Runtime Environment
Since a Java program is not compiled for a specific CPU or OS, we can’t simply execute it like any other program. Instead, we need a Java Runtime Environment (JRE). This is the “Java” that your computer is constantly bugging you to update.
The JRE is actually a virtual computer. It simulates the CPU and hardware of a real computer. Just like any other CPU, Java’s virtual CPU has its own instruction set. This instruction set is Java bytecode! As the JRE executes your program, it actually compiles the Java bytecode into CPU-specific binary instructions that your computer can execute. This process is called Just in Time (JIT) compiling. A handy side effect of this is that Java bytecode can be executed anywhere the JRE can be installed, regardless of hardware or operating system.
You can run a compiled Java .class file using the java command line program. The syntax is:
java &amp;amp;lt;Class Name without .class extension&amp;amp;gt;
For example:
Through this process of JIT compiling, the JRE effectively hides from the programmer everything that makes a particular CPU or OS unique. The computer itself becomes a black box to a Java developer. We no longer care what CPU or OS we’re using. We no longer care about the implementation, we only care that it works. The JRE takes care of everything else for us.
This process of hiding implementation details is called abstraction. Abstraction is a key theme in programming.
The Java Development Kit
The Java Development Kit is key to all of the above. It provides everything we need to make Java applications. In particular, the JDK provides the javac command we use to compile Java code.
The JDK also includes the JRE, which provides the java command we use to execute Java bytecode. Many other useful tools are included for debugging, analyzing code, and packaging applications for distribution.
So, what is Java?
Java is a collection of tools used to compile and execute code written in the Java programming language. | https://doughughes.net/2017/02/22/what-is-java/ | CC-MAIN-2018-34 | refinedweb | 997 | 59.5 |
Game with Pearls
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1431 Accepted Submission(s): 527
Problem Description
Tom and Jerry are playing a game with tubes and pearls. The rule of the game is:
1) Tom and Jerry come up together with a number K.
2) Tom provides N tubes. Within each tube, there are several pearls. The number of pearls in each tube is at least 1 and at most N.
3) Jerry puts some more pearls into each tube. The number of pearls put into each tube has to be either 0 or a positive multiple of K. After that Jerry organizes these tubes in the order that the first tube has exact one pearl, the 2nd tube has exact 2 pearls, …, the Nth tube has exact N pearls.
4) If Jerry succeeds, he wins the game, otherwise Tom wins.
Write a program to determine who wins the game according to a given N, K and initial number of pearls in each tube. If Tom wins the game, output “Tom”, otherwise, output “Jerry”.
Input
The first line contains an integer M (M<=500), then M games follow. For each game, the first line contains 2 integers, N and K (1 <= N <= 100, 1 <= K <= N), and the second line contains N integers presenting the number of pearls in each tube.
Output
For each game, output a line containing either “Tom” or “Jerry”.
Sample Input
2
5 1
1 2 3 4 5
6 2
1 2 3 4 5 5
Sample Output
Jerry
Tom
题意:有n个盒子,每个盒子初始有1-n个球,现在要在盒子里添加k的倍数个球,使得最后盒子排序后,第一个盒子有1个球,第n个盒子有n个球
思路:暴力,1-n每个数字是由谁得来的,只要有一个就可以,如果有多个,那么如果满足题意条件,剩下的也必然能转化成其他的
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<set> #include<algorithm> using namespace std; const int maxn=510; int a[maxn]; int N,K; int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&N,&K); memset(a,0,sizeof(a)); for(int i=1;i<=N;i++) { int x; scanf("%d",&x); a[x]++; } bool flag=true; for(int i=1;i<=N;i++) { bool flag1=false; for(int j=0;i-K*j>=0;j++) { if(a[i-K*j]) { flag1=true; a[i-j*K]--; break; } } if(!flag1){flag=false;break;} } if(flag)printf("Jerry\n"); else printf("Tom\n"); } return 0; }
Beam Cannon
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 644 Accepted Submission(s): 234
Problem Description
Recently, the γ galaxies broke out Star Wars. Each planet is warring for resources. In the Star Wars, Planet X is under attack by other planets. Now, a large wave of enemy spaceships is approaching. There is a very large Beam Cannon on the Planet X, and it is very powerful, which can destroy all the spaceships in its attack range in a second. However, it takes a long time to fill the energy of the Beam Cannon after each shot. So, you should make sure each shot can destroy the enemy spaceships as many as possible.
To simplify the problem, the Beam Cannon can shot at any area in the space, and the attack area is rectangular. The rectangle parallels to the coordinate axes and cannot rotate. It can only move horizontally or vertically. The enemy spaceship in the space can be considered as a point projected to the attack plane. If the point is in the rectangular attack area of the Beam Cannon(including border), the spaceship will be destroyed.
Input
Input contains multiple test cases. Each test case contains three integers N(1<=N<=10000, the number of enemy spaceships), W(1<=W<=40000, the width of the Beam Cannon’s attack area), H(1<=H<=40000, the height of the Beam Cannon’s attack area) in the first line, and then N lines follow. Each line contains two integers x,y (-20000<=x,y<=20000, the coordinates of an enemy spaceship).
A test case starting with a negative integer terminates the input and this test case should not to be processed.
Output
Output the maximum number of enemy spaceships the Beam Cannon can destroy in a single shot for each case.
Sample Input
2 3 4
0 1
1 0
3 1 1
-1 0
0 1
1 0
-1
Sample Output
2
2
题意:有n个星星,一个W*H的框,问最多能框住多少星星
思路:线段树扫描线,将每个点抽象成两条线段,我是按y轴方向扫的,这样做的原因是每个点的影响范围有限,见下图。
图中A点可以影响到的矩形是(x,x+W)范围内的,A点抽象成了1,-1这两条线,也就是说明,他纵向能影响到的是这个范围。
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<set> #include<algorithm> using namespace std; const int maxn=40010; const int BIT=20000; int N,W,H; struct Segment { int l,r,h,t; Segment()=default; Segment(int a,int b,int c,int d):l(a),r(b),h(c),t(d){} bool operator<(const Segment &a)const { return h<a.h; } }s[maxn]; struct IntervalTree { int sum[maxn<<2]; int setv[maxn<<2]; void build(int o,int l,int r) { sum[o]=setv[o]=0; if(l==r)return ; int mid=(l+r)>>1; build(o<<1,l,mid); build(o<<1|1,mid+1,r); } void pushdown(int o) { if(setv[o]) { setv[o<<1]+=setv[o]; setv[o<<1|1]+=setv[o]; sum[o<<1]+=setv[o]; sum[o<<1|1]+=setv[o]; setv[o]=0; } } void pushup(int o) { sum[o]=max(sum[o<<1],sum[o<<1|1]); } void update(int o,int l,int r,int q1,int q2,int x) { if(q1<=l&&r<=q2) { sum[o]+=x; setv[o]+=x; return ; } pushdown(o); int mid=(l+r)>>1; if(q1<=mid)update(o<<1,l,mid,q1,q2,x); if(q2>mid)update(o<<1|1,mid+1,r,q1,q2,x); pushup(o); } }tree; int main() { while(scanf("%d",&N)!=EOF,N>0) { scanf("%d%d",&W,&H); int num=0; for(int i=0;i<N;i++) { int x,y; scanf("%d%d",&x,&y); x+=BIT,y+=BIT; int lx=(x+W>40000?40000:x+W); s[num++]=Segment(x,lx,y,1); s[num++]=Segment(x,lx,y+H,-1); } int ans=0; sort(s,s+num); tree.build(1,0,40000); for(int i=0;i<num;i++) { tree.update(1,0,40000,s[i].l,s[i].r,s[i].t); ans=max(ans,tree.sum[1]); } printf("%d\n",ans); } return 0; }
Seam Carving
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 797 Accepted Submission(s): 323
Problem Description
Fish likes to take photo with his friends. Several days ago, he found that some pictures of him were damaged. The trouble is that there are some seams across the pictures. So he tried to repair these pictures. He scanned these pictures and stored them in his computer. He knew it is an effective way to carve the seams of the images He only knew that there is optical energy in every pixel. He learns the following principle of seam carving. Here seam carving refers to delete through horizontal or vertical line of pixels across the whole image to achieve image scaling effect. In order to maintain the characteristics of the image pixels to delete the importance of the image lines must be weakest. The importance of the pixel lines is determined in accordance with the type of scene images of different energy content. That is, the place with the more energy and the richer texture of the image should be retained. So the horizontal and vertical lines having the lowest energy are the object of inspection. By constantly deleting the low-energy line it can repair the image as the original scene.
For an original image G of m*n, where m and n are the row and column of the image respectively. Fish obtained the corresponding energy matrix A. He knew every time a seam with the lowest energy should be carved. That is, the line with the lowest sum of energy passing through the pixels along the line, which is a 8-connected path vertically or horizontally.
Here your task is to carve a pixel from the first row to the final row along the seam. We call such seam a vertical seam.
Input
There several test cases. The first line of the input is an integer T, which is the number of test cases, 0
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<set> #include<algorithm> using namespace std; const int maxn=110; const int INF=0x3f3f3f3f; int N,M; int dp[maxn][maxn]; int a[maxn][maxn]; int path[maxn][maxn]; int main() { int T,cas=1; scanf("%d",&T); while(T--) { scanf("%d%d",&N,&M); for(int i=1;i<=N;i++) for(int j=1;j<=M;j++)scanf("%d",&a[i][j]); memset(dp,INF,sizeof(dp)); memset(path,-1,sizeof(path)); for(int i=1;i<=M;i++)dp[N][i]=a[N][i]; for(int i=N-1;i>=1;i--) { for(int j=1;j<=M;j++) { dp[i][j]=dp[i+1][j]+a[i][j]; path[i][j]=j; if(j-1>0&&dp[i+1][j-1]+a[i][j]<dp[i][j]) { dp[i][j]=dp[i+1][j-1]+a[i][j]; path[i][j]=j-1; } if(j+1<=M&&dp[i+1][j+1]+a[i][j]<=dp[i][j]) { dp[i][j]=dp[i+1][j+1]+a[i][j]; path[i][j]=j+1; } } } int ans,maxv=INF; for(int i=1;i<=M;i++) if(dp[1][i]<=maxv)maxv=dp[1][i],ans=i; bool first=true; printf("Case %d\n",cas++); for(int i=1;i<=N;i++) { printf("%d",ans); if(i!=N)printf(" "); else printf("\n"); ans=path[i][ans]; } } return 0; }
Maze
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 100000/100000 K (Java/Others)
Total Submission(s): 763 Accepted Submission(s): 273
Problem Description
This story happened on the background of Star Trek.
Spock, the deputy captain of Starship Enterprise, fell into Klingon’s trick and was held as prisoner on their mother planet Qo’noS.
The captain of Enterprise, James T. Kirk, had to fly to Qo’noS to rescue his deputy. Fortunately, he stole a map of the maze where Spock was put in exactly.
The maze is a rectangle, which has n rows vertically and m columns horizontally, in another words, that it is divided into n*m locations. An ordered pair (Row No., Column No.) represents a location in the maze. Kirk moves from current location to next costs 1 second. And he is able to move to next location if and only if:
Next location is adjacent to current Kirk’s location on up or down or left or right(4 directions)
Open door is passable, but locked door is not.
Kirk cannot pass a wall
There are p types of doors which are locked by default. A key is only capable of opening the same type of doors. Kirk has to get the key before opening corresponding doors, which wastes little time.
Initial location of Kirk was (1, 1) while Spock was on location of (n, m). Your task is to help Kirk find Spock as soon as possible.
Input
The input contains many test cases.
Each test case consists of several lines. Three integers are in the first line, which represent n, m and p respectively (1<= n, m <=50, 0<= p <=10).
Only one integer k is listed in the second line, means the sum number of gates and walls, (0<= k <=500).
There are 5 integers in the following k lines, represents xi1, yi1, xi2, yi2, gi; when gi >=1, represents there is a gate of type gi between location (xi1, yi1) and (xi2, yi2); when gi = 0, represents there is a wall between location (xi1, yi1) and (xi2, yi2), ( | xi1 - xi2 | + | yi1 - yi2 |=1, 0<= gi <=p )
Following line is an integer S, represent the total number of keys in maze. (0<= S <=50).
There are three integers in the following S lines, represents xi1, yi1 and qi respectively. That means the key type of qi locates on location (xi1, yi1), (1<= qi<=p).
Output
Output the possible minimal second that Kirk could reach Spock.
If there is no possible plan, output -1.
Sample Input
4 4 9
9
1 2 1 3 2
1 2 2 2 0
2 1 2 2 0
2 1 3 1 0
2 3 3 3 0
2 4 3 4 1
3 2 3 3 0
3 3 4 3 0
4 3 4 4 0
2
2 1 2
4 2 1
Sample Output
14
题意:有一个迷宫,格子之间有门或墙,有p种门,S个钥匙,问从(1,1)走到(n,m)最短时间
思路:还是普通的bfs,只不过是加一个状态,保存当前有哪些钥匙
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<set> #include<algorithm> using namespace std; const int maxn=55; int N,M,P,K,S; struct node { int x,y,t; int S; node()=default; node(int a,int b,int c,int d):x(a),y(b),t(c),S(d){} }; int gate[maxn][maxn][maxn][maxn]; int key[maxn][maxn]; bool vis[maxn][maxn][1<<11]; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; int BFS(int sx,int sy) { memset(vis,0,sizeof(vis)); queue<node> q; node B; if(key[sx][sy]) q.push(node(sx,sy,0,key[sx][sy])); else q.push(node(sx,sy,0,0)); while(!q.empty()) { node A=q.front();q.pop(); for(int i=0;i<4;i++) { int tx=A.x+dx[i]; int ty=A.y+dy[i]; if(tx<1||tx>N||ty<1||ty>M)continue; int g=gate[A.x][A.y][tx][ty]; if(g==0)continue; if(g>0) { if(!(A.S&(1<<(g-1)))) continue; } int tmpS=A.S; if(key[tx][ty])tmpS|=key[tx][ty]; if(vis[tx][ty][tmpS])continue; vis[tx][ty][tmpS]=1; if(tx==N&&ty==M)return A.t+1; q.push(node(tx,ty,A.t+1,tmpS)); } } return -1; } int main() { while(scanf("%d%d%d",&N,&M,&P)!=EOF) { scanf("%d",&K); memset(gate,-1,sizeof(gate)); memset(key,0,sizeof(key)); for(int i=1;i<=K;i++) { int a,b,c,d,e; scanf("%d%d%d%d%d",&a,&b,&c,&d,&e); gate[a][b][c][d]=gate[c][d][a][b]=e; } scanf("%d",&S); for(int i=1;i<=S;i++) { int x,y,t; scanf("%d%d%d",&x,&y,&t); key[x][y]|=(1<<(t-1)); } printf("%d\n",BFS(1,1)); } return 0; }
Smart Software Installer
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 471 Accepted Submission(s): 143
Problem Description
The software installation is becoming more and more complex. An automatic tool is often useful to manage this process. An IT company is developing a system management utility to install a set of software packages automatically with the dependencies. They found that reboot is often required to take effect after installing some software. A software package cannot be installed until all software packages it depends on are installed and take effect.
In the beginning, they implemented a simple installation algorithm, but the system would reboot many times during the installation process. This will have a great impact on the user experience. After some study, they think that this process can be further optimized by means of installing as much packages as possible before each reboot.
Now, could you please design and implement this algorithm for them to minimize the number of restart during the entire installation process?
Input
The first line is an integer n (1 <= n <= 100), which is the number of test cases. The second line is blank. The input of two test cases is separated by a blank line.
Each test case contains m (1 <= n <= 1000) continuous lines and each line is no longer than 1024 characters. Each line starts with a package name and a comma (:). If an asterisk (*) exists between the package name and the comma, the reboot operation is required for this package. The remaining line is the other package names it depends on, separated by whitespace. Empty means that there is no dependency for this software. For example, “a: b” means package b is required to be installed before package a. Package names consist of letters, digits and underscores, excluding other special symbols.
Assume all packages here need to be installed and all referenced packages will be listed in an individual line to define the reboot property. It should be noted that cyclic dependencies are not allowed in this problem.
Output
For each test case, you should output a line starting with “Case #: ” (# is the No. of the test case, starting from 1) and containing the reboot count for this test case. (Refer to the sample format)
Sample Input
2
glibc:
gcc*: glibc
uefi*:
gcc*:
raid_util*: uefi
gpu_driver*: uefi
opencl_sdk: gpu_drivergcc
Sample Output
Case 1: 1
Case 2: 2
题意:告诉你软件之间的依赖关系,带*的是需要重启才生效的,问最小重启几次。
思路:转自:hdu5098
很神奇,相当于先把不需要重启的全部按完,然后把暴露在最外面的需要重启的一块按完,重启一次
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<sstream> #include<set> #include<algorithm> using namespace std; const int maxn=10240; int in[maxn],out[maxn],reboot[maxn]; int tot,cnt; int head[maxn]; map<string,int> mp; struct node { int v,next; }edge[maxn]; void init() { tot=cnt=0; mp.clear(); memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); memset(reboot,0,sizeof(reboot)); memset(head,-1,sizeof(head)); } char soft[maxn*10]; void add_edge(int x,int y) { edge[tot].v=y; edge[tot].next=head[x]; head[x]=tot++; } int topo() { queue<int> q1,q2; for(int i=1;i<=cnt;i++) { if(in[i]==0) { if(reboot[i])q2.push(i); else q1.push(i); } } int ans=0; while(!q1.empty()||!q2.empty()) { if(q1.empty()&&!q2.empty()) { ans++; while(!q2.empty()) { q1.push(q2.front()); q2.pop(); } } while(!q1.empty()) { int u=q1.front();q1.pop(); for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; in[v]--; if(in[v]==0) { if(reboot[v])q2.push(v); else q1.push(v); } } } } return ans; } int main() { int T,cas=1; scanf("%d",&T); getchar();getchar(); string s; while(T--) { init(); while(getline(cin,s)) { if(s[0]=='\0')break; istringstream ss(s); ss>>soft; int len=strlen(soft); int flag=0; if(soft[len-2]=='*') { flag=1; soft[len-2]='\0'; } else soft[len-1]='\0'; string id(soft),name; if(mp.find(id)==mp.end()) { mp[id]=++cnt; } reboot[mp[id]]=flag; while(ss>>name) { if(mp.find(name)==mp.end()) { mp[name]=++cnt; } add_edge(mp[name],mp[id]); out[mp[name]]++; in[mp[id]]++; } } printf("Case %d: %d\n",cas++,topo()); } return 0; } | https://blog.csdn.net/u010660276/article/details/46827091 | CC-MAIN-2018-30 | refinedweb | 3,208 | 62.48 |
Bridge to Kubernetes GA.
Simplifying Microservice Development
Microservice applications are comprised of many services, often calling each other. Each service has its own configuration and dependencies, making setting up and running the application locally time-consuming and complex.
By using Bridge to Kubernetes to connect your development workstation to your Kubernetes cluster, you eliminate the need to manually source, configure and compile external dependencies on your development workstation. Environment variables, connection strings and volumes from the cluster are inherited and available to your microservice code running locally.
Develop Microservice Apps Faster
Bridge to Kubernetes extends the Kubernetes perimeter to your development workstation, allowing you to sidestep operational complexities of building and deploying your code into the cluster to test, debug and rapidly iterate.
Docker and Kubernetes configurations are not required when using Bridge to Kubernetes. Simply run code natively on your development workstation using familiar development tools and practices, while connected to the Kubernetes cluster, allowing you to develop, test and debug in the context of the larger application.
Debugging and testing end-to-end
Bridge to Kubernetes enables debugging and testing end-to-end in the context of the larger application. Select an existing service in the cluster to route to your development machine where an instance of that service is running locally. Requests initiated through the application running in Kubernetes will route between services running in the cluster. When the service you are debugging is called, the request is redirected to your development machine to your locally running version. Your local changes are executed, and the request is completed transparently for the other services.
Work in isolation in a shared development environment
In clusters where developers are working together on the same application at the same time, there is a significant risk of interfering with another developers’ debugging session. This is because there is only one copy of each service deployed to the application namespace. To enable developers to work more effectively together and isolate their inner loop from the rest of the team, they need a copy of the service to work on exclusively..
Public Previews
Support for any Kubernetes.
Support for Bridge to Kubernetes on any Kubernetes cluster is initially available in the VS Code experience and soon after in Visual Studio.
Increase confidence in pull requests with review apps
Bridge to Kubernetes lets you work in isolation from colleagues using the same cluster and namespace by leveraging our new routing technology. You can also apply the isolation capability outside the Bridge to Kubernetes experience, such as directly from a GitHub pull request. You can test changes from a PR directly in Kubernetes before the pull request is merged into the main branch of your repo. Having a running application to review changes of a pull request can increase confidence in proposed code changes. Testing your changes in the running application can also help other team members, such as product managers and designers, see the results of the development work even in the early stages.
For more information, including how to get started with the pull request review apps, see here.
Start debugging your Kubernetes applications today using Bridge to Kubernetes. Download the extensions from the Visual Studio and VS Code marketplaces and follow the quickstarts on how to use Bridge to Kubernetes.
We’d love to hear about your experience with Bridge to Kubernetes and where we can improve. For issues or comments, please visit our GitHub issues page.
Does this support debugging of Node apps, or just .NET?
Hi Brian,
Thanks for your question. The Bridge to Kubernetes experience in the VS Code extension is not tied to any specific language. You can use Bridge to debug your Node apps. This quickstart walks you through debugging a node microservice which makes up part of a polyglot application.
Thanks Nick – how does relate/compare to Azure Dev Spaces?
Hi Mike,
Great question.
In short, Bridge to Kubernetes offers many of the key development scenarios Dev Spaces supports, but with an improved lighter weight solution..
Nice. I think I’ve got it now. I’m going to try to find some time with it to see if it can replace my current local dev set-up – that would be a huge win.
Awesome!!! We’ve been missing a tool like this for quite a while, especially with the advent of microservices and the need to just debug/test just a “cell” of the whole system. Both this and Dev Center are wonderful additions to the .net developer toolbelt . Project Tye is worth mentioning too.
This seems like a great tool with lots of increased productivity potential. Looking forward to improvements like,
1. Handling StatefulSets
2. Launch local process that’s being built & ran in VS Code dev containers (get error saying not supported yet)
3. Cmd line to establish/disconnect bridge connection as part of a script rather than from VS Code IDE (couldn’t find documentation if there is a way)
This does not work with Windows containers and MVC applications built on top of .NET framework 4.5+. I don’t even see this option in Visual Studio unless I use a .NET Core project. Even when I tried .NET Core project targeting Windows, the pods goes into error state in Kubernetes. So I guess this works only for .NET Core targeting Linux containers. Do you have any plans to bring support for .NET Framework and Windows containers?
Hi Rav,
Thanks for your question. At the moment, Bridge to Kubernetes is limited to .NET Core targeting Linux containers. We are working through supporting Windows containers and will hopefully have a preview available in the next few months.
What happens if we have a service that connects to an Azure Cosmos DB/SQL Server resource that has a strict firewall configuration, only allowing traffic from the AKS nodes. If I run that service locally using Bridge to Kubernetes, is there a possibility for the outbound traffic to be routed back through the cluster? My observation is that the outbound traffic is directly sent from my development workstation, and is therefore blocked by the firewall.
Any advice for working with a scenario like this?
Nick, I know you’re working in vs team, but did you heard any future support of this feature in vs code ? or vs / OSX ?
Thanks
I’m facing issues when I try to run it in Visual Studio 2019 I get an error: ‘Common port ’80’ is in use on your machine and may prevent Bridge to Kubernetes from forwarding network traffic.’. Can you maybe help me with this?
First, this is AWESOME!! I am really excited to give this a try. And the move to make with work with my On Premises Kubernetes makes me really happy!
Second, I am noticing that VS Code is the IDE that is first getting features (as is the case here with “Any Kubernetes” support).
It seems odd leave the paying customers waiting for the features while you deliver first to the free product line (Visual Studio is not free for most of us).
Is Microsoft starting to shift away from Visual Studio? I have tried VS Code a few times, but always end up preferring Visual Studio. But as I see more and more features coming to VS Code first, I am wondering if I need to force the switch.
Will Bridge to Kubernetes support other IDEs besides Visual Studio and Visual Studio Code, such as IntelliJ or Eclipse? | https://devblogs.microsoft.com/visualstudio/bridge-to-kubernetes-ga/?WT.mc_id=vstoolbox-c9-niner | CC-MAIN-2022-21 | refinedweb | 1,246 | 55.34 |
Bugtraq
mailing list archives
Hi,
It seems that sendmail ran with -t option does NOT block SIGINT ...
In that moment while we are sending data to its stdin, when we will press
CTRL-C process is being killed, but in queue rests unfinished letter.
It stays there quite long - long enought to fullfill partition on disk where
/var/spool/mqueue resides.
When it happends, sendmail doesn't allow new connections - so it is a kind
of DoS attack for this service.
It has been tested on all new versions on sendmail up to current (8.9.3).
Example ...
--- CUT HERE ----
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#define DELAY 5 /* time in seconds needed to reach
MaxMessageSize limit */
#define SM_PATH "/usr/sbin/sendmail -t"
void main()
{
FILE *fd;
int pid;
for(;;) {
if(( pid = fork()) == 0) {
setpgrp();
if(( fd = popen( SM_PATH, "w")) == NULL)
fprintf( stderr, "popen error\n");
for(;;) fputc( 'A', fd);
} else {
sleep( DELAY);
kill( (-1) * pid, SIGINT);
fprintf( stdout, "next\n");
wait( NULL);
}
}
}
--- CUT HERE ---
Regards,
---
Lukasz Luzar K.K.I. lluzar () kki pl
By Date
By Thread | http://seclists.org/bugtraq/1999/Apr/2 | CC-MAIN-2014-10 | refinedweb | 185 | 81.33 |
)
Manish Singh(8)
Manpreet Singh(6)
Gowtham Rajamanickam(4)
Muhammad Aqib Shehzad(3)
Suthish Nair(2)
Gaurav Kumar(2)
Nimit Joshi(2)
Sudhir Choudhary(2)
Karthikeyan Anbarasan(2)
Puran Mehra(2)
Carmelo La Monica(2)
Priyaranjan K S(1)
Fabio Silva Lima(1)
Praveen Kumar Sreeram(1)
Ananth G(1)
Kasam Shaikh(1)
Jignesh Trivedi(1)
Kuppurasu Nagaraj(1)
Prashant Bansal(1)
Arun Goyal(1)
Vignesh Ganesan(1)
Surya Kant(1)
Venkatesan Jayakantham(1)
Rion Williams(1)
Pankaj Kumar Choudhary(1)
Santhi Maadhaven(1)
Vikas Kumar Garg(1)
Chervine Bhiwoo(1)
Mozart He(1)
Neeraj Kumar(1)
Junaid Masoodi(1)
Gaurav Kumar Arora(1)
Celin Smith(1)
Jason Brown(1)
Lakshmanan Sethu(1)
Veena Sarda(1)
Abhishek Jain(1)
Syed Shanu(1)
Vinod Kumar(1)
Anubhav Chaudhary(1)
Jay Tallamraju(1)
Arun Choudhary(1)
Dipal Choksi(1)
Deepak Verma(1)
Shalini Juneja(1)
Nipun Tomar(1)
Abhimanyu K Vatsa(1)
Sanket Terdal(1)
rottensystem (1)
Matthew Cochran(1)
Malcolm Crowe(1)
Vivek Gupta(1)
Aradhana Tripathi(1)
Praveen Moosad(1)
Pradeep Sahoo(1)
Suraj Sahoo(1)
Santhakumar Munuswamy(1)
Ankur Mistry(1)
Sumit Deshmukh(1)
Destin joy(1)
Prerana Tiwari(1)
Abhijit Patil(1)
Veda Bs(1)
Abhishek Jaiswal :)(1)
Deepak Sharma(1)
Amit Choudhary(1)
Manikavelu Velayutham(1)
Resources
No resource found
Working With R Programming Using Microsoft R Open And R Tools For Visual Studio
Apr 23, 2017.
This article illustrates working with R Programming, using Microsoft R Open and R Tools for Visual Studio.
Adding SharePoint Column To List Item Using Napa Tools And JSOM
Mar 01, 2017.
In this article, you will learn how to add SharePoint column to list Item, using Napa tools and JS..
Install Visual Studio Tools For Azure Logic Apps
Dec 25, 2016.
In this article, we will learn how to install Visual Tools for Azure Logic Apps.
Python Tools For Visual Studio Installation
Dec 08, 2016.
This article explains how to install Python Tools in our Visual Studio application.
Learning Path For Visual Studio Tools For Office (VSTO) Programming
Nov 06, 2016.
A simple but productive way of learning Visual Studio Tools for Office (VSTO) programming.
Command Line Interface (CLI) Tools In .NET Core
Oct 10, 2016.
In this article, you will learn about Command Line Interface (CLI) Tools in .NET Core.
Setting Up Visual Studio Enterprise 2015 With UWP Tools And Azure SDK Virtual Machine In Azure Portal
Sep 12, 2016.
In this article, you will learn, how to set up Visual Studio Enterprise 2015 with UWP Tools and Azure SDK Virtual Machine, using Azure portal.
SharePoint Developer Tools - Get Your Gears
Aug 22, 2016.
This article will talk about the "Must Have" developer tools which every SharePoint Developer must have in his or her Arsenal in order to boost productivity while developing solutions on the SharePoint platform.
Useful Tools For AngularJS Developers
Aug 21, 2016.
In this article, we will see different Angular JS tools to help to achieve the productivity and pace the workflow fast.
Must Have Visual Studio Extensions or Tools - Part Two
Aug 01, 2016.
You must Have Visual Studio Extensions or Tools, which improves your development productivity.
Useful Tools For .NET Developers
Jul 18, 2016.
In this article, we will review some of the best productivity tools for .NET developers.
Six Best Tools Every Android Developer Must Know
May 11, 2016.
In this article you will learn about some of the best tools every Android Developer must know.
New Tools To Build Desktop Applications in Visual Studio 2016
Apr 21, 2016.
In this Channel 9 video, Microsoft’s Unni demonstrates new tools in Visual Studio “15” and developing, debugging, packaging apps.
Runtime Editing Tools for XAML In Visual Studio 2015
Apr 02, 2016.
There are new runtime tools for XAML In Visual Studio 2015 Update 2 and Visual Studio "15" Preview.
Useful Tools For SharePoint Practitioners
Mar 10, 2016.
In this article you will learn about some useful tools for SharePoint Practitioners.
Debugging Tools in Visual Studio
Mar 03, 2016.
In this article you will learn about debugging tools in Visual Studio.
Administrative Tools In Windows 10
Feb 19, 2016.
In this article you will learn how to identify Administrative Tools in Windows 10.
R Tools For Visual Studio Sneak Peek
Jan 29, 2016.
In this article you will learn R Tools For Visual Studio are on the way. Here is a sneak peek.
Handy Development Tools For Assisting Others From Your Browser
Oct 28, 2015.
In this article you will learn Handy Development Tools for Assisting others from your Browser.
GUI Tools For MongoDB
Sep 23, 2015.
In this article you will learn about GUI Tools in MongoDB. there are several third party tools that provide a GUI interface for MongoDB. Some important GUI tools are discussed here.
Comparison Of Unit Testing Tools In .NET
Sep 17, 2015.
In this article I am comparing Unit Testing Tools in .NET.
Best Ever Performance And Debugging Tools In Visual Studio 2015
Sep 11, 2015.
In this article we will learn the best ever performance and debugging tools in Visual Studio 2015.
Access Windows Accessories Tools in Windows 10
Aug 10, 2015.
In this article, we will see how to access Windows Accessories Tools in Windows 10.
Properties of Napa Office 365 Development Tools in SharePoint 2013 & Office 365
Aug 08, 2015.
In this article you will learn the properties of Napa Office 365 Development Tools in SharePoint 2013 and Office 365.
"Napa" Office 365 Development Tools in SharePoint 2013 & Office 365 - Part 3
Aug 01, 2015.
In this article you will learn "Napa" Office 365 Development Tools in SharePoint 2013 & Office 365. This is Part 3 of the article series.
"Napa" Office 365 Development Tools in SharePoint 2013 & Office 365 - Part 4
Aug 01, 2015.
In this article you will learn about "Napa" Office 365 Development Tools in SharePoint 2013 & Office 365.
"Napa" Office 365 Development Tools in SharePoint 2013 & Office 365
Jul 31, 2015.
In this article you will learn about "Napa" Office 365 Development Tools in SharePoint 2013 & Office 365.
"Napa" Office 365 Development Tools in SharePoint 2013 & Office 365 - Part 1
Jul 31, 2015.
In this article you will learn about Napa Office 365 Development Tools in SharePoint 2013 & Office 365.
"Napa" Office 365 Development Tools in SharePoint 2013 & Office 365 - Part 2
Jul 31, 2015.
In this article you will learn Napa - Office 365 Development Tools in SharePoint 2013 & Office 365.
Visual Studio Tools For Bootstrap
Jul 17, 2015.
This article focuses on the Tools available in Visual Studio to develop Web Applications using Bootstrap.
New XAML Tools in Visual Studio 2015 and Blend
Jul 13, 2015.
Watch this video by Robert Green and Seth Juarez talk and demonstrate new XAML Tools in Visual Studio 2015.
Use Free Spire.Doc to Satisfy All Word Header and Footer Tools in C#
Jul 07, 2015.
In this article you will learn how to Spire.Doc to satisfy all Word Header and Footer tools in C#.
Google Input Tools For Indian Language
Jun 01, 2015.
In this article you will learn about Google Input Tools for Indian Language.
Modern Tools For Front-End Developers
Feb 02, 2015.
In this article you will learn about the tools that a modern Front-End Developer should consider,
Build Tools in Android Studio 1.0
Jan 27, 2015.
This article explains some basic build tools embedded in the Android Studio 1.0.
Must Have Visual Studio Extensions or Tools - Part One
Jan 20, 2015.
In this article you will learn Visual Studio extensions or tools that supports development activities.
List of Important Tools in Android Studio 1.0
Jan 14, 2015.
This article provides an introduction to some enhanced tools and updates to the new Android Studio 1.0.
Getting Start With Node.JS Tools For Visual Studio
Nov 29, 2014.
In this article you will get the great thing, Node.JS tools for Visual Studio. It provides all flavors of Visual Studio to develop Node.JS applications. This tool has many great features, it provides great Node.JS templates.
Top 5 Data Visualization Tools You Will be Happy to Use
Nov 04, 2014.
In this article you will learn how to use Data Visualization Tools.
15 Free Web Design Tools to Design & Manage Websites
Oct 14, 2014.
In this article you will learn about 15 Free Web Design Tools to Design & Manage Websites.
Napa Office 365 Development Tools Installation
Feb 27, 2014.
This article shows how to install the "Napa" Office 365 Development Tools.
Start the New Taste of Visual Studio 2012 With Web Tools 2013.1
Nov 22, 2013.
In this article I am describing the new ASP.NET Web Tools 2013.1 that has been revealed by Microsoft for Visual Studio 2012 and the new changes made in this update.
SharePoint Backup and Recovery Tools and Best Practices
Oct 05, 2013.
Backup and restore operations can consume server resources and limit server performance while these operations are running. There is a need to select the right tools and follow best practices for performing these operations.
Web Tools Enhancement in Visual Studio 2013 RC
Oct 01, 2013.
This article describes various enhancements to the previous features and new features in the Visual Studio 2013 RC.
Continous Integration Tools Comparison
Aug 15, 2013.
This article only covers the comparison of some of the renowned tools used for continuous integration.
Atlas Copco PowerFocus (3000/4000) Nutrunner Tools Ethernet Communication Using C#.Net
Jul 03, 2013.
The main purpose of this article is the result of when I started the Nutrunner tool communication program it was like a blank page.
Pie Chart By Google Chart Tools in PHP
Apr 26, 2013.
In this article I show how to create a Pie Chart using Google Chart Tools in PHP.
Customize the Tools Menu of Server Menager by Adding Shortcuts in Administrative Tool
Apr 19, 2013.
In this you will learn how to customize the Tools Menu of the Server Menager by adding shortcuts in the Administrative Tools.
Crop and Slice Tools in Photoshop
Mar 29, 2013.
This article describes the Crop and Slice tools.
Drawing and Type Tools in Photoshop
Mar 29, 2013.
In this article you will learn about Drawing and type tools in Photoshop..
Using HTML5 Tools to Design a Simple Form
Jan 07, 2012.
This article helps to show how to design a simple payment form using HTML 5 tools.
SharePoint Developer Tools in Visual Studio 11
Sep 21, 2011.
This article takes an introductory look at the new facilities announced for SharePoint development in the upcoming version of Visual Studio.
Windows Azure - Create an Azure Service Package Using Windows Azure Tools V1.4 For VS 2010
Aug 09, 2011.
In this article we are going to see how to create an Azure Application package using the Visual Studio 2010 Azure tool from the latest (August 2011) release.
New Windows Azure Tools V1.4 For Visual Studio 2010
Aug 04, 2011.
Microsoft has just released the new Windows Azure Tools V1.4 for Visual Studio 2010 with highly enhanced new features which are very useful from the developer perspective.
Installing Android SDK Tools in Windows XP
Jul 28, 2011.
Here, you can learn the steps involved in Android SDK installation and how to start the Android Emulator in Windows XP.
Essential Concepts And Tools For Learning F#
Jul 01, 2011.
This article contains basic concepts and tools essential for learning F#. If you want to learn F#, do so with this.
Computer Aided Software Engineering Tools (CASE)
Apr 26, 2011.
CASE stands for Computer Aided Software Engineering which is software that supports the software development process
Introduction to Brushes tools in XAML Silverlight
Apr 19, 2011.
In this article, you will find an introduction to Brushes tools used in XAML Silverlight.
Using Tools and Windows in Expression Blend 2.0
Sep 14, 2010.
This article is a basic introduction of Expression Blend 2 and how to use various tools in Expression Blend. I am using Expression Blend version 2.0.
Visual Studio 2010 Tools - To improve code quality
Jun 21, 2010.
In this article, I am going to present a step by step demo on how to improve code quality by using Visual Studio Tools.
.NET Framework Security Tools
Mar 19, 2010.
In this article I will explain you about the .NET Framework Security Tools.
Developing external tools add-in with ProcessStartInfo and Process classes for PragmaSQL Editor
Aug 28, 2008.
This article describes making of an external tools add-in for PragmaSQL Editor by using ProcessStartInfo and Process classes from System.Diagnostics namespace.
Running the command prompt from visual studio tools menu
Jan 17, 2008.
This article tells you how to run visual studio command prompt from inside the visual studio.
Compiler Tools in C#
Sep 10, 2002.
The attached zip file contains the source code and documentation of Compiler tools in C#.
VS.NET Tools Intermediate Language Disassembler (ILDAM)
Feb 06, 2002.
"The ILDSAM tool parses any .NET Framework EXE/DLL Module and shows the information in a human-readeble format"
Top Creative Tips-Tools to Attract And Recruit The Best Talent
May 19, 2017.
This article includes 10 creative tips, tools & methodologies to attract & recruit the best talent.
Working With SharePoint Document Library Using Napa Office 365 Development Tools
Mar 08, 2017.
In this article, you will learn how to work with SharePoint Document Library using Napa Office 365 Development Tools..
Top Website Performance Testing Tools
Jul 25, 2016.
In this article, you will learn about top website performance testing tools.
Top 5 Website Speed Test Tools
Jul 18, 2016.
In this article you will learn about the top 5 website speed test tools.
Top 3 Free Responsive Web Design Testing Tools
Jun 29, 2016.
In this article, we will see top 3 website testing tools and how to use them.
Tools That Make .NET Development Easy
May 29, 2016.
In this article you will learn how to use tools that make .NET development work easier for developers.
Tools That Make Web Developers' Lives Easy
Apr 28, 2016.
In this article you will learn about tools that make developers' lives easy.
.NET Decompiling Tools: Part 1
Jan 31, 2016.
This article explains about decompiling tools for the .NET application and their features, how to use the tools to decompile assembly and assembly browser.
Visual Studio Team Services - Agile - Scrum Project Management Tools
Dec 31, 2015.
This article is an overview of Visual Studio Team Services and Agile - Scrum Project Management Tools.
Tools For Debugging In Visual Studio 2015 - Part 2
Sep 21, 2015.
In this article you will learn about the new tools for debugging in Visual Studio 2015.
Tools For Debugging In Visual Studio 2015 - Part 1
Sep 20, 2015.
In this article you will learn about the tools for debugging in Visual Studio 2015.
SharePoint App Using Napa Development Office 365 Tools
Sep 11, 2015.
In this article we will learn how to create a SharePoint app using napa development tool.
Tools and Capabilities For Monitoring in SharePoint 2013
Oct 03, 2014.
We can learn some of the Tools and Capabilities for Monitoring in SharePoint 2013
Tools of Business Intelligence in QlikView
May 30, 2014.
This article provides an introduction to business intelligence and also describes various tools of business intelligence.
Tools in SQL Server Management Studio
Mar 04, 2014.
This article shows how to use Tools in SQL Server Management Studio.
How to Create an App For SharePoint Using Office 365 Tools
Feb 18, 2014.
In this article you can learn how to create an app for SharePoint using the “Napa” Office 365 Development tools.
Understanding SQL Server Data Tools
Jan 09, 2014.
This article talks about some of the challenges that developers encouter during database design and implementation.
Creating Charts in ASP.NET Using Google Chart Tools
Apr 19, 2013.
In this article I explain how to create charts in ASP.NET using Google Chart Tools.
Create Rotating Buttons Using CSS3 and HTML 5 Tools
Jan 28, 2012.
This is a simple application for beginners that shows how to rotate a button using HTML 5 and CSS 3 tools.
Design Hexagon Using The HTML5 Tools
Jan 12, 2012.
This is a simple application developed in HTML 5 that shows how to draw a hexagon..
Building a Moving Image Using HTML5 Tools
Jan 04, 2012.
This simple application developed in HTML 5 helps to show how to move an image in a browser. We know that HTML stands for Hyper Text Markup Language and it helps to display the data in a browser..
Create Flexible Box Model Using HTML5 Tools
Jan 02, 2012.
This is a simple application developed in HTML 5 that help to how to create the Quick hits with the Flexible Box Model application. We have know that the HTML 5 is the advance version of the HTML..
Improve your productivity with VisualStudio 2010- Productivity Power Tools
Sep 22, 2011.
Are you a smart visual studio 2010 developer? If you want to be then this post is for you. This post is for Visual Studio 2010 users to get productive while working.
Performance Engineering Tools
Apr 20, 2011.
In this article let’s discuss various tools that help to analyze performance issues in web applications.
About Tools
NA
File APIs for .NET
Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more! | http://www.c-sharpcorner.com/tags/Tools | CC-MAIN-2017-22 | refinedweb | 2,909 | 66.64 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How set STATE=DONE? (Action & Button)
How do I go about creating a button that sets the state of purchase order to done?
I have in my purchase.py file
def action_done(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'done'}, context=context) return True
I then added the line action_done in xml. When I click the button, it says no attribute for purchase order. I've already updated the modules, and also rebooted the server. The action is defined in the purchase.py file
This issue has been resolved.
It was notified as a bug :
Let me try this out. In XML view I defined it as "function" and when I call it, it says purchase.order has no such attribute. I'll try it as "workflow" to see if it works
EDIT: Somehow after moving it to a different line in purchase.py the button now works. This is the code I used:
in purchase.py
def action_done(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'done'}, context=context) return True
in form view xml
<button name="action_done" type="object" string="Done" />
Thanks a bunch!
can you please share this solution file i need it also. as in my problem that the purchase order always remain in purchase order state not getting done automatically even invoice paid, and the good in warehouse received
Hi, you need to modify your own .py file and in debug mode, add the extra line into the xml. If you can't get it done, drop another message here or leave your email I can send you screenshot on how to get it done. Many bugs are fixed in v8 but now I noticed that if you purchase and pay for an item that is $0, it will not complete the purchase order as well.
my problem is when the purchase order scheduler then it will be in not done state. because i make the sales order it will generate purchase order. when payment done and warehouse goods received still the purchase order in purchase order state. that's let me confuse which order are not done, which is done.
my problem come if the purhcase order from warehouse scheduler, even payment done, goods received in warehouse purhcase order remain "purchase order state". i find solution over google non of them give satisfied answer. even in launchpad no solution or update. i'm no knowledge in programing. but i added your command above in purhcase.py via gedit and add the button line in xml file still no done button appear. maybe because i put in wrong line. since i don't know any in programing. my mail: blackneck6666 at gmail dot com
Cheers and luck
The button is clickable and an action is set, but the purchase order status is still showing as "purchase order" instead of done. I'd post a picture but I don't have enough karma. Any help on this?
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
you most have in the xml view, for example, in the form view a button <button name="action_done" type="workflow" string="Done" /> | https://www.odoo.com/forum/help-1/question/how-set-state-done-action-button-42621 | CC-MAIN-2018-05 | refinedweb | 577 | 75 |
Member since 09-15-2015
457
507
Kudos Received
90
Solutions
I just installed a new cluster on HDP 2.3.4 with Solr 5.2.1 including Kerberos + Ranger Solr Plugin. Following this article However when I enable the Ranger Solr Plugin and restart solr I am seeing the following error: 632300 [Thread-15] WARN org.apache.ranger.plugin.util.PolicyRefresher [ ] – cache file does not exist or not readble 'null' 662301 [Thread-15] ERROR org.apache.ranger.plugin.util.PolicyRefresher [ ] – PolicyRefresher(serviceName=null): failed to refresh policies. Will continue to use last known version of policies (-1) com.sun.jersey.api.client.ClientHandlerException: java.lang.IllegalArgumentException: URI is not absolute at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151) at com.sun.jersey.api.client.Client.handle(Client.java:648) at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680) at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74) at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507) at org.apache.ranger.admin.client.RangerAdminRESTClient.getServicePoliciesIfUpdated(RangerAdminRESTClient.java:73) at org.apache.ranger.plugin.util.PolicyRefresher.loadPolicyfromPolicyAdmin(PolicyRefresher.java:205) at org.apache.ranger.plugin.util.PolicyRefresher.loadPolicy(PolicyRefresher.java:175) at org.apache.ranger.plugin.util.PolicyRefresher.run(PolicyRefresher.java:154) Caused by: java.lang.IllegalArgumentException: URI is not absolute at java.net.URI.toURL(URI.java:1088) at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:159) at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149) ... 8 more This is what it looks like on HDP 2.3.2 INFO - 2016-03-15 16:54:50.478; [ ] org.apache.ranger.plugin.util.PolicyRefresher; PolicyRefresher(serviceName=mycluster_solr): found updated version. lastKnownVersion=-1; newVersion=61 On 2.3.4 the serviceName is not replaced by the actual repository name, which was set in the install.properties file. On 2.3.2 the serviceName is replaced by the repository name <clustername>_solr. Looks like a bug :( Anyone seen this issue before? Any possible workaround? ... View more
What are the values of the following configurations? hbase.rootdir hbase.cluster.distributed Metrics service operation mode hbase.zookeeper.property.clientPort hbase.zookeeper.quorum If you are using the Zookeeper Quorum that was installed during the HDP installation, make sure hbase.zookeeper.quorum contains the quorum of your cluster (see e.g. yarn.resourcemanager.zk-address) and hbase.zookeeper.property.clientPort is set to 2181. ... View more
is your cluster kerberized? are you using the Zookeeper service that is provided by AMS or the one of your hadoop cluster? ... View more
Can you create policies for this repository through the Ranger UI? What HDP and Ranger version is this? I just tried you command in my sandbox and it worked (only changed the repository name and ranger host)"] }] }' Response: HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/json Transfer-Encoding: chunked Date: Thu, 17 Mar 2016 07:07:35 GMT ... View more
Headless keytabs dont have a hostname. Try klist -k /etc/security/keytabs/hdfs.headless.keytab This will show you what principals are available in this keytab file. I think for the sandbox the principal is [email protected] Copy the principal name and do kinit -kt /etc/security/keytabs/hdfs.headless.keytab <principal name including realm> Afterwards do klist and see whether you have a new ticket. Also check the Namenode log and make sure there are no GSS exceptions in there. What Sandbox, JDK and HDP version is this? ... View more
If you have enabled kerberos your connection string should look as follows: !connect jdbc:hive2://<hiveserver host>:<port>/default;principal=hive/_HOST@<REALM> ... View more
It looks like your user does not have the right permissions to access the Tez View. Thats what it looks like when I am logged in as the admin user Go To Manage Ambari (user dropdown menu) -> Views (left side navigation) -> Tez View -> Add your user "maria_dev" to the list of allowed users ("GRant permission to these users") ... View more
One way is to use Chef (OS + DBs + Partitions + ...) in combination with Ambari Blueprints (Cluster + Kerberos/Security). There are already some sample cookbooks out there that you can use as a starting point, e.g. or ... View more
This might help, take a look at the post from @Lester Martin ... View more
It looks like you are not running the installation as administrator, make sure you use a user that has enough privileges to install the HDP package ... View more
Put the Solr instances on the slave/Datanodes. In regards to configuration, see this although its focused on securing Solr with Kerberos and Ranger, there is also a small section about the installation. ... View more
Usually when you want to use curl in combination with Kerberos (secured cluster), you have to use the following command: curl --negotiate -u : -X GET '' Make sure you have a valid kerberos ticket (run: klist) ... View more
Can you do a "hdfs dfs -count <path>" on both directories.Just to see if they both have the same amount of files and folders or if one of them has more files and therefore is larger in regards to the size ... View more
What Ambari version are you using, is it the latest one (2.2.1.0)? You might have to upgrade to the latest version, so that you have the latest stack information ... View more
Make sure Hive Service and all its components are running, you can check via Ambari In addition, you might want to download the latest sandbox from with HDP 2.4 ... View more
Is this the correct JAVA_HOME path => /usr/java/default/bin/java? Check /etc/ambari-server/conf/ambari.properties and make sure the configured java paths are correct, You can also check the health of your HDFS by running hdfs fsck / ... View more
Yes absolutely, Nifi is a great option, take a look at this example (even though its not RDBMS) ... View more
You can retrieve individual configurations as follows. I guess you are only interested in the latest configurations 1.Get a list of current configurations curl -H "X-Requested-By:ambari" -u admin -X GET Result: .... "provisioning_state" : "INSTALLED", "security_type" : "NONE", "total_hosts" : 6, "version" : "HDP-2.3", "desired_configs" : { "admin-properties" : { "tag" : "version1454834038932", "user" : "admin", "version" : 1 }, "capacity-scheduler" : { "tag" : "version1455710459816", "user" : "admin", "version" : 3 }, "cluster-env" : { "tag" : "version1455710460245", "user" : "admin", "version" : 3 }, "core-site" : { "tag" : "version1455710465648", "user" : "admin", "version" : 6 }, .... Note: The "tag"-field is the most important information here. 2) Retrieve individual configurations (e.g. cluster-env) curl -H "X-Requested-By:ambari" -u admin -X GET Result: { "href" : "", "items" : [ { ....... "properties" : { "ignore_groupsusers_create" : "false", "kerberos_domain" : "EXAMPLE.COM", "override_uid" : "true", "repo_suse_rhel_template" : "[{{repo_id}}]\nname={{repo_id}}\n{% if mirror_list %}mirrorlist={{mirror_list}}{% else %}baseurl={{base_url}}{% endif %}\n\npath=/\nenabled=1\ngpgcheck=0", "repo_ubuntu_template" : "{{package_type}} {{base_url}} {{components}}", "security_enabled" : "false", "smokeuser" : "ambari-qa", "smokeuser_keytab" : "/etc/security/keytabs/smokeuser.headless.keytab", "smokeuser_principal_name" : "[email protected]", "user_group" : "hadoop" } } ] } Hope it helps ... View more
Hi @prakash pal there are some differences between these data types, basically string allows a variable length of characters (max 32K chars), char is a fixed length string (max. 255 chars). Usually (I doubt that this is different with Impala) CHAR is more efficient and can speed up operations and is better reg. memory allocation. (This does not mean always use CHAR) See this => "All data in CHAR and VARCHAR columns must be in a character encoding that is compatible with UTF-8. If you have binary data from another database system (that is, a BLOB type), use a STRING column to hold it." There are a lot of use cases where it makes sense to only use CHAR instead of STRING, e.g. lets say you want to have a column that stores the two-letter country code (ISO_3166-1_alpha-2; e.g. US, ES, UK,...), here it makes more sense to use CHAR. ... View more
This might be a Parquet problem, but could also be something else. I have seen some performance and job issues when using Parquet instead of ORC. Have you seen this What features are you missing regarding SparkORC? I have seen you error before, but in a different context (Query on ORC table was failing) Make sure your HDFS (especially the DNs) are running and healthy. It might be related to some bad blocks, so make sure the blocks that are related to your job are ok ... View more
02-25-2016 05:55 AM
02-25-2016 05:55 AM
Can you log into the machine (ssh [email protected] -p 2222) and check the status of the ambari server and agent? ambari-server status ambari-agent status Make sure both services are running and also check if the ambari database is up and running service postgresql status The issue you are facing could mean: A: Ambari DB is not running B: Ambari Server is not running and you are looking at a cached Ambari UI (try a hard page reload or emptying the browser cache) ...
Make sure your HDFS is running and not in safemode. You can check via Ambari (localhost:8080). Is this the latest sandbox you're using? What HDP and Hue version is this? ... View more
Take a look at this questions, maybe it is helpful => ... View more
HDP search does only include Solr, but I have used Nutch -> Solr -> HDP/HDFS before and it worked. @Sebastian Droeppelmann what dependency issues did you run into? ... View more
You can specify the number of mappers that will be used for the distcp job. -m <num_maps> Maximum number of simultaneous copies Specify the number of maps to copy data. Note that more maps may not necessarily improve throughput. If nothing is specified, the default should be 20 map tasks. /* Default number of maps to use for DistCp */ public static final int DEFAULT_MAPS = 20; ... View more
This sounds like the issue mentioned here, however I dont know a valid workaround for our Hue version at the moment. I strongly encourage you to use different ways to ingest large amounts of data into your cluster, e.g. separate data ingestion node (+hdfs cmds to move files into hdfs), Nifi, distcp,... ... View more
please see my comment above. In secure mode you need local user accounts on all Nodemanager nodes ... View more | https://community.cloudera.com/t5/user/v2/viewprofilepage/user-id/35914/page/3 | CC-MAIN-2020-05 | refinedweb | 1,721 | 50.23 |
[
]
Jitendra Nath Pandey commented on HDFS-1580:
--------------------------------------------
- The design doesn't go in any detail regarding snapshots concurring to your view. However,
I mentioned about it because it is one of the requirements we will have to address eventually.
- This jira doesn't change any semantics related to the layout version. The version is a piece
of metadata that needs to be stored with edit logs so that namenode can understand and load
edit logs. I am open to making it a byte array instead of just an integer so that namenode
can store any metadata it wants to store, which is relevant for understanding the edit logs.
I agree that version is a little overloaded but that can be addressed in a different jira.
- I think retention policy for edit logs should be namenode's responsibility, because retention
of edit logs will be closely tied with retention of old checkpoint images. If namenode has
called purgeTransactions it should never ask for older transaction ids.
- "mark" means that the last written transaction is available for reading including all previous
transactions. sinceTxnId in getInputStream can be any transaction Id before the last call
of mark or close of the output stream. Apart from that, sinceTxnId doesn't assume any boundary.
- The motivation for "mark" method was that BK has this limitation that open ledgers cannot
be read, "mark" will give a cue to a BK implementation that the current ledger should be made
available for reading. If an implementation doesn't have this limitation it can just ignore
mark, that is why I didn't call it roll. That also explains that it is different from sync.
- I assumed that a write also syncs, because in most operations we sync immediately after
writing the log, and in this design we are writing the entire transaction as a unit. Management
of buffers and flush, should be the responsibility of the implementation.
- In EditLogInputStream, I think we can rename next to readNext, it will look less like iterator.
One way to avoid extra array copy would be that readNext() reads the version and txnId and
synchronizes the underlying inputstream to the begining of transaction record and then getTxn
can directly return the underlying inputstream for reading the transaction bytes. Does that
make sense?
LogSegements:
LogSegments gets rid of roll method but exposes the underlying units of storage to the namenode
which I don't think is required.
>.. elsewhere we have discussed that we want to keep the property that logs always roll
together across all parts of the system.
Do we really want this property? Isn't it better that we don't expose any boundaries between
transactions to the namenode?
> We generally want the property that, while saving a namespace or in safe mode, we don't
accept edits.
This can be achieved by just closing the EditLogOutputStream.
>: | http://mail-archives.apache.org/mod_mbox/hadoop-hdfs-issues/201104.mbox/%3C1085137408.10167.1304029923876.JavaMail.tomcat@hel.zones.apache.org%3E | CC-MAIN-2016-07 | refinedweb | 476 | 61.06 |
You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.
1. Create Extension in yii2.
As for this step, you can refer to Create Extension
In short, you can use gii to create extension after read above article. Just be care to change the output as
@app/vendor/yourname
change the namespace as
yourname\yourwidgetname\
2. Install github in you computer.
I use window. So you can google/baidu to search msysgit. It is a window version github. You should be able right click folder and find "Git Bash", "Git Gui", "Git Init Here" and so on menu after you success install msysgit.
3. Link your widget to github
You can link your github account now. ~~~ $ git config --global user.name "Your Name" $ git config --global user.email "[email protected]" ~~~ And then add files. ~~~ git add git add git status git commit -m "your comment" ~~~
Remote github. ~~~ $ ssh-keygen -t rsa -C "[email protected]" ~~~ You will find .ssh dir in you home dir, and find id_rsa和id_rsa.pub You can tell id-rsa.pub to everyone.
Login github with your browser ==> "Account Setting" ==> "SSH keys" ==> "Add SSH key", and paste your id-rsa.pub content in key, as for title, you can type any.
After that ~~~ $ git remote add origin [email protected]:youraccount/yourrepository.git $ git push -u origin master it will need input your github account and pass since use -u
In future, you only need below $ git push origin master ~~~
4. Register your github repository into packagist
Don't forget register your github repository into packagist, end user can install your widget only after you complete register. And packagist will give you hint for how to setup service in github to auto synchronize every commit from github to packagist.
Above is my experiences in past 2 days which I success fully create yii2-google-chart extension.
packagist yii2-google-chart
awesome tutorial
it's nice tutorial
sweet..!!!
If you have any questions, please ask in the forum instead. | https://www.yiiframework.com/wiki/809/how-to-create-yii2-extension-and-push-to-github-and-register-into-packagist-to-allow-end-user-install-from-composer?revision=1 | CC-MAIN-2021-49 | refinedweb | 354 | 68.87 |
In-Depth
Every Silverlight developer needs to know these differences between Silverlight and the Windows Runtime before starting on a WinRT app..
1. Fundamental Differences
It's important that you first understand the fundamental differences between Silverlight and WinRT apps. Take a look at Table 1 for a quick comparison of each platform's technology.
Windows 8 is more flexible in terms of environments, allowing not only XAML but HTML. This opens the platform up to Web developers as well as Silverlight and XAML developers.
WinRT apps are built primarily for touch input, whereas with Silverlight, a mouse and keyboard are the primary input devices. As I move between each item in this list, keep these differences in mind.
Table 1. A comparison between Silverlight and WinRT apps.
2. Application Lifecycle
The application lifecycle of Silverlight applications versus WinRT apps is very different. The Silverlight application lifecycle is shown in Figure 1.
In Silverlight, the user typically types a URL into a browser, and the <object > tag located in the HTML page loads the plug-in. The plug-in then downloads the XAP file (which contains the application code) and creates an instance of the Application class, then fires the start-up event. Finally, the Silverlight application is rendered inside the browser. The application will continue to run until the browser is closed.
In a WinRT app, this process is managed completely by Windows 8, instead of the user, as shown in Figure 2. When the user launches a WinRT app, it's quickly up and running. This app can be suspended when the user switches away from it, or when Windows enters a low-power state.
The app has 5 seconds to handle suspension. During this time, it's best to use Isolated Storage to persist settings that may benefit the user upon resuming; if the user switches back to the app, it's resumed.
Finally, if Windows has detected low memory, it might terminate the application while in suspended status. The user also has the ability to terminate a WinRT app at any time, but Windows 8 will primarily be managing this.
3. XML and Code Namespaces
XML and code namespaces have changed from Silverlight to the Windows Runtime. Let's look at an example of each.
Starting with XML namespaces, look at the following highlighted text for Silverlight:
<UserControl x:Class="DiggSample.Page"
xmlns=""
xmlns:x=""
xmlns:
</UserControl >
And for the Windows Runtime:
<UserControl x:Class="DiggSample.MainPage"
xmlns=""
xmlns:x=""
xmlns:
</UserControl >
You should use the using statement in your WinRT apps instead of clr-namespace, and you should never declare the assembly, as was done in Silverlight applications.
Taking a look at code namespaces, you'll quickly find that a majority of the changes occur in the UI-related classes. For example, in Silverlight applications you would typically find the following using statements:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
In WinRT apps, they'll look like the following:;
A great way to see a Silverlight 5 versus Windows Runtime comparison by namespace can be found at Tim Greenfield's Web site. He documents the differences in an easy-to-read manner.
4. WebRequest
Almost every application built today requires some sort of Web request. It might be pulling down an RSS feed to the daily news or weather, for example; whatever it is, applications need to connect to the Web, and this is no different with WinRT apps. Before you can begin to write WinRT apps, you must be aware of a few things:
Before looking at a code sample, I want discuss asynchronous programming. The Windows Runtime introduces a special keyword, async, which, when used correctly, avoids the bottleneck of your application being executed line-by-line. The async keyword enables the await keyword in that method. The await operator is applied to a task to suspend execution of the method until the task is complete. The Tasks <T> simply represents an asynchronous operation that can return a value.
Let's take a look at a sample of each, in Listing 1 and Listing 2. Again, notice the highlighted text.
In Listing 1 (the Silverlight example) I used the tried-and-true WebClient to make the call and return the XML response. In Listing 2 (the WinRT example) I marked the method as async and created a variable, client, that instantiated a new HttpClient that would later use the await keyword to asynchronously create our HttpResponseMessage.
I finished up by calling Task <T> to return the response as a string, which would be passed to the DisplayStories method. This method isn't shown, but it uses standard LINQ to parse the XML data.
This example demonstrates how using async, await and Task <T> made the application more responsive in case the request took a while to return. While these keywords may look strange at first, after building your first WinRT app they'll become second nature.
5. Storage: Files and Isolated Storage
Table 2 compares files and isolated storage for each platform.
Table 2. Silverlight versus WinRT app files and isolated storage.
I'll break these down into three groups: isolated storage, special folders (such as Documents and Pictures) and local files located anywhere on the hard disk drive (HDD).
For isolated storage, you'll quickly find that there are no differences between Silverlight and the Windows Runtime. A user can create, read, update or delete anything, as in Silverlight. The API for saving the files to isolated storage has changed slightly, but you still have free access to do anything in your sandboxed application.
For special folders, including Documents, Pictures and so on, you have the ability to prompt the user in a WinRT app by using a File or Folder Picker API, or write directly to these folders by specifying them in the Application Manifest.
For any other file or folder located on the local HDD, you have the ability in a WinRT app to write to it through the File and Folder Picker APIs. You can't write to a folder (such as C:\Temp\) in WinRT apps without first prompting the user. (In Silverlight 5, by contrast, you could use full trust to write to that folder without user intervention.)
6. Navigation: No More URI
In Silverlight applications, you typically use NavigationService.Navigate and pass it to a URI to navigate to a new page, like so:
this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
You can also implement more sophisticated application navigation by using the Frame and Page controls. Page controls represent discrete sections of content, while the Frame acts as a container for Page controls and facilitates navigation to pages.
The Frame control usually uses the UriMapper to navigate to a new page in XAML, rather than codebehind. Here's a sample of the Frame control as well as the UriMapper (both of these reside in the System.Windows.Navigation namespace):
>
WinRT apps still have the concepts of Frame and Page classes. The Frame is responsible for navigation and determining if you can navigate, go back or go forward to a page. You can create a new page by using one of the built-in templates and navigate to it by calling the following:
this.Frame.Navigate(typeof(NewPage));
Of course, this is generally more helpful if you can pass data to the page to which you're navigating. For example, if you had a TextBox named tb1 and wanted to pass the contents of it to another page, you could use the following code:
this.Frame.Navigate(typeof(NewPage), tb1.Text);
When the new page loads, you can retrieve the contents of the tb1.Text in the OnNavigatedTo event.
7. Controls
Silverlight controls such as Calendar, ChildWindow, DataGrid, DataPager, DescriptionViewer, MultiScaleImage, OpenFileDialog, RichTextBox, SaveFileDialog, TabControl, TabItem, TreeView, Validation and WebBrowser are no longer present in the Windows Runtime. Instead, Microsoft has replaced some of them with controls that interact with touch devices more easily. Here's a list of the most important ones:
Many of these new controls can be found in Figure 3.
8. Animations
Animations are a key component of the new Windows UI. After logging into Windows 8 you'll see animated live tiles that display information such as new e-mails, the weather, trending news topics and so on. Opening an application launches an animation. When a user adds or removes an item inside an app, an animation might appear. In short, animations are everywhere in Windows 8, so it makes sense that Microsoft baked animations into the Windows Runtime.
Animation Easing in Silverlight allows you to apply built-in animation functions to your Silverlight controls. The result is a variety of animation effects that make your controls move in a more realistic way. The only issue with this is that few people are interested in Silverlight animations, as Windows XP and Windows 7 don't have the "fast and fluid" feel of Windows 8.
WinRT apps have a built-in animation library provided out of the box. It includes a variety of animations such as page and content transitions, as well as many others that you can see here.
Note that there are two types of WinRT animation:
You can also create custom animations if the supplied animations don't fit your needs. I haven't yet found a case for building my own animations.
9. Charms
Charms allow you to have everything at your finger tips without going through a whole lot of effort. With a swipe to the right-hand side of the screen you can bring up the Charms bar, which allows you to do things like create Search contracts to allow your application to integrate with the built-in Windows Search.
You can also make use of the Share contract to share content in your application with other apps. For instance, a user that has opened an RSS reader might want to share a link with her friends; this can be done easily with this built-in contract. Many other examples can be found at here. This functionality was missing completely from Silverlight applications, as they were sandboxed inside a Web browser -- you'd have to write code for similar functionality.
10. Monetization
One of the best features of Windows 8 is the built-in marketplace, which is designed for app discovery and reach. One problem that plagued Silverlight developers was an inability to find customers for their applications. The Windows Store already has 231 global markets (at the time of this writing) available to discover and purchase your app.
There's also a solution for customers wanting to deploy their WinRT app to their internal infrastructure, as well as a flexible business model (free, paid or trial) for those wanting public discovery of an application. The Microsoft Advertising SDK is also available if you want to give your app away and make money off of ad impressions.
There's a low barrier to entry, as the registration fee is $49 for individuals and $99 for companies. Microsoft shares up to 80 percent of the revenue generated from app sales, providing even more incentive for developers.
Only the Start
These 10 items are only the start. As you begin building your application, you'll likely find other differences between the Windows Runtime and Silverlight. The good news is that the Windows 8 community is thriving, and many folks are blogging and helping others understand this new platform. Microsoft has also provided excellent guidance about the way apps should look and feel, as well as plenty of sample source code. So what are you waiting for? Go ahead and begin building your first WinRT app!
About the Author
Michael Crump is a Microsoft MVP, INETA Community Champion, and an author of several .NET Framework books. He speaks at a variety of conferences, including CodeStock, DevLink and TechDays. Michael has also written dozens of articles on .NET Framework development for sites including CodeProject, SilverlightShow, DZone, Developer Fusion and CodeZone. You can follow Michael on twitter @mbcrump or keep up with his blog at michaelcrump.net.
Printable Format
> More TechLibrary
I agree to this site's Privacy Policy.
> More Webcasts | http://visualstudiomagazine.com/articles/2012/12/01/silverlight.aspx | CC-MAIN-2014-52 | refinedweb | 2,060 | 54.42 |
The k-Nearest Neighbors algorithm (or kNN for short) is an easy algorithm to understand and to implement, and a powerful tool to have at your disposal.
In this tutorial you will implement the k-Nearest Neighbors algorithm from scratch in Python (2.7)..
What is k-Nearest Neighbors
The model for kNN is the entire training dataset. When a prediction is required for a unseen data instance, the kNN algorithm will search through the training dataset for the k-most similar instances. The prediction attribute of the most similar instances is summarized and returned as the prediction for the unseen instance.
The similarity measure is dependent on the type of data. For real-valued data, the Euclidean distance can be used. Other other types of data such as categorical or binary data, Hamming distance can be used.
In the case of regression problems, the average of the predicted attribute may be returned. In the case of classification, the most prevalent class may be returned.
How does k-Nearest Neighbors Work
The kNN algorithm is belongs to the family of instance-based, competitive learning and lazy learning algorithms.
Instance-based algorithms are those algorithms that model the problem using data instances (or rows) in order to make predictive decisions. The kNN algorithm is an extreme form of instance-based methods because all training observations are retained as part of the model.
It is a competitive learning algorithm, because it internally uses competition between model elements (data instances) in order to make a predictive decision. The objective similarity measure between data instances causes each data instance to compete to “win” or be most similar to a given unseen data instance and contribute to a prediction.
Lazy learning refers to the fact that the algorithm does not build a model until the time that a prediction is required. It is lazy because it only does work at the last second. This has the benefit of only including data relevant to the unseen data, called a localized model. A disadvantage is that it can be computationally expensive to repeat the same or similar searches over larger training datasets.
Finally, kNN is powerful because it does not assume anything about the data, other than a distance measure can be calculated consistently between any two instances. As such, it is called non-parametric or non-linear as it does not assume a functional form.
Get your FREE Algorithms Mind Map
Sample of the handy machine learning algorithms mind map.
I've created a handy mind map of 60+ algorithms organized by type.
Download it, print it and use it.
Also get exclusive access to the machine learning algorithms email mini-course.
Classify Flowers Using Measurements
The test problem we will be using in this tutorial is iris classification.
The problem is comprised of 150 observations of iris flowers from three different species. There are 4 measurements of given flowers: sepal length, sepal width, petal length and petal width, all in the same unit of centimeters. The predicted attribute is the species, which is one of setosa, versicolor or virginica.
It is a standard dataset where the species is known for all instances. As such we can split the data into training and test datasets and use the results to evaluate our algorithm implementation. Good classification accuracy on this problem is above 90% correct, typically 96% or better.
You can download the dataset for free from iris.data, see the resources section for further details.
How to implement k-Nearest Neighbors in Python
This tutorial is broken down into the following steps:
- Handle Data: Open the dataset from CSV and split into test/train datasets.
- Similarity: Calculate the distance between two data instances.
- Neighbors: Locate k most similar data instances.
- Response: Generate a response from a set of data instances.
- Accuracy: Summarize the accuracy of predictions.
- Main: Tie it all together..
Next we need to split the data into a training dataset that kNN can use to make predictions and a test dataset that we can use to evaluate the accuracy of the model.
We first need to convert the flower measures that were loaded as strings into numbers that we can work with. Next we need to split the data set randomly into train and datasets. A ratio of 67/33 for train/test is a standard ratio used.
Pulling it all together, we can define a function called loadDataset that loads a CSV with the provided filename and splits it randomly into train and test datasets using the provided split ratio.
Download the iris flowers dataset CSV file to the local directory. We can test this function out with our iris dataset, as follows:
2. Similarity
In order to make predictions we need to calculate the similarity between any two given data instances. This is needed so that we can locate the k most similar data instances in the training dataset for a given member of the test dataset and in turn make a prediction.
Given that all four flower measurements are numeric and have the same units, we can directly use the Euclidean distance measure. This is defined as the square root of the sum of the squared differences between the two arrays of numbers (read that again a few times and let it sink in).
Additionally, we want to control which fields to include in the distance calculation. Specifically, we only want to include the first 4 attributes. One approach is to limit the euclidean distance to a fixed length, ignoring the final dimension.
Putting all of this together we can define the euclideanDistance function as follows:
We can test this function with some sample data, as follows:
3. Neighbors
Now that we have a similarity measure, we can use it collect the k most similar instances for a given unseen instance.
This is a straight forward process of calculating the distance for all instances and selecting a subset with the smallest distance values.
Below is the getNeighbors function that returns k most similar neighbors from the training set for a given test instance (using the already defined euclideanDistance function)
We can test out this function as follows:
4. Response
Once we have located the most similar neighbors for a test instance, the next task is to devise a predicted response based on those neighbors.
We can do this by allowing each neighbor to vote for their class attribute, and take the majority vote as the prediction.
Below provides a function for getting the majority voted response from a number of neighbors. It assumes the class is the last attribute for each neighbor.
We can test out this function with some test neighbors, as follows:
This approach returns one response in the case of a draw, but you could handle such cases in a specific way, such as returning no response or selecting an unbiased random response.
5. Accuracy
We have all of the pieces of the kNN algorithm in place. An important remaining concern is how to evaluate the accuracy of predictions.
An easy way to evaluate the accuracy of the model is to calculate a ratio of the total correct predictions out of all predictions made, called the classification accuracy.
Below is the getAccuracy function that sums the total correct predictions and returns the accuracy as a percentage of correct classifications.
We can test this function with a test dataset and predictions, as follows:
6. Main
We now have all the elements of the algorithm and we can tie them together with a main function.
Below is the complete example of implementing the kNN algorithm from scratch in Python.
Running the example, you will see the results of each prediction compared to the actual class value in the test set. At the end of the run, you will see the accuracy of the model. In this case, a little over 98%.
Ideas For Extensions
This section provides you with ideas for extensions that you could apply and investigate with the Python code you have implemented as part of this tutorial.
- Regression: You could adapt the implementation to work for regression problems (predicting a real-valued attribute). The summarization of the closest instances could involve taking the mean or the median of the predicted attribute.
- Normalization: When the units of measure differ between attributes, it is possible for attributes to dominate in their contribution to the distance measure. For these types of problems, you will want to rescale all data attributes into the range 0-1 (called normalization) before calculating similarity. Update the model to support data normalization.
- Alternative Distance Measure: There are many distance measures available, and you can even develop your own domain-specific distance measures if you like. Implement an alternative distance measure, such as Manhattan distance or the vector dot product.
There are many more extensions to this algorithm you might like to explore. Two additional ideas include support for distance-weighted contribution for the k-most similar instances to the prediction and more advanced data tree-based structures for searching for similar instances.
Resource To Learn More
This section will provide some resources that you can use to learn more about the k-Nearest Neighbors algorithm in terms of both theory of how and why it works and practical concerns for implementing it in code.
Problem
Code
This section links to open source implementations of kNN in popular machine learning libraries. Review these if you are considering implementing your own version of the method for operational use.
Books
You may have one or more books on applied machine learning. This section highlights the sections or chapters in common applied books on machine learning that refer to k-Nearest Neighbors.
- Applied Predictive Modeling, pages 159 and 350.
- Data Mining: Practical Machine Learning Tools and Techniques, Third Edition (The Morgan Kaufmann Series in Data Management Systems), pages 76, 128 and 235.
- Machine Learning for Hackers, Chapter 10.
- Machine Learning in Action, Chapter 2.
- Programming Collective Intelligence: Building Smart Web 2.0 Applications, Chapters 2 and 8 and page 293.
Tutorial Summary
In this tutorial you learned about the k-Nearest Neighbor algorithm, how it works and some metaphors that you can use to think about the algorithm and relate it to other algorithms. You implemented the kNN algorithm in Python from scratch in such a way that you understand every line of code and can adapt the implementation to explore extensions and to meet your own project needs.
Below are the 5 key learnings from this tutorial:
- k-Nearest Neighbor: A simple algorithm to understand and implement, and a powerful non-parametric method.
- Instanced-based method: Model the problem using data instances (observations).
- Competitive-learning: Learning and predictive decisions are made by internal competition between model elements.
- Lazy-learning: A model is not constructed until it is needed in order to make a prediction.
- Similarity Measure: Calculating objective distance measures between data instances is a key feature of the algorithm.
Did you implement kNN using this tutorial? How did you go? What did you learn?.
Jason –
I appreciate your step-by-step approach. Your explanation makes this material accessible for a wide audience.
Keep up the great contributions.
Thanks Damian!
A very interesting and clear article. I haven’t tried it out yet but will over the weekend.
Thanks.
Thanks Pete, let me know how you go.
Hey Jason, I’ve ploughed through multiple books and tutorials but your explanation helped me to finally understand what I was doing.
Looking forward to more of your tutorials.
Thanks Alan!
Hey Jason!
Thank you for awesome article!
Clear and straight forward explanation. I finaly understood the background under kNN.
p.s.
There’s some code errors in the article.
1) in getResponse it should be “return sortedVote[0]” instead sortedVotes[0][0]
2) in getAccuracy it should be “testSet[x][-1] IN predictions[x]” instead of IS.
Thanks Vadim!
I think the code is right, but perhaps I misunderstood your comments.
If you change getResponse to return sortedVote[0] you will get the class and the count. We don’t want this, we just want the class.
In getAccuracy, I am interested in an equality between the class strings (is), not a set operation (in).
Does that make sense?
Thank you very much for this example!
You’re welcome Mario.
Thank you for the post on kNN implementation..
Any pointers on normalization will be greatly appreciated ?
What if the set of features includes fields like name, age, DOB, ID ? What are good algorithms to normalize such features ?
Hey PVA, great question.
Notmalization is just the rescaling of numerical attributes between 0-1. Tools like scikit-learn can do it for you if you like, here’s a recipe:
You can compute distances between strings using methods like edit distance, learn more here:
DOB – well the distance between two dates could be in days, hours or whatever makes sense in your domain.
ID might just be useful as some kind of indirect marker of “when the entry was added to the database” if you don’t have a “record create time”.
I hope this helps.
A million thanks !
I’ve had so many starting points for my ML journey, but few have been this clear.
Merci !
Glad to here it Landry!
Hi,
when i run the code it shows
ValueError: could not convert string to float: ‘sepallength’
what should i do to run the program.
please help me out as soon as early….
thanks in advance…
Hi kumaran,
I believe the example code still works just fine. If I copy-paste the code from the tutorial into a new file called knn.py and download iris.data into the same directory, the example runs fine for me using Python 2.7.
Did you modify the example in some way perhaps?
Hi jabson ,
Thanks for your reply..
I am using Anaconda IDE 3.4 .
yes it works well for the iris dataset If i try to put some other dataset it shows value error because those datasets contains strings along with the integers..
example forestfire datasets.
X Y month day FFMC DMC DC ISI temp RH wind rain area
7 5 mar fri 86.2 26.2 94.3 5.1 8.2 51 6.7 0 0
7 4 oct tue 90.6 35.4 669.1 6.7 18 33 0.9 0 0
7 4 oct sat 90.6 43.7 686.9 6.7 14.6 33 1.3 0 0
8 6 mar fri 91.7 33.3 77.5 9 8.3 97 4 0.2 0
8 6 mar sun 89.3 51.3 102.2 9.6 11.4 99 1.8 0 0
Is it possible to classify these datasets also with your code??
please provide me if some other classifer code example in python…
HI KUMARAN
did you get the solution for the problem mentioned in your comment. I am also facing the same problem. Please help me or provide me the solution if you have..
Excellent article on knn. It made the concepts so clear.
Thanks sanksh!
I like how it is explained, simply and clear. Great job.
Thanks!
Great article Jason !! Crisp and Clear.
Nice artical Jason. I am a software engineer new to ML. Your step by step approach made learning easy and fun. Though Python was new to me, it became very easy since I could run small small snippet instead of try to understand the entire program in once.
Appreciate your hardwork. Keep it up.
Thanks Raju.
It’s really fantastic for me. I can’t find a better one
I also face the same problem with Kumaran. After checking, I think the problem “can’t convert string into float” is that the first row is “sepal_length” and so on. Python can’t convert it since it’s totally string. So just delete it or change the code a little.
Hi,
Many thanks for this details article. Any clue for the extension Ideas?
Thanks,
RK
Hi – I was wondering how we can have the data fed into the system without randomly shuffling as I am trying to make a prediction on the final line of data?
Do we remove:
if random.random() < split
and replace with something like:
if len(trainingSet)/len(dataset) < split
# if < 0.67 then append to the training set, otherwise append to test set
The reason I ask is that I know what data I want to predict and with this it seems that it could use the data I want to predict within the training set due to the random selection process.
I also have the same dilemma as you, I performed trial and error, right now I cant seem to make things right which code be omitted to create a prediction.
I am not a software engineer nor I have a background in computer science. I am pretty new to data science and ML as well, I just started learning Python and R but the experience is GREAT!
Thanks so much for this Jason!
This article was absolutely gorgeous. As a computational physicist grad student who has taken an interest in machine learning this was the perfect level to skim, get my hands dirty and have some fun.
Thank you so much for the article on this. I’m excited to see the rest of your site.
Thanks for the article!
I wished to write my own knn python program, and that was really helpful !
Thanks a lot for sharing this.
One thing you didn’t mention though is how you chose k=3.
To get a feeling of how sensitive is the accuracy % to k, i wrote a “screening” function that iterates over k on the training set using leave-one-out cross validation accuracy % as a ranking.
Would you have any other suggestions ?
This is really really helpful. Thanks man !!
An incredibly useful tutorial, Jason. Thank you for this.
Please could you show me how you would modify your code to work with a data set which comprises strings (i.e. text) and not numerical values?
I’m really keen to try this algorithm on text data but can’t seem to find a decent article on line.
Your help is much appreciated.
Mark
Nice tutorial! Very helpful in explaining KNN — python is so much easier to understand than the mathematical operations. One thing though — the way the range function works for Python is that the final element is not included.
In loadDataset() you have
for x in range(len(dataset)-1):
This should simply be:
for x in range(len(dataset)):
otherwise the last row of data is omitted!
this gets an index out of range..
Thank you so much
great
thank very much
That’s great! I’ve tried so many books and articles to start learning ML. Your article is the first clear one! Thank you a lot! Please, keep teaching us!)
Thanks Gleb!
Hi Jason,
Thanks for this amazing introduction! I have two questions that relate to my study on this.
First is, how is optimization implemented in this code?
Second is, what is the strength of the induction this algorithm is making as explained above, will this is be a useful induction for a thinking machine?
Thank you so much!
HI jason;
it is great tutorial it help me alot thanks for great effort but i have queastion what if i want to split the data in to randomly 100 training set and 50 test set and i want to generate in separate file with there values instead of printing total numbers? becaouse i want to test them in hugin
thank you so much!
Hi Jason,
It is a really great tutorial. Your article is so clear, but I have a problem.
When I run code, I see the right classification.
> predicted=’Iris-virginica’, actual=’Iris-virginica’
> predicted=’Iris-virginica’, actual=’Iris-virginica’
> predicted=’Iris-virginica’, actual=’Iris-virginica’
> predicted=’Iris-virginica’, actual=’Iris-virginica’
…
However, accuracy is 0%. I run accuracy test but there is no problem with code.
How can I fix the accuracy? Where do I make mistake?
Thanks for reply and your helps.
Hi, I solved this doing this:
Originaly, on the step 5, in the function getAccuracy you have:
…
for x in range(len(testSet)):
if testSet[x][-1] is predictions[x]:
correct += 1
…
The key here is in the IF statement:
if testSet[x][-1] is predictions[x]:
Change “IS” to “==” so the getAccuracy now is:
…
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
…
That solve the problem and works ok!!
I think setting the value of K plays an important role in the accuracy of the prediction. How to determine the best value of ‘K’ . Please suggest some best practices ?
Dear, How to do it for muticlass classifcation with data in excelsheet: images of digits(not handwritten) and label of that image in corresponding next column of excel ??
Your this tutorial is totally on numeric data, just gave me the idea with images.
Very clear explanation and step by step working make this very understandable. I am not sure why the list sortedVotes within the function getResponse is reversed, I thought getResponse is meant to return the most common key in the dictionary classVotes. If you reverse the list, doesn’t this return the least common key in the dictionary?
I do not know how to take the k nearest neighbour for 3 classes for ties vote for example [1,1,2,2,0]. Since for two classes, with k=odd values, we do find the maximum vote for the two classes but ties happens if we choose three classes.
Thanks in advance
hi
thanks for this great effort buddy
i have some basic questions:
1: i opened “iris.data’ file and it is simply in html window. how to download?
2: if do a copy paste technique from html page. where to copy paste?
You can use File->Save as in your browser to save the file or copy the text and paste it int a new file and save it as the file “iris.data” expected by the tutorial.
I hope that helps.
Jason.
This is a really simple but thorough explaination. Thanks for the efforts.
Could you suggest me how to draw a scatter plot for the 3 classes. It will be really great if you could upload the code. Thanks in advance!
What if we want to classify text into categories using KNN,
e.g a given paragraph of text defines {Politics,Sports,Technology}
I’m Working on a project to Classify RSS Feeds
How to download the file without using library csv at the first stage?
Nice explanation Jason.. Really appreciate your work..
Thanks Avinash.
Hi! Really comprehensive tutorial, i loved it!
What will you do if some features are more important than others to determine the right class ?
Thanks Agnes.
Often it is a good idea to perform feature selection before building your model:
Hello,
I get this error message.
Train set: 78
Test set: 21
—————————————————————————
TypeError Traceback (most recent call last)
in ()
72 print(‘Accuracy: ‘ + repr(accuracy) + ‘%’)
73
—> 74 main()
in main()
65 k = 3
66 for x in range(len(testSet)):
—> 67 neighbors = getNeighbors(trainingSet, testSet[x], k)
68 result = getResponse(neighbors)
69 predictions.append(result)
in getNeighbors(trainingSet, testInstance, k)
27 length = len(testInstance)-1
28 for x in range(len(trainingSet)):
—> 29 dist = euclideanDistance(testInstance, trainingSet[x], length)
30 distances.append((trainingSet[x], dist))
31 distances.sort(key=operator.itemgetter(1))
in euclideanDistance(instance1, instance2, length)
20 distance = 0
21 for x in range(length):
—> 22 distance += pow(float(instance1[x] – instance2[x]), 2)
23 return math.sqrt(distance)
24
TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’
Can you please help.
Thank you
It is not clear, it might be a copy-paste error from the post?
Thank you for your answer,
as if i can’t do the subtraction here is the error message
TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’
and i copy/past the code directly from the tutorial
am so happy to be able to extend my gratitude to you.Have searched for good books to explain machine learning(KNN) but those i came across was not as clear and simple as this brilliant and awesome step by step explanation.Indeed you are a distinguished teacher
Thanks.
hi Jason, i really want to get into Machine learning. I want to make a big project for my final year of computer engg. which i am currently in. People are really enervating that way by saying that its too far fetched for a bachelor. I want to prove them wrong. I don’t have much time (6 months from today). I really want to make something useful. Can you send me some links that can help me settle on a project with machine learning? PLZ … TYSM
import numpy as np
from sklearn import preprocessing, cross_validation, neighbors
import pandas as pd
df= np.genfromtxt(‘/home/reverse/Desktop/acs.txt’, delimiter=’,’)
X= np.array(df[:,1])
y= np.array(df[:,0])
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,y,test_size=0.2)
clf = neighbors.KNeighborsClassifier()
clf.fit(X_train, y_train)
ValueError: Found arrays with inconsistent numbers of samples: [ 1 483]
Then I tried to reshape using this code: df.reshape((483,1))
Again i am getting this error “ValueError: total size of new array must be unchanged”
Advance thanks ….
Hi Jason,
great tutorial, very easy to follow. Thanks!
One question though. You wrote:
“Additionally, we want to control which fields to include in the distance calculation. Specifically, we only want to include the first 4 attributes. One approach is to limit the euclidean distance to a fixed length, ignoring the final dimension.”
Can you explain in more detail what you mean here? Why is the final dimension ignored when we want to include all 4 attributes?
Thanks a lot,
Caroline
The gist of the paragraph is that we only want to calculate distance on input variables and exclude the output variable.
The reason is when we have new data, we will not have the output variable, only input variables. Our job will be to find the k most similar instances to the new data and discover the output variable to predict.
In the specific case, the iris dataset has 4 input variables and the 5th is the class. We only want to calculate distance using the first 4 variables.
I hope that makes things clearer.
Hi Jason! The steps u showed are great. Do you any article regarding the same in matlab.
Thank you.
Thanks Pranav,
Sorry I don’t have Matlab examples at this stage.
Best algorithm tutorial I have ever seen! Thanks a lot!
Thanks Sara, I’m glad to hear that.
Detailed explanation given and I am able to understand the algorithm/code well! Trying to implement the same with my own data set (.csv file).
loadDataset(‘knn_test.csv’, split, trainingSet, testSet)
Able to execute and get the output for small dataset (with 4-5 rows and columns in the csv file).
When I try the same code for a bigger data set with 24 columns (inputs) and 12,000 rows (samples) in the csv file, I get the following error:
TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’
The following lines are indicated in the error message:
distance += pow((instance1[x] – instance2[x]), 2)
dist = euclideanDistance(testInstance, trainingSet[x], length)
neighbors = getNeighbors(trainingSet, testSet[x], k)
main()
Any help or suggestion is appreciated. Thank in advance.
Thanks Nivedita.
Perhaps the loaded data needs to be converted from strings into numeric values?
Thank you for the reply Jason. There are no strings / no-numeric values in the data set. It is a csv file with 24 columns(inputs) and 12,083 rows(samples).
Any other advice?
Help is appreciated.
Understood Nivedita, but confirm that the loaded data is stored in memory as numeric values. Print your arrays to screen and/or use type(value) on specific values in each column.
Implemented this in Golang.
Check it out at –
Any feedback is much appreciated.
Also planning to implement as many algorithms as possible in Golang
Well done Vedhavyas.
Thanks for your great effort and implementation but I think that you need to add normalization step before the eucledian distance calculation.
Great suggestion, thanks Baris.
In this case, all input variables have the same scale. But, I agree, normalization is an important step when the scales of the input variables different – and often even when they don’t.
Great article! It would be even fuller if you add some comments in the code; previewing the data and its structure; and a step on normalization although this dataset does not require one.
Great suggestion, thanks Sisay.
hello, i”ve some error like this:
Traceback (most recent call last):
File “C:/Users/FFA/PycharmProjects/Knn/first.py”, line 80, in
main()
File “C:/Users/FFA/PycharmProjects/Knn/first.py”, line 65, in main
loadDataset(‘iris.data’, split, trainingSet, testSet)
File “C:/Users/FFA/PycharmProjects/Knn/first.py”, line 10, in loadDataset
dataset = list(lines)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
what’s wrong ? how to solve the error ?
Change this line:
to this:
See if that makes a difference.
how do i can plot result data set calssifier using matplotlib, thanks
Great question, sorry I don’t have an example at hand.
I would suggest using a simple 2d dataset and use a scatterplot.
hello,
iris.data site link is unreachable. Could you reupload to other site please ? Thank you
Sorry, the UCI Machine Learning Repository that hosts the datasets appears to be down at the moment.
There is a back-up for the website with all the datasets here:
One of the best articles I have ever read! Everything is so perfectly explained … One BIG THANK YOU!!!
I’m so glad to hear that Gabriela.
Great tutorial, worked very well with python3 had to change the iteritems in the getResponse method to .items()
line 63 & 64:
print (“Train set: ” + repr(len(trainingSet)))
print (“Test set: ” + repr(len(testSet)))
generally great tutorial , Thank you 🙂
Thanks Abdallah.
Hi,
first of all, Thanks for this great informative tutorial.
secondly, as compared to your accuracy of ~98%, i am getting an accuracy of around ~65% for every value of k. Can you tell me if this is fine and if not what general mistake i might be doing?
Thanks 🙂
Sorry to hear that.
Perhaps a different version of Python (3 instead of 2.7?), or perhaps a copy-paste error?
Hi, Jason, this article is awesome, it really gave me clear insight of KNN, and it’s so readable. just want to thank you for your incredible work. Awesome!!
I’m glad you found it useful!
Hi,
Thanks for your article.. ?
I have something to ask you..
Is the accuracy of coding indicates the accuracy of the classification of both groups ? What if want to see the accuracy of classification of true positives ? How to coding ?
Thanks before
Yes Meaz, accuracy is on the whole problem or both groups.
You can change it to report on the accuracy of one group or another, I do not have an off the cuff snippet of code for you though.
Super Article!
After reading tones of articles in which by second paragraph I am lost, this article is like explaining Pythagoras theorem to someone who landed on Algebra!
Please keep doing this Jason
I’m glad to hear it Neeraj.
This is a great tutorial, keep it up. I am trying to use KNN to generate epsilon for my DBSCAN algorithm. My data set is a time series. It only has one feature which is sub-sequenced into different time windows. I am wondering if there is a link where I can get a clear cut explanation like this for such a problem.Do you think KNN can predict epsilon since each of my row has a unique ID not setosa etc in the iris data set.
I don’t know Afees, i would recommend try it and see.
Hi Jason
I am working on a similar solution in R but i am facing problems during training of knn
What problem are you seeing Ahmad?
Thank you very much, it really helped me to understand the concept of knn.
But when i run this clock i get an error, and i couldn’t solve it. Could you please help
import csv
import random
def loadDataset(filename, split, trainingSet=[] , testSet=[]):
with open(filename, ‘rb’) as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
trainingSet=[]
testSet=[]
loadDataset('iris.data', 0.66, trainingSet, testSet)
print 'Train: ' + repr(len(trainingSet))
print 'Test: ' + repr(len(testSet))
IndexError Traceback (most recent call last)
in ()
15 trainingSet=[]
16 testSet=[]
—> 17 loadDataset(‘/home/emre/SWE546_DataMining/iris’, 0.66, trainingSet, testSet)
18 print ‘Train: ‘ + repr(len(trainingSet))
19 print ‘Test: ‘ + repr(len(testSet))
in loadDataset(filename, split, trainingSet, testSet)
7 for x in range(len(dataset)):
8 for y in range(4):
—-> 9 dataset[x][y] = float(dataset[x][y])
10 if random.random() < split:
11 trainingSet.append(dataset[x])
IndexError: list index out of range
solved it thanks
Glad to hear it.
How did you solve it?
Hi jason,
I am getting error of syntax in return math.sqrt(distance) and also in undefined variables in main()
Sorry to hear that, what errors exactly?
How should I take testSet from user as input and then print my prediction as output?
AWESOME POST! I cant describe how much this has helped me understand the algorithm so I can write my own C# version. Thank you so much!
I’m glad to here!
Hello,
I have encountered a problem where I need to detect and recognize an object ( in my case a logo ) in an image. My images are some kind of scanned documents that contains mostly text, signatutes and logos. I am interested in localizing the logo and recognizing which logo is it.
My problem seems easier than most object recognition problems since the logo always comes in the same angle only the scale and position that changes. Any help on how to proceed is welcome as I’m out of options right now.
Thanks
Sound great Mark.
I expect CNNs to do well on this problem and some computer vision methods may help further.
Hi Jason, I have folowed through your tutorial and now I am trying to change it to run one of my own files instead of the iris dataset. I keep getting the error:
lines = csv.reader(csvfile)
NameError: name ‘csv’ is not defined
All i have done is change lines 62-64 from:
loadDataset(‘iris.data’, split, trainingSet, testSet)
print ‘Train set: ‘ + repr(len(trainingSet))
print ‘Test set: ‘ + repr(len(testSet))
To:
loadDataset(‘fvectors.csv’, split, trainingSet, testSet)
print( ‘Train set: ‘ + repr(len(trainingSet)))
print( ‘Test set: ‘ + repr(len(testSet)))
I have also tried to it with fvectors instead of fvectors.csv but that doesnt work either. DO you have any idea what is going wrong?
It looks like your python environment might not be installed correctly.
Consider trying this tutorial:
Hi Jason, id missed an import, a silly mistake. But now i get this error:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Any ideas?
I got that fixed by changing
with open(‘fvectors.csv’, ‘rb’) as csvfile:
to
with open(‘fvectors.csv’, ‘rt’) as csvfile:
but now i get this error.
dataset[x][y] = float(dataset[x][y])
ValueError: could not convert string to float:
It appears to not like my headers or labels for the data but are the labels not essential for the predicted vs actual part of the code
Nice.
Double check you have the correct data file.
Consider opening the file in ASCII format open(filename, ‘rt’). This might work better in Python 3.
Hi Jason
thanks a lot for such a wonderful tutorial for KNN.
when i run this code i found the error as
distance += pow((instance1[x] – instance2[x]), 2)
TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’
can u help me f or clearing this error
Thank u
Hi, i have some zipcode point (Tzip) with lat/long. but these points may/maynot fall inside real zip polygon (truezip). i want to do a k nearest neighbor to see the k neighbors of a Tzip point has which majority zipcode. i mean if 3 neighbors of Tzip 77339 says 77339,77339,77152.. then majority voting will determine the class as 77339. i want Tzip and truezip as nominal variable. can i try your code for that? i am very novice at python…thanks in advance.
tweetzip, lat, long, truezip
77339, 73730.689, -990323 77339
77339, 73730.699, -990341 77339
77339, 73735.6, -990351 77152
Perhaps, you may need to tweak it for your example.
Consider using KNN from sklearn, much less code would be required:
Thanks for your reply. i tried to use sklearn as you suggeested. But as for line ‘kfold=model_selection.KFold(n_splits=10,random_state=seed)’ it showed an error ‘seed is not defined’.
Also i think (not sure if i am right) it also take all the variable as numeric..but i want to calculate nearest neighbor distance using 2 numeric variable (lat/long) and get result along each row.
what should i do?
def getNeighbors(trainingSet, testInstance, k):
distances = []
length = len(testInstance)-1
for x in range(len(trainingSet)):
dist = euclideanDistance(testInstance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1))
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
in this fuction either “length = len(testInstance)-1” -1 shouldn’t be there or the
testInstance = [5, 5, 5] should include a character item at its last index??
Am I correct?
Yes, I believe so.
Thanks
plz anyone has dataset related to human behaviour please please share me
Consider searching kaggle and the uci machine learning repository.
Hello, can you tell me at getResponce what exactly are you doing line by line?Cause I do this in Java and cant figure out what exactly I have to do.
thanks
Hi,
I am trying to run your code in Anaconda Python —–Spyder….
I have landed in errors
(1) AttributeError: ‘dict’ object has no attribute ‘iteritems’
(2) filename = ‘iris.data.csv’
with open(filename, ‘rb’) as csvfile:
Initially while loading and opening the data file , it showed an error like
Error: iterator should return strings, not bytes (did you open the file in text mode?)
when i changed rb to rt , it works….i don’t whether it will create problem later…
Please response ASAP
Thanks
The first error may be caused because the example was developed for Python 2.7 and you are using Python 3. I hope to update the examples for Python 3 in the future.
Yes, In Python 3, change to ‘rt’ top open as a text file.
Hi, for python 3
just replace this line(47):
sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True)
with this line:
sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)
it is in def getResponse(neighbors) function
Thanks Ivan.
I didn’t find anything about performance in this article. Is it so that the performance is really bad?
let’s say we have a training set of 100,000 entries, and test set of 1000. Then the euclidean distance should be calculated 10e8 times? Any workaround for this ?
Yes, you can use more efficient distance measures (e.g. drop the sqrt) or use efficient data structures to track distances (e.g. kd-trees/balls)
Nice !! Thank you 🙂
If you are using Python 3,
Use
1.#instead of rb
with open(filename, ‘r’) as csvfile:
2. #instead of iteritems.
sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)
Thanks Vipin!
Hello Jason,
Nice Article. I understand a lot about the KNN under the hood. But one thing though. In scikit learn we use KNN from training to predict in 2 step.
Step 1: Fitting the classifier
Step 2: Predicting
In Fitting section we didn’t pass the test data. Only train data is passed and hence we can see where it is training and where it is testing. With respect to your other blog on Naive Bayes implementation, the part which was calculating mean and std can be considered as fitting/training part while the part which was using Gaussian Normal Distribtuion can be considered as testing/prediction part.
However in this implementation I can not see that distinction. Can you please tell me which part should be considered as training and which part is testing. The reason I am asking this question is because it is always imporatant to correalte with scikit-learn flow so that we get a better idea.
Great question.
There is no training in knn as there is no model. The dataset is the model.
Thanks for the reply…Is it the same for even scikit learn ? What exactly happens when we fit the model for KNN in Scikit Learn then?
Yes it is the same.
Nothing I expect. Perhaps store the dataset in an efficient structure for searching (e.g. kdtree).
Thanks..That’s seems interesting..BTW..I really like your approach..Apart from your e-books what materials (video/books) you think I may need to excel in deep learning and NLP. I want to switch my career as a NLP engineer.
Practice on a lot of problems and develop real and usable skills.
Where do you think I can get best problems that would create real and usable skills? Kaggle?? or somewhere else?
See this post:
Great post. Why aren’t you normalizing the data?
Great question. Because all features in the iris data have the same units.
HI Jason,
In one of your e-book ‘machine_learning_mastery_with_python’ Chapter – 11 (Spot-Check Classification Algorithms), you have explained KNN by using scikit learn KNeighborsClassifier class. I would like to know the difference between the detailed one what you’ve explained here and the KNeighborsClassifier class. It might be a very basic question for ML practitioner as I’m very new in ML and trying to understand the purposes of different approaches.
Thanks
Golam Sarwar
The tutorial here is to help understand how the kNN method works.
To use it in practice, I would strongly encourage you to use the implementation in a library like sklearn.
The main reasons are to avoid bugs and for performance. Learn more here:
Thanks…..
nice explication and great tutorial , i hope that you have other blogs about other classification algorithms like this
thanks …. Jason
Thanks.
I do, use the blog search.
Hi Jason,
Nice explanation !!
Can you please show us the implementation of the same (KNN) algorithm in Java also ?
Thanks for the suggestion, perhaps in the future.
Thanks Jason
You’re welcome.
Hi Jason,
Is it normal to get different accuracy, FP, TP, FN, TN on every different try? I am using same data.
Yes, see this post for an explanation of why to expect this in machine learning:
Thanks Jason. you can add below explanation to the post to make it more clear:
I’ve discovered that the different accuracy is caused by the below line in the loadDataset function:
if random.random() randomized.csv
Hi,
I am using that function instead of getAccuracy. It gives TP, TN, FP, FN.
def getPerformance(testSet, predictions):
tp = 0
tn = 0
fp = 0
fn = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
if predictions[x] == “yes”:
tp += 1
else:
tn += 1
else:
if predictions[x] == “yes”:
fp += 1
else:
fn += 1
performance = [ ((tp/float(len(testSet))) * 100.0), ((tn/float(len(testSet))) * 100.0), ((fp/float(len(testSet))) * 100.0), ((fn/float(len(testSet))) * 100.0) ]
return performance
This is the best tutorial entry I have seen on any blog post about any topic. It is very easy to follow. The code is correct and not outdated. I love the way everything is structured. It kind of follows the TDD approach where it first builds on the production code step by step, testing each step on the way. Kudos to you for the great work! This is indeed helpful.
Thanks! | https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/ | CC-MAIN-2017-43 | refinedweb | 7,442 | 66.44 |
Yesterday’s Programming Praxis problem is about making a convenient way to do modular arithmetic. While the most elegant way to do this in Haskell is probably via a Num instance, my attempts at achieving this have failed because either the typechecker cannot infer everything anymore, or because you cannot use the same syntax for modular square roots, congruency and the rest of the operations. Maybe a better Haskell hacker than me can come up with a working solution.
In the meantime, we’re going to use a solution that’s consistent and plays nice with the type checker, even if it’s a tad less elegant.
First our imports:
import Data.Bits import Data.List
We’ll be needing these two functions for divisions.
euclid :: Integral a => a -> a -> a euclid x y = f 1 0 x 0 1 y where f a b g u v w | w == 0 = mod a y | otherwise = f u v w (a-q*u) (b-q*v) (g-q*w) where q = div g w inv :: Integral a => a -> a -> a inv x m | gcd x m == 1 = euclid x m | otherwise = error "divisor must be coprime to modulus"
All the basic operations are pretty simple:
(<=>) :: Integral a => a -> a -> a -> Bool a <=> b = \m -> mod a m == mod b m (<+>), (<->), (<*>), (</>) :: Integral a => a -> a -> a -> a a <+> b = \m -> mod (a + mod b m) m a <-> b = a <+> (-b) a <*> b = \m -> mod (a * mod b m) m a </> b = \m -> (a <*> inv b m) m
For exponentiation we get to recycle the expm function, which was used in previous exercises.
expm :: Integer -> Integer -> Integer -> Integer expm b e m = foldl' (\r (b', _) -> mod (r * b') m) 1 . filter (flip testBit 0 . snd) . zip (iterate (flip mod m . (^ 2)) b) $ takeWhile (> 0) $ iterate (`shiftR` 1) e
And a little syntactic shortcut for expm:
(<^>) :: Integer -> Integer -> Integer -> Integer (<^>) = expm
This modular square root implementation is undoubtedly a lot slower than the provided one. However, implementing that one would be boring (just translating Scheme to Haskell, with not much opportunity for size reduction) and would double or triple the size of the code. Therefore we use a more naive algorithm, that works well enough when the modulus is small. Copying the provided algorithm to Haskell is left as an exercise for the reader.
sqrtm :: Integral a => a -> a -> [a] sqrtm x m = case [n | n <- [1..m], (n <*> n) m == mod x m] of (_:_:_:_) -> [] s -> s
The modulo function is just syntactic sugar for reverse function application.
modulo :: a -> (a -> b) -> b modulo = flip ($)
This results in test code that looks as follows:
main :: IO () main = do mapM_ (modulo 12) [ print . (17 <=> 5), print . (8 <+> 9), print . (4 <-> 9), print . (3 <*> 7), print . (9 </> 7)] mapM_ (modulo 13) [ print . (6 <^> 2), print . (7 <^> 2), print . sqrtm 10]
Not terrible, but I believe a better solution exists. If anyone has one, please let me know.
Tags: arithmetic, Haskell, kata, modular, praxis, programming
December 3, 2011 at 4:50 pm |
I been looking for a good solution to this problem, but there seems to be surprisingly few around.
I dont immediately see how your solution would look in a more complicated example. Do you have to write out the same modulo number more than once?
For example in this hideous function to add two points on an elliptic curve::56 pm |
It had some indentation when I pasted it in. Stupid WordPress.
What about this::57 pm
Pretty bad also.
December 3, 2011 at 5:40 pm |
After more investigation it seems like it is not possible to compose your mod operations to a compound expression:
n = modulo 13 (5 6 7)
The reason is that you functions take integers as arguments, but return functions, so the result of one operation cant be the argument to the next.
Hm, what would be a good solution to that…?
December 3, 2011 at 6:21 pm |
Here is one approach where the operation take and return functions. The disadvantage is that you cant use ints directly in the expressions, you have to wrap them in the ugly i functions.
tfunc = ( | http://bonsaicode.wordpress.com/2009/07/08/programming-praxis-modular-arithmetic/ | CC-MAIN-2013-20 | refinedweb | 698 | 69.31 |
CodePlexProject Hosting for Open Source Software
Hi!
1) Finally created my PPPOE dialer. Now, as I always want to improve the code, comes the question: If I have 2 or more NICs, Is there a way for me to select which one will do the dotRas dialing?
2) I did some research on the discussion list and what I saw did not have a way dotRas "native" to control the speed of download / upload connection, as well as amount of data traffic. For this, I have to use the class "System.Net.NetworkInformation",
correct?
1) DotRas doesn't handle this. If there's something in Windows that'll do it, you'll need to track that down. Could have something to do with the routing tables, not sure though. Just a theory.
2) DotRas is simply the thing that gets Windows to connect to the remote network, download managers typically have logic built into them to control the speed at which they download the data. They don't change the upload / download rate of the connection
itself but rather change the speed at which they download the data. As for what you need to accomplish that in your project, you're gonna be on your own there.
Hope that helps!
Hello,
After talking with other people, I saw to my project is not necessary that control of the network cards. For now, this will not be implemented.
About the connection speed, this would not be good right now. The interesting thing for me is to control data traffic connection. That I got this:
Dim devices() = NetworkInterface.GetAllNetworkInterfaces()
Dim device As NetworkInterface
For Each device In devices
Dim received As Long = device.GetIPv4Statistics().BytesReceived()
Dim sent As Long = device.GetIPv4Statistics().BytesSent()
It has some controls over what I do inside the loop, but basically how it works.
Thanks for the help.
If all you're trying to do is retrieve the bytes sent and received, you can use DotRas to pull that information for you. For example:
using DotRas;
using System.Linq;
RasConnection connection = RasConnection.GetActiveConnections().Where(c => c.Name = "My Connection").FirstOrDefault();
if (connection != null)
{
RasLinkStatistics stats = connection.GetConnectionStatistics();
if (stats != null)
{
long received = stats.BytesRecieved;
long sent = stats.BytesTransmitted;
}
}
This will find your active connection in the list of active connections, and then request the connection statistics from Windows which you can then use.
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. | https://dotras.codeplex.com/discussions/392035 | CC-MAIN-2017-43 | refinedweb | 431 | 68.47 |
acl_get_file()
Get the ACL for a given path
Synopsis:
#include <sys/acl.h> acl_t acl_get_file( const char *path_p, acl_type_t type );
Since:
BlackBerry 10.0.0
Arguments:
- path_p
- The path that you want to get the ACL for.
- type
- The type of ACL; this must currently be ACL_TYPE_ACCESS.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The acl_get_file() function gets the ACL associated with the given file or directory, copies it into working storage, and returns a pointer to that storage. When you're finished with the ACL, you should call acl_free() to release it.
The ACL in working storage is independent of the file or directory's ACL. Changes that you make to the copy in working storage don't affect the file or directory's ACL.
Errors:
- EACCES
- Search permission was denied for a component of the path prefix, or the object exists and the process doesn't have the appropriate access rights.
- EINVAL
- The type argument isn't ACL_TYPE_ACCESS.
- ENAMETOOLONG
- The length of the path_p argument exceeds PATH_MAX.
- ENOENT
- The named object doesn't exist, or path_p is an empty string.
- ENOMEM
- There wasn't enough memory available to create the ACL in working storage.
- ENOTDIR
- A component of the path prefix isn't a directory.
Classification:
This function is based on the withdrawn POSIX draft P1003.1e.
Last modified: 2014-11-17
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/a/acl_get_file.html | CC-MAIN-2020-05 | refinedweb | 254 | 67.86 |
When it comes to styling your React app, you have a ton of different options. Which do you choose?
I have broken down the 5 primary ways you have to choose between when writing CSS in your React app.
There is no #1 way to approach to writing styles in React for every project. Every project is different and has different needs.
That’s why at the end of each section, I will cover the pros and cons of each approach to help you choose which is the best for you in your projects.
Let’s get started!
Want to become a pro React developer while building amazing projects? Check out The React Bootcamp.
What We Will Be Coding
To see how the code for each of these styling approaches compare with one another, we will create the same example: a simple, but clean testimonial card.
Want to code along with each of these examples? Go to react.new to create a new React application instantly ✨
Inline Styles
Inline styles are the most direct away to style any React application.
Styling elements inline doesn’t require you to create a separate stylesheet.
Style applied directly to the elements as compared to styles in a stylesheet also have higher precedence. This means that they “override” other style rules that may be applied to an element.
Here is our testimonial card styled with inline styles:
export default function App() { return ( <section style={{ fontFamily: '-apple-system', fontSize: "1rem", fontWeight: 1.5, lineHeight: 1.5, color: "#292b2c", backgroundColor: "#fff", padding: "0 2em" }} > <div style={{ textAlign: "center", maxWidth: "950px", margin: "0 auto", border: "1px solid #e6e6e6", padding: "40px 25px", marginTop: "50px" }} > <img src="" alt="Tammy Stevens" style={{ margin: "-90px auto 30px", width: "100px", borderRadius: "50%", objectFit: "cover", marginBottom: "0" }} /> <div> <p style={{ lineHeight: 1.5, fontWeight: 300, marginBottom: "25px", fontSize: "1.375rem" }} > This is one of the best developer blogs on the planet! I read it daily to improve my skills. </p> </div> <p style={{ marginBottom: "0", fontWeight: 600, fontSize: "1rem" }} > Tammy Stevens <span style={{ fontWeight: 400 }}> · Front End Developer</span> </p> </div> </section> ); }
Despite a few quick benefits, inline styles are only an acceptable choice for very small applications. The difficulties with inline styles become apparent as your code base grows even slightly.
As the code example above shows, even a small component like this becomes very bulky if all the styles are inline.
One quick trick however is to put inline styles into reusable variables, which can be stored in a separate file:
const styles = { section: { fontFamily: "-apple-system", fontSize: "1rem", fontWeight: 1.5, lineHeight: 1.5, color: "#292b2c", backgroundColor: "#fff", padding: "0 2em" }, wrapper: { textAlign: "center", maxWidth: "950px", margin: "0 auto", border: "1px solid #e6e6e6", padding: "40px 25px", marginTop: "50px" }, avatar: { margin: "-90px auto 30px", width: "100px", borderRadius: "50%", objectFit: "cover", marginBottom: "0" }, quote: { lineHeight: 1.5, fontWeight: 300, marginBottom: "25px", fontSize: "1.375rem" }, name: { marginBottom: "0", fontWeight: 600, fontSize: "1rem" }, position: { fontWeight: 400 } }; export default function App() { return ( <section style={styles.section}> <div style={styles.wrapper}> <img src="" alt="Tammy Stevens" style={styles.avatar} /> <div> <p style={styles.quote}> This is one of the best developer blogs on the planet! I read it daily to improve my skills. </p> </div> <p style={styles.name}> Tammy Stevens <span style={styles.position}> · Front End Developer</span> </p> </div> </section> ); }
Despite this improvement, inline styles do not have a number of essential features that any simple CSS stylesheet could provide.
For example, you cannot write animations, styles for nested elements (i.e. all child elements, first-child, last-child), pseudo-classes (i.e. :hover), and pseudo-elements (::first-line) to name a few.
If you’re prototyping an application, inline styles are great. However, as you get further into making it, you will need to switch to another CSS styling option to give you basic CSS features.
👍 Pros:
- Quickest way to write styles
- Good for prototyping (write inline styles then move to stylesheet)
- Has great preference (can override styles from a stylesheet)
👎 Cons:
- Tedious to convert plain CSS to inline styles
- Lots of inline styles make JSX unreadable
- You can not use basic CSS features like animations, selectors, etc.
- Does not scale well
Plain CSS
Instead of using inline styles, it’s common to import a CSS stylesheet to style a component’s elements.
Writing CSS in a stylesheet is probably the most common and basic approach to styling a React application, but it shouldn’t be dismissed so easily.
Writing styles in “plain” CSS stylesheets is getting better all the time, due to an increasing set of features available in the CSS standard.
This includes features like CSS variables to store dynamic values, all manner of advanced selectors to select child elements with precision, and new pseudo-classes like
:is and
:where.
Here is our testimonial card written in plain CSS and imported at the top of our React application:
/* src/styles; } .testimonial { margin: 0 auto; padding: 0 2em; } .testimonial-wrapper { text-align: center; max-width: 950px; margin: 0 auto; border: 1px solid #e6e6e6; padding: 40px 25px; margin-top: 50px; } .testimonial-quote p { line-height: 1.5; font-weight: 300; margin-bottom: 25px; font-size: 1.375rem; } .testimonial-avatar { margin: -90px auto 30px; width: 100px; border-radius: 50%; object-fit: cover; margin-bottom: 0; } .testimonial-name { margin-bottom: 0; font-weight: 600; font-size: 1rem; } .testimonial-name span { font-weight: 400; }
// src/App.js import "./styles.css"; export default function App() { return ( <section className="testimonial"> <div className="testimonial-wrapper"> <img className="testimonial-avatar" src="" alt="Tammy Stevens" /> <div className="testimonial-quote"> <p> This is one of the best developer blogs on the planet! I read it daily to improve my skills. </p> </div> <p className="testimonial-name"> Tammy Stevens<span> · Front End Developer</span> </p> </div> </section> ); }
For our testimonial card, note that we are creating classes to be applied to each individual element. These classes all start with the same name
testimonial-.
CSS written in a stylesheet is a great first choice for your application. Unlike inline styles, it can style your application in virtually any way you need.
One minor problem might be your naming convention. Once you have a very well-developed application, it becomes harder to think of unique classnames for your elements, especially when you have 5 divs wrapped inside each other.
If you don’t have a naming convention you are confident with (i.e. BEM), it can be easy to make mistakes, plus create multiple classes with the same name, which leads to conflicts.
Additionally, writing normal CSS can be more verbose and repetitive than newer tools like SASS/SCSS. As a result, it can take a bit longer to write your styles in CSS versus a tool like SCSS or a CSS-in-JS library.
Plus, it’s important to note that since CSS cascades to all children elements, if you apply a CSS stylesheet to a component it is not just scoped to that component. All its declared rules will be transferred to any elements that are children of your styled component.
If you are confident with CSS, it is definitely a viable choice for you to style any React application.
With that being said, there are a number of CSS libraries that give us all the power of CSS with less code and include many additional features that CSS will never have on its own (such as scoped styles and automatic vendor prefixing).
👍 Pros:
- Gives us all of the tools of modern CSS (variables, advanced selectors, new pseudo-classes, etc.)
- Helps us clean up our component files from inline styles
👎 Cons:
- Need to setup vendor prefixing to ensure latest features work for all users
- Requires more typing and boilerplate than other CSS libraries (i.e. SASS)
- Any stylesheet cascades to component and all children; not scoped
- Must use a reliable naming convention to ensure styles don’t conflict
SASS / SCSS
What is SASS? SASS is an acronym that stands for: Syntactically Awesome Style Sheets.
SASS gives us some powerful tools, many of which don’t exist in normal CSS stylesheets. It includes features like variables, extending styles, and nesting.
SASS allows us to write styles in two different kinds of stylesheets, with the extensions .scss and .sass.
SCSS styles are written in a similar syntax to normal CSS, however SASS styles do not require us to use open and closing brackets when writing style rules.
Here is a quick example of an SCSS stylesheet with some nested styles:
/* styles.scss */ nav { ul { margin: 0; padding: 0; list-style: none; } li { display: inline-block; } a { display: block; padding: 6px 12px; text-decoration: none; } }
Compare this with the same code written in a SASS stylesheet:
/* styles.sass */ nav ul margin: 0 padding: 0 list-style: none li display: inline-block a display: block padding: 6px 12px text-decoration: none
Since this is not regular CSS, it needs to be compiled from SASS into plain CSS. To do so in our React projects, you can use a library like node-sass.
If you are using a Create React App project, to start using .scss and .sass files, you can install node-sass with npm:
npm install node-sass
Here is our testimonial card styled with SCSS:
/* src/styles.scss */ $font-stack: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; $text-color: #292b2c; %font-basic { font-size: 1rem; } body { @extend %font-basic; font-family: $font-stack; color: $text-color; margin: 0; font-size: 1rem; font-weight: 1.5; line-height: 1.5; background-color: #fff; } /* unchanged rules skipped */ .testimonial-name { @extend %font-basic; margin-bottom: 0; font-weight: 600; span { font-weight: 400; } }
These styles give us the following features: variables, extending styles and nested styles.
Variables: You can use dynamic values by writing variables, just like in JavaScript, by declaring them with a
$ at the beginning.
There are two variables that can be used in multiple rules:
$font-stack,
$text-color.
Extending / Inheritance: You can add onto style rules by extending them. To extend rules, you create your own selector which can be reused like a variable. The name of rules that you want to extend start with
%.
The variable
%font-basic is inherited by the rules
body and
.testimonial-name.
Nesting: Instead of writing multiple rules that begin with the same selector, you can nest them.
In
.testimonial-name , we use a nested selector to target the
span element within it.
You can find a working version of a React application with SCSS here.
👍 Pros:
- Includes many dynamic CSS features like extending, nesting, and mixins
- CSS styles can be written with much less boilerplate over plain CSS
👎 Cons:
- Like plain CSS, styles are global and not scoped to any one component
- CSS stylesheets is starting to include a number of features that SASS had exclusively, such as CSS variables (not necessarily a con, but worth noting)
- SASS / SCSS often requires setup, such as installing the Node library
node-sass
CSS Modules
CSS modules are another slight alternative to something like CSS or SASS.
What is great about CSS modules is that they can be used with either normal CSS or SASS. Plus, if you are using Create React App you can start using CSS modules with no setup at all.
Here is our application written with CSS modules:
/* src/styles.module; } /* styles skipped */ .testimonial-name span { font-weight: 400; }
import styles from './styles.module.css'; export default function App() { return ( <section className={styles.testimonial}> <div className={styles['testimonial-wrapper']}> <img src="" alt="Tammy Stevens" className={styles['testimonial-avatar']} /> <div> <p className={styles['testimonial-quote']}> This is one of the best developer blogs on the planet! I read it daily to improve my skills. </p> </div> <p className={styles['testimonial-name']}> Tammy Stevens <span> · Front End Developer</span> </p> </div> </section> ); }
Our CSS file has the name
.module in it before the extension
.css. Any CSS module file must have the name “module” in it and end in the appropriate extension (if we are using CSS or SASS/SCSS).
What is interesting to note if we look at the code above is that CSS modules are written just like normal CSS, but are imported and used as if it were created as objects (inline styles).
The benefit of CSS modules is that it helps avoid our problem of class conflicts with normal CSS. The properties that we are referencing turn into unique classnames that cannot conflict with one another when our project is built.
Our generated HTML elements will look like this:
<p class="_styles__testimonial-name_309571057"> Tammy Stevens </p>
Plus, CSS modules solve the problem of global scope in CSS. As compared to our normal CSS stylesheets, CSS declared using modules to individual components will not cascade to child components.
Therefore, CSS modules are best to use over CSS and SASS to make sure classes don’t conflict and to write predictable styles that only apply to one or another component.
👍 Pros:
- Styles are scoped to one or another component (unlike CSS / SASS)
- Unique, generated classnames ensure no style conflict
- Can use them immediately without setup in CRA projects
- Can be used with SASS / CSS
👎 Cons:
- Can be tricky to reference classnames
- May be a learning curve to use CSS styles like object properties
CSS-in-JS
Similar to how React allowed us to write HTML as JavaScript with JSX, CSS-in-JS has done something similar with CSS.
CSS-in-JS allows us to write CSS styles directly in our components’ javascript (.js) files.
Not only does it allow you write CSS style rules without having to make a single .css file, but these styles are scoped to individual components.
In other words, you can add, change or remove CSS without any surprises. Changing one component’s styles will not impact the styles of the rest of your application.
CSS-in-JS often makes use of a special type of JavaScript function called a tagged template literal. What’s great about this is that we can still write plain CSS style rules directly in our JS!
Here’s a quick example of a popular CSS-in-JS library, Styled Components:
import styled from "styled-components"; const Button = styled.button` color: limegreen; border: 2px solid limegreen; font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; &:hover { opacity: 0.9; } `; export default function App() { return ( <div> <Button>Click me</Button> </div> ); }
Note a few things here:
- You can write normal CSS styles, but can include nested styles and pseudo-classes (like hover).
- You can associate styles with any valid HTML element, such as the button element above (see
styled.button).
- You can create new components with these associated styles. See how
Buttonis used in our App component.
Since this is a component, can it be passed props? Yes! We can export this component and use it anywhere in our app we like, plus give it dynamic features through props.
Let’s say that you want an inverted variant of
Button above with an inverted background and text. No problem.
Pass the
inverted prop to our second button and in
Button, you can access all props passed to the component using the
${} syntax with an inner function.
import styled from "styled-components"; const Button = styled.button` background: ${props => props.inverted ? "limegreen" : "white"}; color: ${props => props.inverted ? "white" : "limegreen"}; border: 2px solid limegreen; font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; &:hover { opacity: 0.9; } `; export default function App() { return ( <div> <Button>Click me</Button> <Button inverted>Click me</Button> </div> ); }
In the return of the function, you can select the
inverted prop and use a ternary to conditionally determine the color of the background and text.
Here is the result:
There are a great deal more benefits to using a CSS-in-JS library to style your React applications (too many to cover here), some of which I will list below.
Be sure to check out the two most popular CSS-in-JS libraries for React: Emotion and Styled Components.
One downside to using a CSS-in-JS libraries is adding an additional library to your project. However, I would argue this is easily worth the improved developer experience you have when styling your React apps versus plain CSS.
👍 Pros:
- CSS-in-JS is predictable – styles are scoped to individual components
- Since our CSS is now JS, we can export, reuse, and even extend our styles through props
- CSS-in-JS libraries ensure there are no styling conflicts by generating unique classnames for your written styles
- No need to focus on naming conventions for your classes, just write styles!
👎 Cons:
- Unlike plain CSS, you will need to install one or more third-party JavaScript libraries, which will add weight to your built project
Conclusion
Note that I did not include component libraries in this comparison. I wanted to focus primarily on different ways to compose styles yourself.
Be aware that choosing a library with pre-made components and styles like Material UI or Ant Design (to name a couple) is a totally valid choice for your project.
I hope this guide gave you a good understanding of how to style your React apps along with which approach to choose for your next project.
Want The Rest? Join The React Bootcamp:
| https://envo.app/how-to-style-your-react-app-5-ways-to-write-css-in-2021/ | CC-MAIN-2022-33 | refinedweb | 2,884 | 62.17 |
I have read multiple posts on StackOverFlow about checked vs unchecked exceptions. I’m honestly still not quite sure how to use them properly.
Joshua Bloch in “Effective Java” said that
Use checked exceptions for
recoverable conditions and runtime
exceptions for programming errors
(Item 58 in 2nd edition)
Let’s see if I understand this correctly.
Here is my understanding of a checked exception:
try{ String userInput = //read in user input Long id = Long.parseLong(userInput); }catch(NumberFormatException e){ id = 0; //recover the situation by setting the id to 0 }
1. Is the above consider a checked exception?
2. Is RuntimeException an unchecked exception?
Here is my understanding of an unchecked exception:
try{ File file = new File("my/file/path"); FileInputStream fis = new FileInputStream(file); }catch(FileNotFoundException e){ //3. What should I do here? //Should I "throw new FileNotFoundException("File not found");"? //Should I log? //Or should I System.exit(0);? }
4. Now, couldnt the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the
catch above)
try{ String filePath = //read in from user input file path File file = new File(filePath); FileInputStream fis = new FileInputStream(file); }catch(FileNotFoundException e){ //Kindly prompt the user an error message //Somehow ask the user to re-enter the file path. }
5. Why do people do this?
public void someMethod throws Exception{ }
Why do they let the exception bubble up? Isn’t handling the error sooner better? Why bubble up?
EDIT: Should I bubble up the exact exception or mask it using Exception?
Below are my readings
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don’t have them. So you can always throw a subclass of
RuntimeException (unchecked exception)
However, I think checked exceptions are useful – they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It’s just that checked exceptions are overused in the Java platform, which makes people hate them.
Here’s my extended view on the topic.
As for the particular questions:
Is the
NumberFormatExceptionconsider a checked exception?
No.
NumberFormatExceptionis unchecked (= is subclass of
RuntimeException). Why? I don’t know. (but there should have been a method
isValidInteger(..))
Is
RuntimeExceptionan unchecked exception?
Yes, exactly.
What should I do here?
It depends on where this code is and what you want to happen. If it is in the UI layer – catch it and show a warning; if it’s in the service layer – don’t catch it at all – let it bubble. Just don’t swallow the exception. If an exception occurs in most of the cases you should choose one of these:
- log it and return
- rethrow it (declare it to be thrown by the method)
- construct a new exception by passing the current one in constructor
Now, couldn’t the above code also be a checked exception? I can try to recover the situation like this? Can I?
It could’ve been. But nothing stops you from catching the unchecked exception as well
Why do people add class
Exceptionin the throws clause?
Most often because people are lazy to consider what to catch and what to rethrow. Throwing
Exceptionis a bad practice and should be avoided.
Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.
Whether something is a “checked exception” has nothing to do with whether you catch it or what you do in the catch block. It’s a property of exception classes. Anything that is a subclass of
Exception except for
RuntimeException and its subclasses is a checked exception.
The Java compiler forces you to either catch checked exceptions or declare them in the method signature. It was supposed to improve program safety, but the majority opinion seems to be that it’s not worth the design problems it creates.
Why do they let the exception bubble
up? Isnt handle error the sooner the
better? Why bubble up?
Because that’s the entire point of exceptions. Without this possibility, you would not need exceptions. They enable you to handle errors at a level you choose, rather than forcing you to deal with them in low-level methods where they originally occur.
Is the above consider a checked exception?
No
The fact that you are handling an exception does not make it a Checked Exception if it is a RuntimeException.
Is RuntimeException an unchecked exception?
Yes
Checked Exceptions are subclasses of java.lang.Exception
Unchecked Exceptions are subclasses of java.lang.RuntimeException
Calls throwing checked exceptions need to be enclosed in a try{} block or handled in a level above in the caller of the method. In that case the current method must declare that it throws said exceptions so that the callers can make appropriate arrangements to handle the exception.
Hope this helps.
Q: should I bubble up the exact
exception or mask it using Exception?
A: Yes this is a very good question and important design consideration. The class Exception is a very general exception class and can be used to wrap internal low level exceptions. You would better create a custom exception and wrap inside it. But, and a big one – Never ever obscure in underlying original root cause. For ex,
Dont ever do following –
try { attemptLogin(userCredentials); } catch (SQLException sqle) { throw new LoginFailureException("Cannot login!!"); //<-- Eat away original root cause, thus obscuring underlying problem. }
Instead do following:
try { attemptLogin(userCredentials); } catch (SQLException sqle) { throw new LoginFailureException(sqle); //<-- Wrap original exception to pass on root cause upstairs!. }
Eating away original root cause buries the actual cause beyond recovery is a nightmare for production support teams where all they are given access to is application logs and error messages.
Although the latter is a better design but many people dont use it often because developers just fail to pass on the underlying message to caller. So make a firm note:
Always pass on the actual exception back whether or not wrapped in any application specific exception.
On try-catching RuntimeExceptions
RuntimeExceptions as a general rule should not be try-catched. They generally signal a programming error and should be left alone. Instead the programmer should check the error condition before invoking some code which might result in a RuntimeException. For ex:
try { setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!); } catch (NullPointerException npe) { sendError("Sorry, your userObject was null. Please contact customer care."); }
This is a bad programming practice. Instead a null-check should have been done like –
if (userObject != null) { setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!); } else { sendError("Sorry, your userObject was null. Please contact customer care."); }
But there are times when such error checking is expensive such as number formatting, consider this –
try { String userAge = (String)request.getParameter("age"); userObject.setAge(Integer.parseInt(strUserAge)); } catch (NumberFormatException npe) { sendError("Sorry, Age is supposed to be an Integer. Please try again."); }
Here pre-invocation error checking is not worth the effort because it essentially means to duplicate all the string-to-integer conversion code inside parseInt() method – and is error prone if implemented by a developer. So it is better to just do away with try-catch.
So NullPointerException and NumberFormatException are both RuntimeExceptions, catching a NullPointerException should replaced with a graceful null-check while I recommend catching a NumberFormatException explicitly to avoid possible introduction of error prone code.
1 . If you are unsure about an exception, check the API:
java.lang.Object extended by java.lang.Throwable extended by java.lang.Exception extended by java.lang.RuntimeException //<-NumberFormatException is a RuntimeException extended by java.lang.IllegalArgumentException extended by java.lang.NumberFormatException
2 . Yes, and every exception that extends it.
3 . There is no need to catch and throw the same exception. You can show a new File Dialog in this case.
4 . FileNotFoundException is already a checked exception.
5 . If it is expected that the method calling
someMethod to catch the exception, the latter can be thrown. It just “passes the ball”. An example of it usage would be if you want to throw it in your own private methods, and handle the exception in your public method instead.
A good reading is the Oracle doc itself:.
There’s also an important bit of information in the Java Language Specification:
The checked exception classes named in the throws clause are part of the contract between the implementor and user of the method or constructor.
The bottom line IMHO is that you can catch any
RuntimeException, but you are not required to and, in fact the implementation is not required to maintain the same non-checked exceptions thrown, as those are not part of the contract.
1) No, a NumberFormatException is an unchecked Exception. Even though you caught it (you aren’t required to) it is unchecked. This is because it is a subclass of IllegalArgumentException which is a subclass of RuntimeException.
2) RuntimeException is the root of all unchecked Exceptions. Every subclass of RuntimeException is unchecked. All other Exceptions and Throwables are checked except for Errors ( Which comes under Throwable).
3/4) You could alert the user that they picked a non-existent file and ask for a new one. Or just quit informing the user that they entered something invalid.
5) Throwing and catching ‘Exception’ is bad practice. But more generally, you might throw other exceptions so the caller can decide how to deal with it. For example, if you wrote a library to handle reading some file input and your method was passed a non-existent file, you have no idea how to handle that. Does the caller want to ask again or quit? So you throw the Exception up the chain back to the caller.
In many cases, an unchecked Exception occurs because the programmer did not verify inputs (in the case of NumberFormatException in your first question). That’s why its optional to catch them, because there are more elegant ways to avoid generating those exceptions.
Checked – Prone to happen. Checked in Compile time.
Eg.. FileOperations
UnChecked – Due to Bad data. Checked in Run time.
Eg..
String s = "abc"; Object o = s; Integer i = (Integer) o; Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at Sample.main(Sample.java:9)
Here exception is due to bad data and in no way it can be determined during compile time.
Checked exceptions are checked at compile time by the JVM and its related to resources(files/db/stream/socket etc). The motive of checked exception is that at compile time if the resources are not available the application should define an alternative behaviour to handle this in the catch/finally block.
Unchecked exceptions are purely programmatic errors, wrong calculation, null data or even failures in business logic can lead to runtime exceptions. Its absolutely fine to handle/catch unchecked exceptions in code.
Explanation taken from
To answer the final question (the others seem thoroughly answered above), “Should I bubble up the exact exception or mask it using Exception?”
I am assuming you mean something like this:
public void myMethod() throws Exception { // ... something that throws FileNotFoundException ... }
No, always declare the most precise exception possible, or a list of such. The exceptions you declare your method as capable of throwing are a part of the contract between your method and the caller. Throwing “FileNotFoundException” means that it is possible the file name isn’t valid and the file will not be found; the caller will need to handle that intelligently. Throwing “Exception” means “Hey, sh*t happens. Deal.” Which is a very poor API.
In the comments on the first article there are some examples where “throws Exception” is a valid and reasonable declaration, but that’s not the case for most “normal” code you will ever write.
- Java distinguish between two categories of exceptions (checked & unchecked)
- Java enforce a catch or declared requirement for checked exceptions
- An exception’s type determines whether an exception is checked or unchecked.
- All exception types that are direct or indirect subclasses of class RuntimeException
are unchecked exception.
- All classes that inherit from class Exception but not RuntimeException are considered to be checked exceptions.
- Classes that inherit from class Error are considered to be unchecked.
- Compiler checks each method call and deceleration to determine whether the
method throws checked exception.
- If so the compiler ensures the exception is caught or is declared in a throws clause.
- To satisfy the declare part of the catch-or-declare requirement, the method that generates
the exception must provide a throws clause containing the checked-exception.
- Exception classes are defined to be checked when they are considered important enough to catch or declare.
Why do they let the exception bubble up? Isn’t handling the error sooner better? Why bubble up?
For example let say you have some client-server application and client had made a request for some resource that couldn’t be find out or for something else error some might have occurred at the server side while processing the user request then it is the duty of the server to tell the client why he couldn’t get the thing he requested for,so to achieve that at server side, code is written to throw the exception using throw keyword instead of swallowing or handling it.if server handles it/swallow it, then there will be no chance of intimating to the client that what error had occurred.
Note:To give a clear description of what the error type has occurred we can create our own Exception object and throw it to the client.
Runtime Exceptions
Runtime exceptions are referred to as unchecked exceptions. All other exceptions
are checked exceptions, and they don’t derive from java.lang.RuntimeException.
Checked Exceptions API throw checked exceptions, so you will often write exception handlers to cope with exceptions generated by methods you didn’t write.
Here is a simple rule that can help you decide. It is related to how interfaces are used in Java.
Take your class and imagine designing an interface for it such that the interface describes the functionality of the class but none of the underlying implementation (as an interface should). Pretend perhaps that you might implement the class in another way.
Look at the methods of the interface and consider the exceptions they might throw:
If an exception can be thrown by a method, regardless of the underlying implementation (in other words, it describes the functionality only) then it should probably be a checked exception in the interface.
If an exception is caused by the underlying implementation, it should not be in the interface. Therefore, it must either be an unchecked exception in your class (since unchecked exceptions need not appear in the interface signature), or you must wrap it and rethrow as a checked exception that is part of the interface method.
To decide if you should wrap and rethrow, you should again consider whether it makes sense for a user of the interface to have to handle the exception condition immediately, or the exception is so general that there is nothing you can do about it and it should propagate up the stack. Does the wrapped exception make sense when expressed as functionality of the new interface you are defining or is it just a carrier for a bag of possible error conditions that could also happen to other methods? If the former, it might still be a checked exception, otherwise it should be unchecked.
You should not usually plan to “bubble-up” exceptions (catch and rethrow). Either an exception should be handled by the caller (in which case it is checked) or it should go all the way up to a high level handler (in which case it is easiest if it is unchecked).
My absolute favorite description of the difference between unchecked and checked exceptions is provided by the Java Tutorial trail article, “Unchecked Exceptions – the Controversy” (sorry to get all elementary on this post – but, hey, the basics are sometimes the best):
Here’s the bottom line guideline: If a client can reasonably be
expected to recover from an exception, make it a checked exception. If
a client cannot do anything to recover from the exception, make it an
unchecked exception
The heart of “what type of exception to throw” is semantic (to some degree) and the above quote provides and excellent guideline (hence, I am still blown away by the notion that C# got rid of checked exceptions – particularly as Liskov argues for their usefulness).
The rest then becomes logical: to which exceptions does the compiler expect me to respond, explicitly? The ones from which you expect client to recover.
I think that checked exceptions are a good reminder for the developer that uses an external library that things can go wrong with the code from that library in exceptional situations.
Read more about checked vs unchecked exceptions here
I just want to add some reasoning for not using checked exceptions at all. This is not a full answer, but I feel it does answer part of your question, and complements many other answers.
Whenever checked exceptions are involved, there’s a
throws CheckedException somewhere in a method signature (
CheckedException could be any checked exception). A signature does NOT throw an Exception, throwing Exceptions is an aspect of implementation. Interfaces, method signatures, parent classes, all these things should NOT depend on their implementations. The usage of checked Exceptions here (actually the fact that you have to declare the
throws in the method signature) is binding your higher-level interfaces with your implementations of these interfaces.
Let me show you an example.
Let’s have a nice and clean interface like this
public interface IFoo { public void foo(); }
Now we can write many implementations of method
foo(), like these
public class Foo implements IFoo { @Override public void foo() { System.out.println("I don't throw and exception"); } }
Class Foo is perfectly fine. Now let’s make a first attempt at class Bar
public class Bar implements IFoo { @Override public void foo() { //I'm using InterruptedExcepton because you probably heard about it somewhere. It's a checked exception. Any checked exception will work the same. throw new InterruptedException(); } }
This class Bar won’t compile. As InterruptedException is a checked exception, you must either capture it (with a try-catch inside method foo()) or declare that you’re throwing it (adding
throws InterruptedException to the method signature). As I don’t want to capture this exception here (I want it to propagate upwards so I can properly deal with it somewhere else), let’s alter the signature.
public class Bar implements IFoo { @Override public void foo() throws InterruptedException { throw new InterruptedException(); } }
This class Bar won’t compile either! Bar’s method foo() does NOT override IFoo’s method foo() since their signatures are different. I could remove the @Override annotation, but I want to program against interface IFoo like
IFoo foo; and later on decide on which implementation I want to use, like
foo = new Bar();. If Bar’s method foo() doesn’t override IFoo’s method foo, when I do
foo.foo(); it won’t call Bar’s implementation of foo().
To make Bar’s
public void foo() throws InterruptedException override IFoo’s
public void foo() I MUST add
throws InterruptedException to IFoo’s method signature. This, however, will cause problems with my Foo class, since it’s foo() method’s signature differs from IFoo’s method signature. Furthermore, if I added
throws InterruptedException to Foo’s method foo() I would get another error stating that Foo’s method foo() declares that it throws an InterruptedException yet it never throws an InterruptedException.
As you can see (if I did a decent job at explaining this stuff), the fact that I’m throwing a checked exception like InterruptedException is forcing me to tie my interface IFoo to one of it’s implementations, which in turn causes havoc on IFoo’s other implementations!
This is one big reason why checked exceptions are BAD. In caps.
One solution is to capture the checked exception, wrap it in an unchecked exception and throw the unchecked exception.
Just to point out that if you throw a checked exception in a code and the catch is few levels above, you need to declare the exception in the signature of each method between you and the catch. So, encapsulation is broken because all functions in the path of throw must know about details of that exception.
All of those are checked exceptions. Unchecked exceptions are subclasses of RuntimeException. The decision is not how to handle them, it’s should your code throw them. If you don’t want the compiler telling you that you haven’t handled an exception then you use an unchecked (subclass of RuntimeException) exception. Those should be saved for situations that you can’t recover from, like out of memory errors and the like.
If anybody cares for yet another proof to dislike checked exceptions, see the first few paragraphs of the popular JSON library:
“Although this is a checked exception, it is rarely recoverable. Most callers should simply wrap this exception in an unchecked exception and rethrow: “
So why in the world would anyone make developers keep checking the exception, if we should “simply wrap it” instead? lol | https://exceptionshub.com/java-checked-vs-unchecked-exception-explanation.html | CC-MAIN-2022-05 | refinedweb | 3,665 | 55.03 |
How to fix Yup cannot read property object of undefined
If you’re using TypeScript with Yup, you might be running into this error:
TypeError: Cannot read property 'object' of undefined
And this is what your code may look like
import yup from 'yup'; const schema = yup.object().shape({});
To fix the error message above, make sure you have types for Yup installed.
npm i -D @types/yup
The next thing to update is how you import Yup into your TypeScript file
import * as yup from 'yup';
That’s it!
I like to tweet about JavaScript and post helpful code snippets. Follow me there if you would like some too! | https://linguinecode.com/post/how-to-fix-yup-cannot-read-property-object-of-undefined | CC-MAIN-2022-21 | refinedweb | 110 | 75.54 |
. The difference between javabean and java custom tags was that, though both made use of java classes,tags can be used by non-programmers also withoutknowledge of Java programming, just as they would use html tags.( From a programmer’s perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )
also read:
Back in 1998, a Web-Server Technology , known as ColdFusion , created by Allaire of Allaire Corporation, was very much in demand!. It was a purely tag-based language, using which page-authors can turn into programmers overnight. The tags were so powerful and simple to use! There is a separate lesson on using ColdFusion for typical web-based database opeartions, elsewhere in this edition, just to indicate the source of inspiration of the tag library idea, of the JSTL. To this day, ColdFusion is unbeatable, in its power,speed, ease of use and productivity. However, among the various web-server technologies ( namely ASP, Servlets, JSP,Perl,PHP , ColdFusion & ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no longer popular in Indian environment, though it is said to be very much in vogue still, in US!
MacroMedia of ‘Flash fame’ purchased ColdFusion .There was even a tutorial on MacroMediaColdFusionExprsess in DeveloperIQ., a few months back.It is interesting to make a comparison of the CF tags approach and the JSTL approach., especially , in DataBaseoperations.Readers are requested to read the lesson on ColdFusion,in this edition, after covering sql tags in JSTL , in the fourth part of this tutorial.
To resume,the release of the TagLibrary API, triggereda lot ofactivity and hundreds of tags were introduced by the java community, some of them ‘open’ and a few ‘proprietary’.This led to a lot of confusion in code maintenance, because knowledge of Java was no longer sufficient to understand and interpret a given jsp page using non-standard tags .The JCP had unwittinglyintroduced elements of confusion by the JSP-Custom-Tag specification. To correct this problem, Sun and JCP, initiatedthe JSP-Standard Tag Library (JSTL) project.Though there are a number of popular and powerful tag-libraries, it is always better for j2ee coders toadopt the JCP standard because, it is likely to be merged into the core specification of Java langauage itself , in future. (That yardstick may be valid for all creations, in Java world. Splintering of the Java platform due to’ hyper-active creativity’without the corresponding discipline to get it through a standards body ,is the greatest threat, looming large in the Java-horizon. Too frequent revisions and additions, that too without caring for backward compatibility,are not conducive to programmer productivity and the net result is that programmers spend ,in learning new twists in grammar,their precious time which should have been spent more usefully in applying that grammar in solving business-logic problems and acquiring proficiency in the chosen application-domain. While, tag library is sometimes very elegant and simple to use, it defeats the very purpose if the tags are not standard tags and if there is proliferation of non-standard tags.It is for this reason that JSTL merits our serious study and adoption. JSTL is a quite recentdevelopment. It was only in 2003, that the official version 1.1 was released and now incorporated intoJSP-2.
According to the latest position, the JCP is suggesting that a JSP page should be completely free from any trace of Java code!So, programmers who were writing their JSP using Javabeans and scriptlets , may not be able to carry on in their old style as,to prevent programmers from
introducing scripting sections in their pages, there is aprovisionfor turning off scriptlets altogether from a jsp page. If that happens ,all our knowledge of Java coding will be of little use in creating a jsp page, though such knowledge may be useful in creating beans and other types of java programs. It is thus very important forJ2EE students, to understand the trend and get to know the techniques, advantages and limitations oftag libraries…In a way, a study of JSTL is almost synonymouswith a study of the latest version of JSP (ie) JSP2.0 .
Without an introductory demo for each of these types, it may be difficult to appreciate the significance of the above lines. So we will now give simplest illustration. [It is presumed that readers are conversant with basic Servlets & JSP techniques and executing them in Tomcat environment. In case of any difficulty, they can refer to back issues of this magazine ( from Oct-2003onwards) and gain access to a number of lessons for illustrations.] Servlets are full-fledged java-classes and so are very powerful. But, when we want to create a dynamically-generated web-page using servlets, it becomes difficult and clumsy. Let us consider a very simple example.
The user fills up text in html form with his name and submits the form,to the servlet. The servlet reads the data , appends a greeting and sends it back to the user. We begin with a simple html form;
//greeting.htm
<html><body> <formmethod=post <inputtype= <inputtype=submit> </form> </body> </html>
(relevant section of greeting.javaservlet)
//greeting.java( code-snippet only) public void doPost(HttpServletRequestreq, HttpServletResponseresp) throwsServletException,IOException { resp.setContentType("text/html"); PrintWriterout = resp.getWriter(); //------------------------------- Strings = req.getParameter("text1"); out.println("<html><bodybgcolor=yellow>"); out.println("wewelcome"+",<br>"); out.println (s); out.println("</body> </html>"); }
It will be noticed thatwe have to write so many ‘out.println’ statements. This makes the page unreadable.( If String-buffer is used , we can do it with just a single out.println , butforming the correct string may pose difficulties).
It is to solve this problemthat JSP was developed five years back(1999).While a servletinterposes HTMLin java code, JSP interposes java-code in HTML, as some authors correctly observe..( in this case, we have to modify the action field in html form, so that it refers to the following greeting1.jsp).
Student readers will know about ‘delimiters’( <%).in ASP. This is the same as inJSP. Only the syntax is slightly different.In JSP parlance, the code within delimiters is known as ‘scriptlet‘.( see greeting1.jsp)
———————————————–
//greeting1.jsp
<html> <bodybgcolor=yellow> <% Strings = request.getParameter("text1"); out.println("we welcome"+<br>); out.println(s); %> </body> </html>
Some coders prefer to use expressions. What is an ‘expression’? It is a method of sustituting request-time values in html page. ( see greeting2.jsp). Carefully note that there is no semi-colon after (“text1″).
// greeting2.jsp <html> <bodybgcolor=yellow> we welcome <br> <%=request.getParameter("text1")%> </body> </html>
The third variant is to use a javabean to encapsulate the business-logic. Wedevelop a jsp-bean as follows:
//greeter.java packageourbeans; public class greeter { public greeter(){} publicStringgreetme(Strings) { return"we welcome..."+s; } }
This source file is compiled and the class-file is copied to : ‘e:tomcat5webappsrootWEB-INFclassesourbeans’ (Carefully note that WEB-INF folder name should be in capital letters).
( Anytime, a new class is placed in Tomcat, we should remember to restart the server).
We can nowwrite our JSP code as follows:
greeting3.jsp
<html> <body> <jsp: <% Strings = request.getParameter ("text1"); Stringr =bean1.greeteme(s); out.println(r); %> </body> </html>
<%@taglibprefix=”c”uri=””%>
The directive says that we are using ‘core’ tags and the prefix will be ‘c’.If we want to assign the value ‘sam’ to a variable ‘a’ and then print it, the JSTL code will be
<c:set <c:out
The Dollar sign & brace will be familiar ground for Perl programmers.In JSTL & JSP-2, it isknown as EL ( Expression Language).
To consider another example,Inservlet & jsp, we write:
String s = request.getParameter("text1");
to collect the input from the user. The same job is done inJSTLby:
<c:
With these brief hints, it should not be difficult to understand the followingJSPpage writtenbyusing JSTL core-tags.
//greeting4.jsp(usesJSTL)
<%@ We welcome<br> <c: </body> </html>
In the previous examples, there was java code in a few lines atleast. But, in theJSTLexample, we find that there are only tags and no javascriptlets. This is the avowed objective of the JSTLinitiative, under the auspices of Java Community Project! Why?This enables, clean separation ofPage author’s role and Logic programmers’ role. Thus maintenance becomes easy.
There are five groups under which the JSTL tags have been organized. They are as follows:
- core
- xml
- sql
- formatting
- functions.
The most difficult part isto set up Tomcatso that it executes JSTL.There are some basic requirements, before we can experiment and study the use of JSTL.All that we have studied in using Tomcat for servlets and JSP may not be sufficient to learn JSTL, because, jstl library is not built into Tomcat5even, as yet. Without hands-on experimention, JSTL could be confusing and strange, because of thefact that it is veryrecent. But in coming months, support will be built into Tomcat and we won’t have to worry about installing the JSTLlibraries inside Tomcat. But, as it is, we have to learn how to set up the necessary development environment..So , how do we go about , placing the JSTL libraries in tomcat?
The best solution is to get JWSDP1.3. This is Java Web Service Development’ Pack.
( Carefully note the version , however!). It is good to start with this because, it contains a lot of valuable software , including the latest and greatest fromJCP, (ie) JSF (Java Server Faces)…. which may soon replace Struts.
We unzipthe jwsdp1.3and installit in C: drive. There are a number of folders like JAXP, JAXR, JAXB,JAX-RPC, JSF,JSTL etc. in the JWSDP pack.
For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we find four sub folders :
- docs
- lib
- samples
- tld(tag library descriptors)
When we look into the ‘lib’ folder, we findtwo jar files:
- standard.jar
- jstl.jar
We should copythese two jar files into:
'e:tomcat5webappsrootWEB-INFlib'
(Remember to restart the Tomcat server). That is all that is required to useJSTL. ! The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are alreadyincluded in the /META-INF folder of the jstl.jar and so will be automatically loaded by Tomcat, when it is restarted. ( we are using tomcat5 & jdk1.4.2) ( the results are notensuredfor other environments.).( however, we adopted the same method in Tomcat4.1 with jdk1.41 and got correct functioning.)
The JSTLfolder contains a sub-folder named ‘tld’.There will be a number of tld files there such as c.tld ( core), x.tld (xml), fmt.tld
Speak Your Mind | http://www.javabeat.net/an-introduction-to-jstl/ | CC-MAIN-2015-11 | refinedweb | 1,775 | 57.77 |
Hey guys,
this is the first GUI program I have been trying to write, I have been getting through it all so far, but once my GUI comes up I click on the button and nothing happens, any help is greatly appreciated, thanks in advance.
import javax.swing.*;
import BreezySwing.*;
public class piGUI extends GBFrame{
private JLabel iterationLabel;
private JLabel numberLabel;
private DoubleField iterationField;
private DoubleField numberField;
private JButton iterationButton;
private double iteration;
public piGUI(){
iterationLabel = addLabel ("Iterations" ,1,1,1,1);
numberLabel = addLabel ("Pi" ,1,2,1,1);
iterationField = addDoubleField (0.0 ,2,1,1,1);
numberField = addDoubleField (0.0 ,2,2,1,1);
iterationButton = addButton (">>>>>" ,3,1,1,1);}
public void buttonClicked (JButton buttonObj){
double answer;
double extent = 0.0;
answer = (numberField.getNumber());
extent = (numberField.getNumber());
for (int i=1; i < extent; i++) {
if(answer % 2 == 1)
{
extent=extent-1.0/(2*i-1);
answer=answer+1;
}
else
{
extent=extent+1.0/(2*i-1);
answer=answer+1;
answer = answer * 4;
}
}
numberField.setNumber(answer);
}
public static void main (String[] args){
piGUI theGUI = new piGUI();
theGUI.setSize (250, 100);
theGUI.setVisible(true);
}
}
Please post code using the CODE tags (see my sig) to retain formatting so it is readable.
OK... firstly, I seriously recommend that you don't use something like BreezySwing until you've learned how to code a GUI using the standard library, so you know how it all hangs together behind the scenes. See Creating a GUI with Swing.
That said, when your GUI is displayed, both double fields are 0.0, so when you press the button, the button handler code sees it's zero and will just skip the loop - as you have coded it to do.
Also, in that handler, you put the content of 'numberField' into both variables 'answer' and 'extent', ignoring 'iterationField' - are you sure you wanted to do that? I would suggest that 'numberField' is possibly the least informative name you could give to a numeric field, and this has probably contributed to your confusion. Give it a meaningful name - perhaps to do with its label (e.g. 'piField').
Also, you are using a double (floating point) number for the number of iterations - an integer concept. Does it make sense to input a fraction of an iteration?
Also, you should use the Java Naming Convention, or people might not read your code at all. At the very least, class names should begin with uppercase letters and method & variable names should begin with lowercase letters.
Before software can be reusable it first has to be usable...
R. Johnson
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
View Tag Cloud
Forum Rules | http://forums.codeguru.com/showthread.php?508786-trouble-with-GUI&mode=hybrid | CC-MAIN-2015-48 | refinedweb | 459 | 57.16 |
#include <qthreadstorage.h>
QThreadStorage is a template class that provides per-thread data storage.
Note that due to compiler limitations, QThreadStorage can only store pointers.
The setLocalData() function stores a single thread-specific value for the calling thread. The data can be accessed later using the localData() functions. useful for lazy initializiation.
For example, the following code uses QThreadStorage to store a single cache for each thread that calls the cacheObject() and removeFromCache() functions. The cache is automatically deleted when the calling thread exits (either normally or via termination).
QThreadStorage<QCache<SomeClass> *> caches;
void cacheObject( const QString &key, SomeClass *object )
{
if ( ! caches.hasLocalData() )
caches.setLocalData( new QCache<SomeClass> );
caches.localData()->insert( key, object );
}
void removeFromCache( const QString &key )
{
if ( ! caches.hasLocalData() )
return; // nothing to do
caches.localData()->remove( key );
}
See also Environment Classes and Threading.
Note: The per-thread data stored is not deleted. Any data left in QThreadStorage is leaked. Make sure that all threads using QThreadStorage have exited before deleting the QThreadStorage.
Note: QThreadStorage can only store pointers. This function returns a reference to the pointer that was set by the calling thread. The value of this reference is 0 if no data was set by the calling thread,
Returns a copy of the data that was set by the calling thread.
Note: QThreadStorage can only store pointers. This function returns a pointer to the data that was set by the calling thread. If no data was set by the calling thread, this function returns 0.(). | http://man.linuxmanpages.com/man3/QThreadStorage.3qt.php | crawl-003 | refinedweb | 248 | 51.75 |
bugfix: USE now checks for non-empty file name (reported by Zbigniew Baniewski)
\ A less simple implementation of the blocks wordset. \ Copyright (C) 1995,1996,1997,1998 \ limit block files to 2GB; gforth <0.6.0 erases larger block files on \ 32-bit systems $200000 Value block-limit User block-fid User block-offset ( -- addr ) \ gforth \G User variable containing the number of the first block (default \G since 0.5.0: 0). Block files created with Gforth versions before \G 0.5.0 have the offset 1. If you use these files you can: @code{1 \G offset !}; or add 1 to every block number used; or prepend 1024 \G characters to the file. 0 block-offset ! \ store 1 here fore 0.4.0 compatibility ' block-offset alias offset \ !! eliminate this? : block-cold ( -- ) block-fid off last-block off buffer-struct buffers * %alloc dup block-buffers ! ( addr ) buffer-struct %size buffers * erase ; :noname ( -- ) defers 'cold block-cold ; is 'cold block-cold Defer flush-blocks ( -- ) \ gforth : open-blocks ( c-addr u -- ) \ gforth \g Use the file, whose name is given by @i{c-addr u}, as the blocks file. try ( c-addr u ) 2dup open-fpath-file throw rot close-file throw 2dup file-status throw bin open-file throw >r 2drop r> endtry-iferror ( c-addr u ior ) >r 2dup file-status nip 0= r> and throw \ does it really not exist? r/w bin create-file throw then block-fid @ IF flush-blocks block-fid @ close-file throw THEN block-fid ! ; : use ( "file" -- ) \ gforth \g Use @i{file} as the blocks file. name name-too-short?}. dup block-limit u>= -35 and throw offset @ - chars/block chars um* get-block-fid reposition-file throw ; : update ( -- ) \ block \G Mark the state of the current block buffer as assigned-dirty. last-block @ ?dup IF buffer-dirty on THEN ; : save-buffer ( buffer -- ) \ gforth >r r@ buffer-dirty @ if r@ buffer-block @ block-position r@ block-buffer chars/block r@ buffer-fid @ write-file throw r@ buffer-fid @ flush-file throw r@ buffer-dirty off endif rdrop ; : empty-buffer ( buffer -- ) \ gforth dup buffer-block on buffer-dirty off ; : save-buffers ( -- ) \ block \G Transfer the contents of each @code{update}d block buffer to \G mass storage, then mark all block buffers as assigned-clean. (), read \G the block into the block buffer and return its start address, \G @i{a-addr}. dup offset @ u< ) ; [IFDEF] current-input :noname 2 <> -12 and throw >in ! blk ! ; \ restore-input :noname blk @ >in @ 2 ; \ save-input :noname 2 ; \ source-id "*a block*" :noname 1 blk +! 1 loadline +! >in off true ; \ refill :noname blk @ block chars/block ; \ source Create block-input A, A, A, A, A, : load ( i*x u -- j*x ) \ block \g Text-interpret block @i{u}. Block 0 cannot be @code{load}ed. dup 0= -35 and throw block-input 0 new-tib dup loadline ! blk ! s" * a block*" loadfilename 2! ['] interpret catch pop-file throw ; [ELSE] : (source) ( -- c-addr u ) blk @ ?dup IF block chars/block ELSE tib #tib @ THEN ; ' (source) IS source ( -- c-addr u ) \ core \G @i{c-addr} is the address of the input buffer and @i{u} is the \G number of characters in it. : load ( i*x u -- j*x ) \ block \g Text-interpret block @i{u}. Block 0 cannot be @code{load}ed. dup 0= -35 and throw s" * a block*" loadfilename>r push-file dup loadline ! blk ! >in off ['] interpret catch pop-file r>loadfilename throw ; [THEN] :. \ environment- environment true constant block-ext set-current : bye ( -- ) \ tools-ext \G Return control to the host operating system (if any). ['] flush catch drop bye ; | http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/blocks.fs?f=h;only_with_tag=MAIN;rev=1.58 | CC-MAIN-2020-24 | refinedweb | 606 | 72.26 |
Create a new working directory, then make a copy of the example files for the tutorial, like so:
cd ~ cp -r /project/scv/examples/BuildingSoftware/src tut
This lesson plan covers the (very) basics of building small projects from C or Fortran source code using the GNU compiler, and automating this process using GNU Make. It is intended for scientists venturing into scientific programming, to help ease the frustrations that typically come up when starting to work in compiled programming languages.
The material is not unique, and borrows heavily from the references listed at the end of the lesson. Comments are always welcome!
Let's start with a simple example: building a "hello world" program with the GNU compiler.
Our C program (
hello.c) looks like this:
#include <stdio.h> main() { (void) printf("Hello World\n"); return (0); }
To build a working executable from this file in the simplest way possible, run:
$ gcc hello.c
The Fortran program (
hello.f90) is as following:
program main print *, "Hello world" end program main
$ gfortran hello.f90
The
gcc/gfortran command creates an executable with a default name of
a.out. Running this command prints the familiar message:
$ a.out Hello World
More happened here than meets the eye. In fact, the command
gcc wraps up 4 steps of the build process:
In this step,
gcc calls preprocessing program
cpp to interpret preprocessor directives and modify the source code accordingly.
Some common directives are:
#include
#include <stdio.h>
#define
#ifdef ... #end
conditional compilation, the code block is included only if a certain macro is defined, e.g:
#ifdef TEST_CASE a=1; b=0; c=0; #endif
We could perform just this step of the build process like so:
cpp hello.c hello.i
Examining the output file (
vim hello.i) shows that the long and messy
stdio.h header has been appended to our simple code. You may also like to explore adding
#define statements, or conditional code blocks.
In this step, the (modified) source code is translated from the C programming language into assembly code.
Assembly code is a low-level programming language with commands that correspond to machine instructions for a particular type of hardware. It is still just plain text --- you can read assembly and write it too if you so desire.
To perform just the compilation step of the build process, we would run:
gcc -S -c hello.i -o hello.s
Examining the output file (
vim hello.s) shows that processor-specific instructions needed to run our program on this specific system. Interestingly, for such a simple program as ours, the assembly code is actually shorter than the preprocesses source code (though not the original source code).
Assembly code is then translated into object code (more). This is a binary representation of the actions your computer needs to take to run your program. It is no longer human-readable, but it can be understood by your processor.
To perform just this step of the build process, we would run:
gcc -c hello.s -o hello.o
You can try to view this object file like we did the other intermediate steps, but the result will not be terribly useful (
vim hello.o). Your text editor is trying to interpret binary machine language commands as ASCII characters, and (mostly) failing. Perhaps the most interesting result of doing so is that there are intelligable bits --- these are the few variables, etc, that actually are ASCII characters.
Also note that object files are not executables, you can't run them until after the next step.
In the final step,
gcc calls the linker program
ld to combine the object file with any external functions it needs (e.g. library functions or functions from other source files). In our case, this would include
printf from the C standard library.
To perform just this step of the build process, we would run:
gcc hello.o -o hello
Compile and run the following program (
squares.c):
#include <stdio.h> main() { int i; printf("\t Number \t\t Square of Number\n\n"); for (i=0; i<=25; ++i) printf("\t %d \t\t\t %d \n", i, i*i); }
If you have some extra time, try walking through the process step-by-step and inspecting the results.
gcc squares.c -o squares ./squares
For all but the smallest programming projects, it is convenient to break up the source code into multiple files. Typically, these include a main function in one file, and one or more other files containing functions / subroutines called by main(). In addition, a header file is usually used to share custom data types, function prototypes, preprocessor macros, etc.
We will use a simple example program in the
multi_string folder, which consists of:
main.c: The main driver function, which calls a subroutine and exits
WriteMyString.c: a module containing the subroutine called by main
header.h: one function prototype and one macro definition
The easiest way to compile such a program is to include all the required source files at the
gcc command line:
gcc main.c WriteMyString.c -o my_string ./my_string
It is also quite common to separate out the process into two steps:
The reason is that this allows you to reduce compiling time by only recompiling objects that need to be updated. This seems (and is) silly for small projects, but becomes important quickly. We will use this approach later when we discuss automating the build process.
gcc -c WriteMyString.c gcc -c main.c gcc WriteMyString.o main.o -o write ./write
Note that it is not necessary to include the header file on the
gcc command line. This makes sense since we know that the (bundeled) preprocessing step will append any required headers to the source code before it is compiled.
There is one caveat: the preprocessor must be able to find the header files in order to include them. Our example works because
header.h is in the working directory when we run
gcc. We can break it by moving the header to a new subdirectory, like so:
mkdir include mv header.c include gcc main.c WriteMyString.c -o my_string
The above commands give the output error:
main.c:4:20: fatal error: header.h: No such file or directory
We can fix this by specifically telling
gcc where it can find the requisite headers, using the
-I flag:
gcc -I ./include main.c WriteMyString.c -o my_string
This is most often need in the case where you wish to use external libraries installed in non-standard locations. We will explore this case below.
In the folder
multi_fav_num you will find another simple multi-file program. Build this source code to a program named
fav_num using separate compile and link steps. Once you have done this successfully, change the number defined in
other.c and rebuild. You should not have to recompile
main.c to do this.
gcc -c main.c gcc -c other.c gcc main.o other.o -o fav_num ./fav_num vim other.c gcc -c other.c gcc main.o other.o -o fav_num ./fav_num
NOTE: content in this section is (lightly) modified from this site.
A library is a collection of pre-compiled object files that can be linked into your programs via the linker. In simpler terms, they are machine code files that contain functions, etc, you can use in your programs.
A few example functions that come from libraries are:
printf()from the
libc.soshared library
sqrt()from the
libm.soshared library
We will return to these in a moment.
A static library has file extension of
.a (archive file). When your program links a static library, the machine code of external functions used in your program is copied into the executable. At runtime, everything your program needs is wrapped up inside the executable.
A shared library has file extension of ".so" (shared objects). When your program is linked against a shared library, only a small table is created in the executable. At runtime, the exectutable must be able to locate the functions listed in this table. This is done by the operating system - a process known as dynamic linking.
Static libraries certainly seem simpler, but most programs use shared libraries and dynamic linking. There are several reasons why the added complexity is thought to be worth it:
Because of the advantage of dynamic linking, GCC will prefer a shared library to a static library if both are available (by default).
Let's start with an example that uses the
sqrt() function from the math library:
#include <stdio.h> #include <math.h> void main() { int i; printf("\t Number \t\t Square Root of Number\n\n"); for (i=0; i<=360; ++i) printf("\t %d \t\t\t %d \n", i, sqrt((double) i)); }
Notice the function
sqrt, which we use, but do not define. The (machine) code for this function is stored in
libm.so, and the function definition is stored in the header file
math.h.
To build successfully, we must:
#includethe header file for the external library
Let's go ahead and build the program. To compile and link this in separate steps, we would run:
gcc -c roots.c gcc roots.o -lm -o roots
The first command preprocesses
roots.c, appending the header files, and then translates it to object code. This step does need to find the header file, but it does not yet require the library.
The second command links all of the object code into the executable. It does not need to find the header file (it is already compiled into
roots.o) but it does need to find the library file.
Library files are included using the
-l flag. Thier names are given excluding the
lib prefix and exluding the
.so suffix.
Just as we did above, we can combine the build steps into a single command:
gcc roots.c -lm -o roots
IMPORTANT Because we are using shared libraries, the linker must be able to find the linked libraries at runtime, otherwise the program will fail. You can check the libraries required by a program, and whether they are being found correctly or not using the
ldd command. For out roots program, we get the following
ldd roots
linux-vdso.so.1 => (0x00007fff8bb8a000) libm.so.6 => /lib64/libm.so.6 (0x00007ffc69550000) libc.so.6 => /lib64/libc.so.6 (0x00007ffc691bc000) /lib64/ld-linux-x86-64.so.2 (0x00007ffc69801000)
Which shows that our executable requires a few basic system libraries as well as the math library we explicitly included, and that all of these dependencies are found by the linker.
Before moving on, let's take a few minutes to break this build process. Try the following and read the error messages carefully. These are your hints to fixing a broken build process.
#include <math.h>from
roots.c
-lmfrom the linking step
The preprocessor will search some default paths for included header files. Before we go down the rabbit hole, it is important to note that you do not have to do this for a typical build, but the commands may prove useful when you are trying to work out why something fails to build.
We can run the following commands to show the preprocessor search path and look for files in therein:
cpp -Wp,-v
Which has the following output:
ignoring nonexistent directory "/usr/local/include" ignoring nonexistent directory "/usr/lib/gcc/x86_64-redhat-linux/4.4.7/include-fixed" ignoring nonexistent directory "/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../x86_64-redhat-linux/include" #include "..." search starts here: #include <...> search starts here: /usr/lib/gcc/x86_64-redhat-linux/4.4.7/include /usr/include End of search list. ^C
The last few lines show the paths where GCC will search for header files by default. We can then search these include paths for the file we want,
math.h like so:
find /usr/include /usr/lib/gcc/x86_64-redhat-linux/4.4.7/include -name math.h
Which has the following output:
/usr/include/FL/math.h /usr/include/c++/4.4.4/tr1/math.h /usr/include/math.h
If we are really curious, we could open the header and see what it contains, but this is rarely necessary.
The linker will search some default paths for included library files. Again, it is important to note that you do not have to do this for a typical build, but the commands may prove useful when you are trying to work out why something fails to build.
To look for the library, we can run the following command to get a list of all library files the linker is aware of, then search that list for the math library we need:
ldconfig -p ldconfig -p | grep libm.so
The latter command gives the output:
libm.so.6 (libc6,x86-64, OS ABI: Linux 2.6.18) => /lib64/libm.so.6 libm.so.6 (libc6, hwcap: 0x0028000000000000, OS ABI: Linux 2.6.18) => /lib/i686/nosegneg/libm.so.6 libm.so.6 (libc6, OS ABI: Linux 2.6.18) => /lib/libm.so.6 libm.so (libc6,x86-64, OS ABI: Linux 2.6.18) => /usr/lib64/libm.so libm.so (libc6, OS ABI: Linux 2.6.18) => /usr/lib/libm.so
We certainly have the math library available. In fact, there are a few versions of this library known to the linker. Thankfully, we can let the linker sort out which one to use.
We might also want to peek inside a library file (or any object code for that matter) to see what functions and variables are defined within. We can list all the names, then search for the one we care about, like so:
nm /lib/libm.so.6 nm /lib/libm.so.6 | grep sqrt
The output of this command contains the following line, which shows us that it does indeed include something called
sqrt.
0000000000025990 W sqrt
note: the following command lines build the libctest.so shared library used in the example below:
gcc -Wall -fPIC -c ctest1.c ctest2.c gcc -shared -Wl,-soname,libctest.so -o libctest.so ctest1.o ctest2.o
or
gcc ctest1.c ctest2.c -shared -o libctest.so
end note
Let's switch to a new bit of example code, called
use_ctest.c that makes use of a (very simple) custom library in the
ctest directory:
#include <stdio.h> #include "ctest.h" int main(){ int x; int y; int z; ctest1(&x); ctest2(&y); z = (x / y); printf("%d / %d = %d\n", x, y, z); return 0; }
Trying to compile this fails with an error:
gcc -c use_ctest.c use_ctest.c:2:19: error: ctest.h: No such file or directory
As the error message indicates, the problem here is that an included header file is not found by the preprocessor. We can use the
-I flag to fix this problem:
gcc -I ctest_dir/include -c use_ctest.c
When we try to link the program to create an executable, we know we need to explicitly add the library with the
-l flag, but in this case we still get an error:
gcc use_ctest.o -lctest -o use_ctest /usr/bin/ld: cannot find -lctest collect2: ld returned 1 exit status
Just like for the header, we need to explicitly specify the path to the library file:
gcc -Lctest_dir/lib use_ctest.o -lctest -o use_ctest
Success, or so it would seem. What happens when we try to run our shiny new executable?
./use_ctest ./use_ctest: error while loading shared libraries: libctest.so: cannot open shared object file: No such file or directory
We can diagnose this problem by checking to see if the dynamic linker is able to gather up all the dependencies at runtime:
ldd use_ctest linux-vdso.so.1 => (0x00007fffd75ff000) libctest.so => not found libc.so.6 => /lib64/libc.so.6 (0x00007f802d21b000) /lib64/ld-linux-x86-64.so.2 (0x00007f802d5dd000)
The output clearly shows that it does not. The problem here is that the dynamic linker will only search the default paths unless we:
Permanently add our custom library to this search path. This option is not covered here - I am assuming that many of you will be working on clusters and other systems where you do not have root permissions.
Specify the location of non-standard libraries using the
LD_LIBRARY_PATH variable.
LD_LIBRARY_PATH contains a colon (:) separated list of directories where the dynamic linker should look for shared libraries. The linker will search these directories before the default system paths. You can define the value of
LD_LIBRARY_PATH for a particular command only by preceeding the command with the definintion, like so:
LD_LIBRARY_PATH=ctest_dir/lib:$LD_LIBRARY_PATH ./use_ctest
Or define it for your whole shell as an environment variable:
export LD_LIBRARY_PATH=./ctest_dir/lib:$LD_LIBRARY_PATH ./use_ctest
Hard-code the location of non-standard libraries into the executable. Setting (and forgeting to set)
LD_LIBRARY_PATH all the time can be tiresome. An alternative approach is to burn the location of the shared libraries into the executable as an
RPATH or
RUNPATH. This is done by adding some additional flags for the linker, like so:
gcc use_ctest.o -Lctest_dir/lib -lctest -Wl,-rpath=./ctest_dir/lib -o use_ctest
We can confirm that this worked by running the program (resetting
LD_LIBRARY_PATH first if needed), and more explicitly, by examining the executable directly:
./use_ctest readelf -d use_ctest
Without using your history, try to recompile and run the use_ctest program. For an additional challenge, try to do so using RUNPATH to hardcode the location of the shared library.
The manual build process we used above can become quite tedious for all but the smallest projects. There are many ways that we might automate this process. The simplest would be to write a shell script that runs the build commands each time we invoke it. Let's take the simple
hello.c program as a test case:
#!/bin/bash gcc -c hello.c gcc hello.o -o hello
This works fine for small projects, but for large multi-file projects, we would have to compile all the sources every time we change any of the sources.
The Make utility provides a useful way around this problem. The solution is that we (the programmer) write a special script that defines all the dependencies between source files, edit one or more files in our project, then invoke Make to recompile only those files that are affected by any changes.
GNU Make is a mini-programming language unto itself. Once a Makefile is prepared, a multi-file program can be built by executing one single command,
The commandThe command
make
makelooks for a file named
Makefileor
makefilein the same directory by default. Other file names can be specified by the option
-f:
make -f filename
For the
hello program, a Makefile might look like this:
hello: hello.o gcc hello.o -o hello hello.o: hello.c gcc -c hello.c clean: rm hello hello.o
The syntax here is
target: prerequisite_1 prerequisite_2 etc. The command block that follows will be executed to generate the target if any of the prerequisites have been modified. The command lines always start with a tab key (It does not work to start with spaces). The first (top) target will be built by default, or you can specify a specific target to build following the
make command. When we run
make for the first time, the computer will take the following actions:
hello.
hellois up-to-date.
hellodoes not exist, so it is out-of-date and will have to be built
hello.ois up-to-date.
hello.odoes not exist, so it is out-of-date and will have to be built.
hello.cis not a target, so there is nothing left to check. The command
gcc -c hello.cwill be run to build
hello.o
hello.ois up to date, so
makebuilds the next target
helloby running the command
gcc hello.o -o hello
A target is considered out-of-date if:
Note that the command under the
clean target is not executed by
make, because it is neither the first target nor an prerequisite of any other target. To bring this target up, we need to specify the target name:
make clean
This will remove the executable and the
.o files, which is necessary before rebuilding the program. Notice that if all targets are up-to-date,
make does not recompile anything.
Let's look at an example for our first multi-file program:
write: main.o WriteMyString.o gcc main.o WriteMyString.o -o write main.o: main.c header.h gcc -c main.c WriteMyString.o: WriteMyString.c gcc -c WriteMyString.c clean: rm write *.o
If it is the first build,
make builds the targets in the following order:
main.o,
WriteMyString.o and
write. This compiles all source codes and links object files to build the executable. If it is not the first build,
make will only build the targets whose prerequisite has been modified since last
make. This feature makes it efficient for building a program with many source files. For example, if
WriteMyString.c is modified, only
WriteMyString.c is recompiled, while
main.c is not. If
main.c or
header.h is modified, only
main.c is recompiled, while
WriteMyString.c is not. In either case, the
write target will be built, since either
main.o or
WriteMyString.o is updated.
By default,
make prints on the screen all the commands that it executes. To suppress the print, add an
@ before the commands, or turn on the silent mode with the option
-s:
make -s
Starting from the template below (or using our previous Makefile), see if you can write your own makefile for the
multi_fav_num program:
fav: _____ _____ gcc _____ ______ -o fav main.o: _____ _____ gcc ___ _____ other.o: _____ _____ _________________ clean: rm _____ _____
A Makefile could be very compilcated in a practical program with many source files. It is important to write a Makefile in good logic. The text in the Makefile should be as simple and clear as possbile. To this end, useful features of Makrefile are introduced in this section.
You may have noticed that there are many duplications of the same file name or command name in our previous Makefiles. It is more convinient to use varialbes. Again, take our first multi-file program for example. The Makefile can be rewitten as following,
CC=gcc OBJ=main.o WriteMyString.o EXE=write $(EXE): $(OBJ) $(CC) $(OBJ) -o $(EXE) main.o: main.c header.h $(CC) -c main.c WriteMyString.o: WriteMyString.c $(CC) -c WriteMyString.c clean: rm $(EXE) *.o
Here we have defined the varialbes
CC for the compiler,
OBJ for object files and
EXE for the executable file. If we want to change the compiler or the file names, we only modify the corresponding variables at one place, but do not need to modify all related places in the Makefile.
$(EXE): $(OBJ) $(CC) $^ -o $@ main.o: main.c header.h $(CC) -c $< WriteMyString.o: WriteMyString.c $(CC) -c $<
Here we have used the following automatic variables:
$@--- the name of the current target
$^--- the names of all the prerequisites
$<--- the name of the first prerequisite
These automatic variables automatically take the names of current target or prerequisites, no matter what values are assigned to them.
We can notice that the
main.o and
WriteMyString.o targets are built by the same command. Is there a way to combine the two duplicated commands into one so as to compile all source code files by one command line? Yes, it can be done with an implicit pattern rule:
%.o: %.c $(CC) -c $< main.o: header.h
Here
% stands for the same thing in the prerequisites as it does in the target. In this example, any
.o target has a corresponding
.c file as an implied prerequisite. If a target (e.g.
main.o) needs additional prerequisites (e.g.
header.h), write an actionless rule with those prerequisites. We can imagine that applying this impilict rule should significantly simpify the Makefile when there are a large number of (say hundreds of) source files.
If there are many varialbes to be defined, it is convinient to write the definition of all variables in another file, and then include the file in Makefile:
include ./variables
The content of the file
variables is as following:
CC=gcc OBJ=main.o WriteMyString.o EXE=write
In most cases, the target name is a file name. But there are exceptions, such as the
clean target in this example. The
rm command will not create any file named clean. What if there exists a file named clean in this directory? Let's do an experiment.
TheThe
touch clean make clean make: `clean' is up to date.
cleantarget does not work properly. Since it has no prerequisite,
cleanwill always be considered up-to-date, and thus nothing will be done. To solve this issue, we can declare the target to be phony by making it a prerequisite of the special target
.PHONYas follows:
A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed.A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed.
.PHONY: clean
Finally, we end up with an efficient Makefile:
include ./variables .PHONY: clean $(EXE): $(OBJ) $(CC) $^ -o $@ %.o: %.c $(CC) -c $< main.o: header.h clean: rm $(EXE) *.o
multi_fav_numprogram using regular variables, automatic variables, the implicit pattern rule and the phony target. | http://scv.bu.edu/examples/BuildingSoftware/lesson.html | CC-MAIN-2017-47 | refinedweb | 4,276 | 67.04 |
msync - synchronise memory with physical storage
#include <sys/mman.h> int msync(void *addr, size_t len, int flags);
The msync() function writes all modified data to permanent storage locations, if any, in those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes. If no such storage exists, msync() need not have any effect. If requested, the msync() function, starting at addr and continuing for len bytes are locked, and MS_INVALIDATE is specified.
- [EINVAL]
- The value in flags is invalid.
- [EINVAL]
- The value of addr is not a multiple of the page size, {PAGESIZE}.
- [ENOMEM]
- The addresses in the range starting at addr and continuing for len bytes are outside the range allowed for the address space of a process or specify one or more pages that are not mapped.
None..
The second form of [EINVAL] above is marked EX because it is defined as an optional error in the POSIX Realtime Extension.
None.
mmap(), sysconf(), <sys/mman.h>. | http://www.opengroup.org/onlinepubs/007908799/xsh/msync.html | crawl-002 | refinedweb | 170 | 61.36 |
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Testing the Spinner9:11 with Ben Deitch
In this video we'll see how to use 'onData' to match with Views that aren't shown!
Important Imports
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.core.AllOf.allOf;
Related Links
- 0:00
We've just finished testing our editText with Espresso, and
- 0:03
now it's time that we move on to testing our spinner.
- 0:08
Let's start in the Arrange section,
- 0:10
by copying over the given color variable from MainActivity test.
- 0:26
To find the right spinner item to click we'll be using the with text a few so
- 0:31
let's create a new string variable named spinner item text.
- 0:39
And set it equal to the string Green.
- 0:46
In the act section, we need to start by clicking on our spinner.
- 0:49
Let's type onView(withId( R.id.colorspinner),
- 0:56
and then, .perform, and for
- 1:00
the view action, let's pass in click.
- 1:09
Now that we can see all the items in the spinner,
- 1:11
we need to click on the one that says Green.
- 1:15
Lets use control or command D to duplicate this line and
- 1:18
then replace the withId view matcher with the withText view matcher.
- 1:27
And instead of passing in an ID, let's pass in our spinnerItemText variable.
- 1:33
At this point if we run the test again.
- 1:45
We can see that we're successfully changing the background color to green.
- 1:50
Nice.
- 1:51
But before we move on to asserting, we need to talk about an edge case.
- 1:56
What if we had a spinner with 100 items and we wanted to click on the 98th item.
- 2:03
Well, the spinner only shows so many items at a time.
- 2:07
So if we try to click on the 98th item, it's not going to be there.
- 2:12
And we'll get an error.
- 2:14
To fix this,
- 2:15
Espresso gives us the onData method, which we use to replace the onView method.
- 2:21
OnView only searches through the view hierarchy, but
- 2:25
onData searches through everything.
- 2:28
So if you want to click on that 98th item, onData is the way to go.
- 2:32
Let's refactor our spinnerItem click to use onData instead.
- 2:41
Then let's copy in a few other imports we'll be needing from the teachers'
- 2:45
notes below.
- 2:47
And paste them up here in the import section.
- 2:53
Next we need to provide an object matcher to match the object we're trying to click.
- 2:59
So get rid of what's inside our onData method now.
- 3:05
Because instead of a view matcher, we need to be providing an object matcher.
- 3:09
So inside the parentheses.
- 3:11
Let's first use the all of matcher.
- 3:17
The all of matcher takes in other matchers as parameters and if all
- 3:23
of those other matchers report a match the all of matcher will report a match too.
- 3:30
For the first parameter of all of method,
- 3:35
lets pass on (is(instance0f(String.class).
- 3:41
We don't want to try and
- 3:43
match our spinner item text to something that isn't a string, then for
- 3:49
the second matcher parameter lets pass in is(spinner item text).
- 3:56
Now it will search through the data in our app looking for
- 4:00
a string equal to our spinner item text and
- 4:04
when it finds it, it will find the associated view and perform a click.
- 4:11
Let's run our test again to make sure we're still changing the background color.
- 4:24
Perfect.
- 4:25
Moving onto the assert section we need to assert
- 4:28
that the background color of the app is equal to the given color.
- 4:33
Let's grab the linear layout by using the withIdViewMatcher.
- 4:40
OnView (withId of (R.Id.LinearLayout).
- 4:49
Then since were asserting we need to add the check method, and now we just need
- 4:55
to matcher to check that the background of our view matches the given color.
- 5:02
Unfortunately there isn't a matcher for this.
- 5:05
So we'll just have to make our own.
- 5:08
Let's add a line above this one and declare a new bounded matcher variable.
- 5:14
Named background color matcher.
- 5:23
And let's set it equal to new bounded matcher.
- 5:29
Bounded matchers give us a way to match only on objects of a given class.
- 5:34
But autocomplete didn't fill this part in for us.
- 5:38
So first, in the matchesSafely method, let's replace object item with
- 5:44
(LinearLayout linearLayout).
- 5:51
Then between BoundedMatcher and the parentheses, let's add angle brackets and
- 5:57
inside lets type view on the linear layout.
- 6:05
And import view.
- 6:08
This tells our matcher to only be looking at views and
- 6:12
then to only match on linear layouts.
- 6:16
To finish off the errors,
- 6:18
we just need to provide the class we're looking for as a parameter.
- 6:23
Linearlayout.class and add a semicolon.
- 6:29
Finally we just need to return whether or
- 6:32
not we have a match in the matchesSafely method.
- 6:35
To check if we have a match,
- 6:37
let's start by copying over the actual color variable from MainActivityTest.
- 6:46
And pasting it into our matchesSafely method.
- 6:53
Then let's delete Activity to leave our linear layout parameter,
- 7:01
And let's finish up by returning the outcome of givenColor == actualColor.
- 7:10
The describeTo method is what we'll see in an error message
- 7:13
if something doesn't match.
- 7:15
And while we don't have to fill it in, it's quick and it doesn't hurt.
- 7:19
Let's type description.appendText and
- 7:25
then for the text let's pass in
- 7:29
background color should equal: and
- 7:35
then outside of the quotes.
- 7:39
Plus given color.
- 7:42
Semi colon.
- 7:46
All right.
- 7:47
We finally finished our custom matcher all that's left is to use it.
- 7:52
Inside the check method.
- 7:53
Let's use the matches view assertion.
- 7:55
And pass in our background color matcher.
- 8:03
Then let's use Alt+enter to fix this warning.
- 8:06
And it looks like Android Studio just wanted us to specify the types
- 8:11
over here as well.
- 8:14
Okay moment of truth.
- 8:17
Let's run the test and see what happens.
- 8:30
All right.
- 8:32
You're really getting good at this stuff.
- 8:33
Now, let's comment out the act lines.
- 8:40
And if we run the test again we should be able to see our description.
- 8:54
There it is.
- 8:55
Background color should equal about negative seventeen million.
- 9:01
AKA color dark green.
- 9:02
Now let's un-comment the act section and
- 9:06
then let's conquer our final foe and the next video. | https://teamtreehouse.com/library/testing-in-android/ui-testing-with-espresso/testing-the-spinner | CC-MAIN-2019-43 | refinedweb | 1,297 | 83.36 |
About This Document
We describe ABM++, a software framework used to implement distributed agent based models
on Linux clusters. This document is included with the ABM++ source distribution, which is
available under the GPL license and a virtual appliance
configured to provide a convenient
development and test environment for the ABM++ framework and MPI development in general.
The first sections of the document provide background on the framework, and are followed by an
example of how to implement a dis
tributed ABM within the framework.
The second section of the document provide details on a virtual machine that we have primarily
configured to support parallel C++ development, debugging, and profiling. Our intention is to
provide a user friendly, ready
to go environment for exploration and extension of the ABM++
framework as well as parallel application development with MPI in general. Within this
configured appliance the ABM++ framework has been setup as a fully functioning project
example within the p
opular Eclipse IDE. The initial release of this appliance is based on the
Ubuntu 9.10 release with OpenMPI and with the Eclipse CDT/PTP IDE. With the current
release version, this appliance is usable as VMWare virtual machine that can be started with the
freely available VMWare Player or hosted within one of WMWare’s server options. Full details
on the environment are detailed below.
Introduction
The ABM++ software framework allows the developer to implement agent based models using
C++ that are to b distrib
uted ex
ample.
Tools for Manag
ing Distributed Agents
In a distributed ABM, the agents are distributed across the compute nodes in the cluster. In
most applications some agents might be statically distributed: they never migrate between
distributed compute nodes after the initial dis
tribution. Other agents are dynamically distributed:
they can migrate between compute nodes as the simulation runs. As an example of this, consider
a design for a social network model that simulates interactions between all individual persons in
a city th
e size of Chicago, which has a population of 8.6 million people. The agents in this
design are
individual people, and
locations in the city (households, workplaces, schools, shops, hospitals, etc.). For a
Chicago model there might be 200,000 non
-
househo
ld locations to be simulated, in
addition to ~2,000,000 household locations.
In this example design, location agents will be statically distributed and person agents will be
dynamically distributed. At simulation initialization time all ~2,200,000 locati
ons.
Time Update Tools
Two methods of time update are provided by the framework: time step and discrete event
updates. The provided example framework code includes an example which uses time step
updates.
Syn
chronization tools
Interprocess communications between compute nodes in a distributed ABM often impose
synchronization requirements. In our example social network simulation, person agents migrate
between compute nodes as the person agent randomly move
s disa
dvantage of not scaling well to thousands of compute nodes. A future version of the
framework will include a second synchronization method that utilizes a random pair
-
wise
compute node method that scales well to large cluster configurations.
C++ API to t
he Message Passing Interface (MPI) contain
s a full working implementation of a simple social network
ABM. The agents in the simulation consist of Location agents and Person agents, as described
above. The Location agent software objects are statically distributed, and the Person agents
migrate b
etween them.
It is intended that the code in the Applications directory be used as a stub, or starting point for
actual distributed ABM implementations. In particular, the DSim.[Ch], DistribControl.[Ch],
and ABMEvents.[Ch] files are intended to be modif
ied to meet specific application requirements.
Example Problem statement, to be implemented as a distributed ABM
Create 100 locations of the type described above on each CPU of each available compute node.
Create 1000 people at each location. Randoml
y send all people to other locations every 15
minutes. Assume it takes 15 minutes for a person to reach another location from his current
location.
DSim.C
This file contains the int main() routine for our example simulation application.
It is in mai
n() that several framework globals are instantiated. It is also here that the simulation
end time is set and the simulation is started. One of the globals created is DCtl, instantiated as
shown below starting at line 57 of DSim.C :
//
// Crea
te th
e details of implementation.
DistribControl::Init
Create Distributed Object containers on each compute core. The Distributed Object
containers are used to dereference compute core ids where distributed location objects
reside.
Create a simulation Contr
oller c
ores.C
ontrol: destina
tion location resides on another compute core, the
person
-
agent is serialized into an MPIToolbox message, and the message is sent to its
destination compute core.
DistribControl::Synchronize
This method is called as a result of DCtl having received a mes
sage dist
ributedPerso
n, because only the DistribControl object is aware of the distribution of
Location objects on the cluster compute cores.
ABMEvents.C
TimeStep::Eval
The TimeStep class is used to define what simulation activities are to occur each time
step. The time st
ep interval is defined at line 42, and the time step functionality is
defined in the TimeStep::Eval function which begins at line 45:
1.
Call the DistribControl Synchronize method to ensure that all compute cores
are synchronized to the same simulation time
step.
2.
Call the SocialActivity::MovePeople() method to randomly move person
agents between locations.
3. itse
lf.
Below we describe the configuration of this appliance as well as provide some quick start tips for
running the appliance from a Microsoft Windows or Linux host machine as well as building and
running, debugging and profiling the ABM++ framework from w
ithin the provided Eclipse
project example.
Version 0.1 Configuration
Below is a bullet list outlining the configuration of the version 0.1 appliance release, notes on
decision points and options for the future follow. Version 0.1 might be considered the
personal
version intended for standard laptops and desktop personal computers. Configurations for actual
cluster hardware including dynamic cloud configurations ideally should follow.
-
VMWare virtual machine image
-
32
-
bit Ubuntu 9.10 (
)
-
1536 MB RAM
-
2 CPUS
-
100 GB harddrive
-
1 regular CD and 1 .iso mount
-
OpenMPI 1.4.1 (
-
mpi.org/
)
-
Tau 2.19 (
)
-
Papi 3.7.2 (
)
-
VampirTrace 5.8 (
-
dresden.de/die_tu_dresden/zentrale_einrichtungen/zih/forschung/software_werkzeuge_zu
r_unterstuetzung_von_programmierung_und_optimierung
/vampirtrace/index_html/docu
ment_view?cl=en
)
-
PDToolkit 3.15(
)
-
Sun JDK 1.6.0_15
-
Python 2.6 version of mpi4py 1.2.1
-
Eclipse C/C++ Development T
ools (CDT) 6.0.2 (
)
-
Eclipse Parallel Tools Platform (PTP) 3.0.1 w/
scalable debug manager (SDM)
-
Eclipse Remote System Explorer (RSE) 3.1.1
-
SWIG 1.3.36
-
VNCServer
–
vnc4serve
r 4.1.1
-
NXServer 3.4.0
-
12
-
TODO: python, java dev support in Eclipse
-
TODO: Paraver, JumpShot
-
4 viewers
(
wers/index.htm
)
-
TODO: External source control for project examples in Eclipse
-
TODO: PostgreSQL/PostGIS w/ synthetic population datasets for ABMs
-
TODO: ABM example using synthetic population
-
TODO: Hosting location for the appliance, thoughts on change con
trol, user community
Virtual Machine
There are essentially two choices for creation of a virtual machine which is intended to be easily
shared. One is to create a VMWare virtual machine the other to create a virtual machine based
on Sun’s open source Vi
rtualBox platform. Both are fine options and both will be available as
downloads initially from the MIDAS portal. There are pros and cons to both choices. VMWare
images are cross platform; for this reason the base release is created as a VMWare image an
d
converted to a VBox image. The appliance will be tested in both VMWare Player on both
Windows and Linux hosts, WMWare Server on a linux host, and as VBox images.
We will also likely investigate creation an Amazon EC2 AMI image. This image might be mor
e
production ready, real cluster oriented than the VBox and VMServer personal version(s), ie
version 0.1 which are primarily intended for development of the ABM++ framework. The AMI
image would be made available to the community from Amazon’s AMI collecti
on.
Operating System
It’s not hard to argue that Ubuntu and similar distributions of Linux provide ideal environments
for development of parallel applications especially and obviously for those applications which
are destined to be run on Linux based
cluster configurations. We chose to start with the Ubuntu
9.10 Karmic Koala release for this reason. The ElasticWolf project is another example of a
Fedora based appliance for parallel computing designed specifically for the Amazon EC2 cloud.
“
The
ElasticWulf project
consists of Python command line tools to launch and configure a beowulf
cluster on Amazon EC2. We also include AMI build scripts for
master
and
worker
nodes based on x64
Fedora Core 6 in
stances.
”
32 or 64
-
bit, Memory and Other Hardware Configurations
We chose to create the version 0.1 image as 32
-
bit instead of 64
-
bit. Currently the majority o
f
the laptops used within our organization and many others are still 32 bit. It would not be
difficult to create 64
-
bit versions of the appliance with additional CPUs and RAM for use on
dedicated virtual servers. Since we first intended this appliance t
o be usable on typical laptops
and desktops as an introduction to the ABM++ framework we decided to stick with these modest
configuration options, 32
-
bit, 1536 MB RAM, and 2 CPUs. Some of these are actually
configurable with VMPlayer, VMServer, or VBox.
We also chose to set the harddrive size to
100GB
-
growable; IDE was chosen over the SCSI interface. Down the road this will limit use to
4 drives max, 126GB each in VMPlayer or VM Server but performance is supposed to be better.
By default the network is
setup to share the IP of the host machine using NAT. This will likely
be an issue if trying to connect to the appliance from outside. In VM software this can be easily
changed to a bridged connection which will assign the virtual machine an ip from the h
ost’s
network.
Remote Desktop Options for Server Hosting
We have added VNCServer and NoMachine NX server if the image is to be hosted within a
virtual server vs run within a player like VMPlayer or via VBox GUI. Both remote desktop
methods have been t
ested. One benift of the VBox image is that VBox also supports the RDP
protocol to the running instances, their “vrdp” is supposed to be backwards compatibly with
Microsofts RDP, which if hosted on a server perhaps in headless mode, a Microsoft Windows
d
esktop user could use the existing local remote desktop connection software to utilize the
appliance. Your options for remote desktop with the VM image are VNCServer, No Machine
NX, and if you are using WMWare server there is a firefox plugin which as an
administrator at
least provides useable although a bit ugly and slow, browser based remote desktop option.
It also seems that VBox supports more seamlessly sending shut down signal to the instance
where VMPlayer and Server options I have used so far are
a bit more like pulling the plug, I
could be missing something.
Software Configuration
Compilers and Language Support
We used the Ubuntu included gcc/g++ compilers version 4.4.1, but also added gfortan 4.4.1.
The Sun JDK version 1.6.0_15 was inst
alled. We will likely add to the minimal python install
that comes with ubuntu 9.10 specifically to include mpi4py, NumPy and SciPy and other useful
modules but we have not decided if we will add python development support and Java
development support to
the Eclipse IDE configuration. The mpi4py python bindings to Open
MPI have been installed and tested. MPI for Python really does look promising as does IPython
for interactive parallel programming.
“
MPI for Python
(mpi4py) provides bindings of the
Mess
age Passing Interface
(MPI) standard
for the Python programming language, allowing any Python program to exploit multiple
processors.
This package is constructed on top of the MPI
-
1/MPI
-
2 specification and provides an object
oriented interface which close
ly). You can see what
projects are using IP
ython
here
, or check out the
talks and presentations
we have given about
IPython.
”
IDE
Eclipse is a popular development platform for a number of languages, probably most used for
development of Java applications it also has plug
-
in for a number of other languages including
python, jython,
fortran and most notably a well supported C/C++ plug
-
in. Development of
parallel applications using OpenMPI, OpenMP and others are well supported. Only the OpenMPI
libraries have been installed at this point.
Debugging
The Eclipse PTP plug
-
in provides
the Scalable Debug Manager (SDM) for parallel debugging
and the RSE plug
-
in supports remote execution and debugging as well as integration with
resource managers like PBS and others. So far the RSE and resource manger features have not
been tested but look
promising.
Profiling/Tracing and Viewers
Tau
2.19
Eclipse supports integration with profiling and tracing tools such as the Tuning and Analysis
Utilities (Tau) from
du/research/tau/home.php
. Tau is:
“
TAU Performance System
®
is a portable profiling and tracing toolkit for performance analysis
of parallel programs written in Fortran, C, C++, Java, Python.
TAU (Tuning and Analysis Utilities) is capable of gathering p
erformance information through
instrumentation of functions, methods, basic blocks, and statements. All C++ language features
are supported including templates and namespaces. The API also provides selection of profiling
groups for organizing and controlli
ng instrumentation. The instrumentation can be inserted in the
source code using an automatic instrumentor tool based on the Program Database Toolkit (PDT),
dynamically using DyninstAPI, at runtime in the Java virtual machine, or manually using the
instrum
entation API.
TAU's profile visualization tool, paraprof, provides graphical displays of all the performance
analysis results, in aggregate and single node/context/thread forms. The user can quickly identify
sources of performance bottlenecks in the appli
cation using the graphical interface. In addition,
TAU can generate event traces that can be displayed with the Vampir, Paraver or JumpShot trace
visualization tools.”
Testing of basic mpi profiling options have been successful. Tau was compiled with papi,
vampirtrace, mpi, pthreads and variety of other support libraries. Eclipse integration with all the
features is not there but basic mpi profiling with results stored in a PDToolkit database works.
You can browse the performance database and launch the p
araprof viewer. We have not yet
installed the 3D libraries to support the 3D views and may not as OpenGL via remote desktops
could be a problem, although for the Vbox image with Guest Additions (similar to vmware tools)
I watch it build some kind openGL su
pport. The tau configuration has made it through the tau
validation tests for the following stub makefiles. Only limited testing has been done though:
-
Makefile.taumpi
-
pdt
-
Makefile.tauparam
-
mpi
-
pdt
-
Makefile.taupthread
-
pdt
-
Makefile.taupapi
-
pdt
-
Makefile.
taucallpathdepthlimitpapi
-
mpipthreadcompensatepdt
-
vampirtraceprofile
-
trace
Makefile.taudepthlimitmpi
-
pdt
-
Makefile.taupapi
-
pthread
-
pdt
-
Makefile.tau
-
pdt
-
Makefile.taupapi
-
mpi
-
pdt
-
Makefile.tauphasepapi
-
mpi
-
pdt
Paraver
TODO: Tau can be configured to provi
de conversion tools to tracefile formats for Paraver
.
Jumpshot
-
4
TODO: Tau can be configured to provide conversion tools to the SLOG2 tracefile forma
t used
by Jumpshot
-
4 viewer
.
Data
TODO: It would be useful to have an open source da
tabase such as PostgreSQL w/PostGIS to
house the synthetic population datasets that RTI has developed. This data has been used in a
number of ABMs now for creation and attribution of agents. In addition it would be even more
useful if one of the Eclipse
project examples utilized this data. One issue is that this data is very
large consisting of the geographic locations of all US households and person records with full
census attributes for each household occupant for the entire US; the appliance is alrea
dy 8GB
last time I looked. As well datasets for Mexico, India, and Cambodia have also been created.
Perhaps we should create another appliance specifically for this data and similar?
Example Eclipse Projects and Quick Start Guide
The ABM++ framework ha
s been loaded into the Eclipse IDE as a first example project. It has
been purposely setup as a standard make project meaning that it should build fine outside of
Eclipse. Other examples will likely be included. Some of the MPI exercises from
-
tutor.ncsa.illinois.edu
are good candidates. As well we should investigate mpi4py examples.
Getting the Appliance
The latest version of the appliance should be available from the MIDAS website and/or FTP
or
early on by email request. There will be one or more versions of the appliance available.
Versions will be by virtual image type (VMWare or Sun VBOX) and by 32 or 64 arch. Other
versions might be available with more CPUs and memory but some of this i
s configurable by the
players servers that will host the images. Download the virtual image zip file. Install the player
or server on your host system, unzip the appliance, and point your player or server to the virtual
image. See your players or server
documentation for more details. This is it really, you should
be looking at an entire operating system, with network connectivity, and all the development
tools, and the ABM++ framework described in this document. You may also run your image
from within
a server setup and connect to the instance with VNCServer, No Machine NX, or
RDP if you are using the VBox image.
Start Eclipse and Running the ABM++ Example
With this latest release of the gnome desktop Eclipse has a small bug which makes it so some o
f
the button clicks within the IDE don’t work. The current fix is to start Eclipse with a special
flag. This has been rolled up into StartEclipse.sh though. Open a terminal window and type
StartEclipse.sh. You should be looking at the Eclipse IDE with
project folders on the left.
Eclipse is organized according to developer perspectives. When you first start Eclipse you will
be looking at the C++ developer perspective. Other perspectives that you will be using include
the parallel runtime perspective
and the debug perspective. These can be accessed a variety of
ways. One way is up in the right hand corner; you should see a couple icons and two arrows >>
clicking the icon and following the prompts you should be able to switch perspectives. The other
method is to use the window menu item and open perspective option. In addition to perspectives
the IDE is based on runtime configurations, profiling configurations, and debugging
configurations. These configs are how you will build and launch your tasks.
These are first
setup using the menu items run as, profile as, debug as. Manage and modify these with the run
configurations, profile configurations, and debug configurations. Under these you will be asked
to name the config, pick the executable, point
to the debugger, pick the MPI resource manager,
set the profiling options and other items.
One of the most critical steps to not skip is starting the MPI resource manager. The appliance
has been configured so that this one machine will simulate multip
le nodes. Currently it has been
configured to simulate eight nodes. Before running your application you must switch to the
parallel runtime perspective and create (one should already be there) and/or start the resource.
You will see the nodes displayed
as well there are windows in this perspective to see individual
nodes output or the combined console output. To see individual process info, double click a
node and then click process.
The debug process is also fairly straight forward. From either the d
ebug perspective or the C++
dev perspective you insert break point by clicking just to the left of the code. When the debug
configuration is run, either by the menus, or button bar you will be presented with your typical
stepping mechanisms. Because you
are likely looking at parallel code it will be a bit confusing
as you will see multiple break point at different locations and at different times.
Profiling and tracing is configured by selecting the various tau flags that instrument your code.
This is
done under a tab in the profiling configuration. Profiling and tracing is not required to
develop an application but you might be interested in it at some point.
The documentation for Eclipse the CDT and PTP is really not too bad. If you have not used
Eclipse before it would be worth skimming these before going much farther. In addition you
should visit the Tau, papi, pdt, …… websites for additional information as you dive more into
profiling and tracing.
Question & Answer
Q: I already have an envir
onment for MPI development why use this?
A: This is not intended to be an expert MPI programmer’s suite. It is also not a production
environment for running large simulations? Think of this as a way to share your examples with
others and collaborate on fr
ameworks like the included ABM++ project example.
Q: I have examples I would like to contribute, how can I do that?
A: Ideally all the project examples would be maintained in an outside source code repository. If
given access to this, then from your appl
iance you should be able to contribute your examples.
Future releases of the appliance may then also more directly include your project examples.
Q: Can I customize this environment once I get it?
A: Yes, it is yours, go for it. When you add something tha
t you think would be very useful to
others it can be proposed for the next version also if you enhance the integration of any of the
tools or utilities that would also be great. Take notes on what you’ve done.
Q: So I have not done much with parallel pro
gramming yet but I am looking at and running
examples in a matter of minutes, isn’t that cool? How much time went into setting this up, could
I just have done it myself?
A: Yes and yes. The setup was somewhat time consuming but the biggest thing you gain
over
doing this yourself are the contributed examples and hopefully collaboration with others.
Q: So I’ve developed or have an idea for something but need more resources than this appliance
can handle, what do I do?
A: MPI is supported on a number of cl
uster configurations at RTI and at numerous of other
locations as well as on clouds like Amazon EC2. More robust versions of this appliance may be
available but in the end you should probably be thinking about a physical cluster of machines
somewhere to ru
n large simulations. Check early what the end environment looks like and what
libraries are available. Get others involved.
Q:When is the Amazon EC2 cloud version going to be ready?
A:If there is enough interest perhaps soon. The conversion necessary do
es not look at all
difficult. In addition with the latest releases of Ubuntu Server canonical is moving towards
supporting Amazon EC2 like configurations. So you may start seeing clouds appear within your
own organizations. On the flip side production e
nvironments for parallel programming are a
move away from the initial intentions to support the ABM++ framework, but if framework
grows I think a production environment starts to make more sense.
Enter the password to open this PDF file:
File name:
-
File size:
-
Title:
-
Author:
-
Subject:
-
Keywords:
-
Creation Date:
-
Modification Date:
-
Creator:
-
PDF Producer:
-
PDF Version:
-
Page Count:
-
Preparing document for printing…
0%
Log in to post a comment | https://www.techylib.com/en/view/bossprettying/what_is_hpc_for_the_purposes_of_simulating_large_social_..._midas | CC-MAIN-2018-26 | refinedweb | 3,978 | 54.42 |
Spring ME Supporting Namespaces?
It was actually quite a while ago since I looked at Spring ME, but then Davide Cerbo mentioned that he had presented Spring ME on Android at a Rome Spring meeting. Way cool! It triggered me thinking about the things that - according to the document I once wrote about it - were not implemented yet.
One of the things that I said was missing was support for namespaces. But is it really? Last week, I started to get some doubts. Maybe it was magically supported anyhow, and I just never bothered to give it a try.
Tonight I gave it a try. I have to admit that it didn't work immediately, but that had more to do with the fact that Spring ME didn't support FactoryBean and InitializingBean yet, and since I tested it on utils:constant, support for that turned out to be required. (FieldRetrievingFactoryBean implements both of these interfaces.) So, once I added support for FactoryBean and InitializingBean, it turned out to be working fine. Quite to my astonishment, I have to say.
So, in my test set up, this is my Spring configuration file:
<beans xmlns="..." xsi="..." util="..." schemalocation="...">
<bean id="person" class="me.springframework.sample.namespaces.Person">
<property name="age">
<util:constant
</util:constant></property>
</bean>
</beans>
... and this is what Spring ME is generating:
org.springframework.beans.factory.config.FieldRetrievingFactoryBean result =
new org.springframework.beans.factory.config.FieldRetrievingFactoryBean();
result.setStaticField("java.lang.Integer.MAX_VALUE");
result.afterPropertiesSet();
return result.getObject();
How about that! Note that I am no defining the FieldRetrievingFactoryBean anywhere in my configuration file. That's all based on Spring namespaces. Based on this, I get the feeling that this would basically work for any namespace, as long as the bean definitions generated by Spring are actually compatible with the subset of Spring currently supported by Spring ME. | http://blog.xebia.com/spring-me-supporting-namespaces/ | CC-MAIN-2017-13 | refinedweb | 309 | 50.23 |
Hello, I'm new to sage and have been trying to import numpy when starting up sage for a few hours now. I've searched everywhere and so far i've tried the following options:
Editing the import_all variable in .sage/ipythonrc
import_all numpy
I've also tried adding some execute instructions in the ipythonrc
execute print "test" execute from numpy import *
The thing is, the first line works and writes "test" to the console, but the import statement doesn't seem to work.
Finally, I've edited the main function in .sage/ipy_user_conf like this:
def main(): from numpy import * o = ip.options ip.ex('from numpy import *') main()
But this doesn't seem to work either. When I try to create a new column matrix like this:
a=matrix("[1; 2; 3; 4]")
I get an error which is solved by manually importing the numpy libs. Is there any other way to automatically load modules at startup? Am I missing something?
Thanks in advance for any help. | https://ask.sagemath.org/questions/8929/revisions/ | CC-MAIN-2021-17 | refinedweb | 169 | 72.66 |
Search engine optimization (SEO) is a core element of a strong global growth strategy. To be able to run your application on a global scale, you need to tear down this barrier right from the start.
Nuxt is a popular JavaScript framework that can significantly help your application with SEO to get better rankings on Google. Based on Vue.js, it supports both the Single Page Application (SPA) and Server Side Rendering (SSR) format.
Since it supports pre-rendering and Vue-meta out of the box, it has been a go-to framework for all the applications that need better SEO but still use the quite awesome Vue.js syntax and libraries.
In this end-to-end, we’ll show you how to internationalize your Nuxt.js app and make it fit for the global marketplace. Off we go!
🔗 Resource » Check out our Ultimate Guide to JavaScript Localization for a deep dive into all the steps you need to make your JS apps ready for users around the globe.
create-nuxt-app– to scaffold our Nuxt application
nuxt-i18n– to localize our application
create-nuxt-apputility. It is not mandatory to install this utility first, we could rather use
npxand use it directly.
npx create-nuxt-app nuxt-intl
You can add any entries of your choice for Project name, Project description, and Author name. We can choose between
npm and
yarn. Go simply with the one you feel most comfortable with. It is a good practice to always use
ESLint to detect syntax errors. I prefer using
Prettier as it makes my code look properly formatted, and when multiple developers work on the same code, it forces them to use a particular format so that the code remains uniform.
cd nuxt-intl npm run dev
In this tutorial, we’ll use a library called
nuxt-i18n, based on
vue-i18n, with some Nuxt-specific localization options. Before installing the
nuxt-i18n package, let us go through the basics of localization and have a look at the variety of options available in this library.
We define key-value pairs for each language, where the key remains the same for all languages and the value is the translation in that language.
// English { "hello": "Hello" } // French { "hello": "Bonjour" }
We have two translation options.
- Inside Vue Components
- External JSON or Js files.
Translations inside the Vue components
<i18n> { "en": { "hello": "hello!" }, "fr": { "hello": "Bonjour!" } } </i18n> <template> </template>
//en.json { "message": "Hello", "login": { "username": "User Name", "password": "Password" } }
npm i nuxt-i18n
Since Nuxt does not have a CLI to automatically generate a configuration like
vue-cli for
vue-i18n, we have to add the following configuration to set up the plugin.
Let us create a
config folder and our configuration in the
i18n.js file.
import en from '../locales/en.json' import fr from '../locales/fr.json' export default { locale: 'en', fallbackLocale: 'en', messages: { en, fr } }
In this configuration, we are using the external files to store our translation texts. For example, let us use English and French. We can all pass a default and fallback locale to the plugin. In the next step, we create these two external files to store our translations.
Create a
locales directory in the root folder and two files,
en.json and
fr.json, which will contain all our translations.
{ "message": "Hello!" }
{ "message": "Bonjour" }
Finally, let’s add this library to our
nuxt.config.js file so that Nuxt is aware of it. Now we can make use of it in our application.
import i18n from './config/i18n' buildModules: [ /* other modules */ [ 'nuxt-i18n', { vueI18nLoader: true, defaultLocale: 'fr', locales: [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' } ], vueI18n: i18n } ] ]
vueI18nLoader is optional. This will enable us to write translations in our Vue components.
<template> <div class="container"> <h1 class="title">{{ $t('message') }}</h1> <!-- some code --> </div> </template>
Here,
$t() tells our Nuxt app to use the translation version of the
key based on the selected language.
[ 'nuxt-i18n', { defaultLocale: 'fr', locales: [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' } ], vueI18n: i18n } ]
<template> <div class="lang-dropdown"> <select v- <option v-{{ lang.name }}</option > </select> </div> </template> <script> export default {} </script>
Let’s add this component to ourfile. Now we can easily switch between languages. Great! Let us deep dive into different ways of localization techniques the library offers and see an example for each one of them.
We can use it in our components as follows:
<p>{{ $t('copyrightMessage', { name: 'Phrase.com' }) }}</p>
{ "welcomeMessage": "Welcome! {0}, Your Email: {1} has been verified successfully" }
<p>{{ $t('copyrightMessage', ['Preetish HS', '[email protected]']) }}</p>
As each language has its own specific structure, this technique gives the translator the flexibility to place any value anywhere in a sentence.
{
export const numberFormats = { en: { currency: { style: 'currency', currency: 'USD' } }, 'en-IN': { currency: { style: 'currency', currency: 'INR' } }, fr: { currency: { style: 'currency', currency: 'EUR' } } }
import { numberFormats } from '../formats/numberFormats' import en from '../locales/en.json' import fr from '../locales/fr.json' export default { defaultLocale: 'en', fallbackLocale: 'en', numberFormats, messages: { en, fr } }
<p>{{ $n(1000000, 'currency') }}</p> <p>{{ $n(7000000, 'currency', 'en-IN') }}</p> <p>{{ $n(7000000, 'currency', 'fr') }}</p>
//output $1,000,000.00 ₹70,00,000.00 7 000 000,00 €
Currency looks much better with symbol and proper formatting, International number system for Dollars (USD) and Indian number system for Rupees (INR).
Date and time localization corresponding values show how that property will be displayed.
Reference: ECMA-International
export const dateTimeFormats = { en: { short1: { year: 'numeric', month: 'short', day: 'numeric' }, long: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric' } }, 'en-IN': { short1: { year: 'numeric', month: 'short', day: 'numeric' }, long: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric', hour12: true } } }
To use these formats in our application, we use the
$d() notation. Just like the number formats, if we don’t explicitly pass the
locale, the currently selected locale will be used. If the latter doesn’t have a format defined, then the fallback language format will be used. So make sure to have formats defined for supported locales.
<p>{{ $d(new Date(), 'short') }}</p> <p>{{ $d(new Date(), 'long', 'en-IN') }}</p>
//output Jun 12, 2020 Mon, 12 Jun, 2020, 11:45 am
Just like our number formats, the library will automatically format the date and time based on International standards.
Nuxt-specific localization
The advantage of using
nuxt-i18n over the regular
vue-i18n are its additional options to localize routes, as well as a number of SEO-related benefits.
Localizing routes
Just by seeing our URL, we won’t come to know in which language the application is currently used. We are dependent on local storage or cookies to save our locale preferences.
To understand this better, we need to create two more pages,
About.vue and
Contact.vue, and add the links to those pages to our
index.vue page.
<template> <div> <nuxt-link{{ $t('about') }}</nuxt-link> <nuxt-link{{ $t('contact') }}</nuxt-link> </div> </template>
Now, if we navigate to the
about page, irrespective of the language choice, it opens
localhost:3000/about. It would be much better to have a locale prefixed on our URL (
localhost:3000/fr/about). To achieve this, there are two strategies:
- Prefix without default: Our default language,
en, will not be prefixed, whereas other languages will, e.g. for French, the about page will have the URL:
localhost:3000/fr/.
- Prefix: With this strategy, all the languages including our default language will be prefixed.
- Prefix and default: This strategy combines the previous two strategies. i.e. the default language will have both a prefixed and non-prefixed version.
By default,
nuxt-i18n would already create prefixed routes for us. Without any additional code, it would apply the third strategy.
//routes generated [ { path: "/", component: _3237362a, name: "index___en" }, { path: "/fr/", component: _3237362a, name: "index___fr" }, { path: "/about", component: _71a6ebb4, name: "about___en" }, { path: "/fr/about", component: _71a6ebb4, name: "about___fr" }, { path: "/contact", component: _71a6ebb4, name: "about___en" }, { path: "/fr/contact", component: _71a6ebb4, name: "about___fr" } ]
If we navigate to
localhost:3000/fr/about, it would automatically load French translations on our
about page. However, this will not happen if we navigate through
<nuxt-links>. To make this work, we pass a
localePath() function with the relevant page name.
localePath() is provided by the
nuxt-i18n library, which returns the localized path of the passed in
route.
<nuxt-link :{{ $t('about') }}</nuxt-link> <nuxt-link :{{ $t('contact') }}</nuxt-link>
Default translations will work as it as, when you change the translation to French and then click on about it will now open
localhost:3000/fr/about. the
about page
aboutwill open to
localhost:3000/about. If you now change the translation to French and then click on
about, it will open to
localhost:3000/fr/about.
To have the prefix “lang” for our default language, we need to pass a
strategy attribute to our Nuxt configuration.
// nuxt.config.js ['nuxt-i18n', { strategy: 'prefix' }]
Now load
localhost:3000, and it would automatically redirect to
localhost:3000/en. If you want to remove the prefixed URLs for the default language, set the strategy to
prefix_except_default. This will make the URLs, such as
localhost:3000/en, non-functional.
Search Engine Optimization (SEO)
If the
seo attribute is set to
true during initialization, the library performs various SEO improvements. We also need to pass
ISO for each locale, which the library uses to perform these optimizations:
- Updating the
langattribute in HTML tag
hreflanggeneration for anchor tags
<a href="" hreflang="<selected-locale-iso>">
- Open graph locale tags such as
og:localeand
og:locale:alternate
Let us update our plugin initialization to get these optimizations automatically made for us. This will wrap up our
[ 'nuxt-i18n', { strategy: 'prefix', defaultLocale: 'en', seo: true, locales: [ { code: 'en', name: 'English', iso: 'en-US' }, { code: 'fr', name: 'Français', iso: 'fr-FR' } ], vueI18n: i18n } ] | https://phrase.com/blog/posts/nuxt-js-tutorial-i18n/ | CC-MAIN-2022-33 | refinedweb | 1,639 | 54.93 |
Hello!
I have very big problems with parallelism on my laptop. I've written simple OpenMP
P.S. I have Windows 10 and NetBeans with MinGW compiler.
Link Copied
Hi Griogrii,
Thanks for reaching out to us.
Could you please give more information about your laptop configuration. Kindly, give your scripts or workload that you are trying out. So that we can try it from our end.
Dear Chithra_Intel,
thank you for your response!
Tell me, please what kind of information are you interested in?
As I said, the model of laptop is Acer Nitro AN515-51 and CPU is Intel(R) Core(TM) i7-7700HQ.
I am trying to run simple arithmetic program:
#include <stdio.h> #include <iostream> #include <math.h> #include <omp.h> using namespace std; int main(int argc, char* argv[]) { double a[100000]; #pragma omp parallel num_threads(8) //number of threads is varied { #pragma omp for schedule(static) for (int i = 0; i < 100000; i++) { for (int j = 0; j < 20000; j++){ a = 0; a++; a = a / (a+0.3424782); a=sqrt(a); } } } cout<<a[0]<<" "<<a[12900]<<" "<<a[46540]<<" "<<a[78706]<<" "<<a[99000]<<" "<<a[99909]<<" "; //checking the correctness of the work return 0; }
HW-based Hotspots analysis has revealed that for 8 threads, for example, I have 31.4% parallelism anf 57.3% microarchitecture usage.
(To my great regret, I can't attach screen of histogram due to technical problem in this site, but it is terrible:
1 logical CPU column is very high, 2-7 logical CPU columns are low and 8 logical CPU column is empty :( ).
But then I tried to test parallelism manually and obtained contradictory results.
These are the results of computation with different number of threads (number of threads - corresponding execution time):
Debug
1 74s
2 38s
4 20s
8 11s (22.8s with Intel VTune Profiler and scary histogram)
(parallelism is almost ideal !)
Release
2 47-53? ms
4 53-58? ms
8 47-69? ms
(? means big range of values)
(Release runs faster than Debug, but has no parallelism; -fopenmp is enabled)
So, in Debug case maybe the problem is in some Intel Vtune Profiler Options? I run it as an administrator.
However, causes of problems in Release mode are still unclear. It is interesting that the time of execution doesn't change with the change of maximum of j parameter.
But if some actions with j are added (for example the 3 row of cycle is changed to a = a / (a+0.3424782+(j*1.0/10000));), all of the problems disappear:
Release (jmax 20000->100000)
1 47s
2 24s
4 16s
8 11s (22.6s with Intel VTune Profiler and scary histogram analogous with the descripted above)
(parallelism is good but not ideal, it is strange)
So, I think that the trouble may be in compiler optimization. The compiler understands that cycle with j is useless and just skips it.
The compilation row from Netbeans:
g++ -fopenmp -c -O2 -std=c++11 -MMD -MP -MF "build/Release/MinGW-Windows/main.o.d" -o build/Release/MinGW-Windows/main.o main.cpp
Summary:
1) Why program runs slower with Intel VTune Profiler and has worse parallelism than if I run it manually? (in both Debug and Release modes)
My idea: I should change some options of Intel VTune Profiler. I run it as an administrator..
Hi Griogrii,
We are trying this from our end and will get back to you with the updates soon.
Thanks.
Hi!
I have obtained that Profiler slows programs only in HW-based Hotspots analysis. In User-Mode all work correct (parallelism and histogram is almost ideal).
However, questions I've mentioned above are still actual.
Hi Grigorii,
We tried to take the H/w event based hotspots analysis for your application and able to see the same behavior as noticed by you (Please refer to the screenshots of the vtune summary page attached). So, we had informed this issue to SME and checking this internally.
As you said, the overhead will be more in h/w based profiling compared to user mode sampling, since it has to monitor and collect the underlying h/w events. So, could you please let me know the percentage of difference you observed in h/w based and user mode sampling.
Thanks.
Dear Chithra_Intel,
thank you for your response!
It seems that user mode sampling analysis affects weakly on the execution time and hw-based analysis prolongs it for about 2 times.
However, questions 2 and 3 are still very actual for me:.
Should I open a new thread?
Hi Grigorii,
The few insights/thoughts we got from SME's on your queries are:
Is this clarifies your 2nd query?
Thanks.
Dear Chithra_Intel,
thank you very much for your response!
Yes, it clarifies my 2nd question.
I want to inform you about my progress in 3rd question. I was advised to disable hyper-threading function to increase parallelism on my laptop. If I'm not mistaken, it should be done in BIOS. However, there is no hyper-threading option in BIOS on my laptop. I've asked Acer about it and the answer was that this setting isn't provided.
Tell me, please if idea about hyper-threading is correct and I correctly understand that problems are connected to hardware and can't be solved.
Hi Grigorii,
Thanks for your response. Please look into few points/answers for your queries:
Q:Why program runs slower with Intel VTune Profiler and has worse parallelism than if I run it manually? (in both Debug and Release modes)
Answer: Actually, the elapsed time you observed in the Vtune summary page is the cumulative result of Idle time( In which CPU doesn't do any useful works) and runtime of the application(Where CPU is utilizing). So, in order to get the actual runtime of your application, do:
Elapsed time - Idle time(The first bar in the CPU utilization histogram indicates the idle time where no logical cpu cores are used) = Runtime of the application.
Now, compare this result with the elapsed time you got after running the application without Vtune and this should be comparable. Please let me know whether you are getting comparable result.[Note: please share the results, if possible with snapshots]
Q: Why I have unideal parallelism in Release mode with actions with j even for such a simple arithmetic program with almost 100% parallel actions?
Answer: Compiler optimization happens only in release mode. In your code, without including any operations with 'j' variable, compiler assumes it as dead variable. So, it will perform some optimizations like merge/fuse the loop or something.(Don't know exactly what compiler is doing).
So, we are looking to generate compiler report for getting more picture of this & what happens while introducing actions with 'j' variable. We will give you the updates on this later.
Q: Disabling hyper threading function will improve parallelism or not?
Answer: Currently, we don't have ideas on this.But,while analyzing your application with Vtune, we were able to see that the application performance is good in terms of parallelism.It would be better to stick on User-mode sampling(Hotspots) or do user mode threading analysis to get more detailed information about parallelism. Because, the H/w based hotspots analysis also collects the kernel level threads along with user threads, the parallelism in summary pane can't indicate a true picture of parallelism.
(Link for threading analysis:...).
If possible, could you please share the snapshots of the bottom-up timeline pane for H/w based and User mode sampling results( Both debug and release mode) for detailed analysis.
Hopes this clarifies your some queries.
Thanks.
Dear Chithra_Intel,
thank you very much for your response!
I'm sorry, but I am extremely busy right now and have a lot of another problems. I truly appreciate your help and will try to provide information you ask as soon as possible.
1. There is no sense to profile a debug version without optimizations. Better would be release+debug info.
2. The loop body does not depend on j, so only 100000 iterations are executed in the release mode.
3. it would be better to gather concurrency collection and look at imbalance details, not summary. it looks you have imbalance on the end of parallel region.
Bottom line: IMO low amount of work + imbalance shows summary pictures you see.
Hi Grigorii,
Please let us know that your queries get clarified or not. So, we can close the thread. If not, please share the requested details.
Thanks.
Hi Grigorii,
We are closing the case by assuming that your queries get clarified. Please feel free to raise a new thread if you have further issues. | https://community.intel.com/t5/Analyzers/Bad-parallelism-on-a-laptop/td-p/1184267 | CC-MAIN-2021-39 | refinedweb | 1,456 | 65.12 |
!:
Here is the final trick. And those of you who have read the series have waited a while for this final post. (Sorry for the delay.) Programming against an interface gives you the consistent programming model across the various distributed platforms but abstracting the code that creates the proxy is also critical to hide the .NET Remotingisms from your client code as well.
Take for example the following line from the previous post:
IHello proxy = (IHello)Activator.GetObject(typeof(IHello), "tcp://localhost/Hello.rem");
The use of the Activator class implies a specific distributed application stack so hiding that from your implementation will ease migration to alternate or future stacks with limited client impact. The same holds true for the hosting code written to register objects and channels but this code is often already isolated in the service startup routines (e.g. Main or OnStart for a service).
The easiest way to abstract away the proxy generation code is to use a basic factory pattern on the client that creates the proxy classes. This has the added advantage of enabling the developer to use pooling or handle lifetime issues but the core value for this conversation is the abstraction of proxy creation.
Here is a simple example:
public static class HelloClientProxyFactory
public static IHello CreateHelloProxy()
return (IHello)Activator.GetObject(typeof(IHello), "tcp://localhost/Hello.rem");
As you migrate forward from .NET Remoting to other platforms (e.g., Indigo) this proxy factory can be updated and deployed to your clients enabling the client programming model to remain entirely unchanged but allow your developers to move to a completely different distributed application stack underneath.
This concludes the Shhh… series but I have more post planned for the migration story from .NET Remoting to WCF (“Indigo”).
Stay tuned.
A little self-promotion never hurt anyone...
Some new MSDN TV content has recently been made available on the new features of .NET Remoting for .NET Framework 2.0. Enjoy!
Matt Tavis shows some new features and code examples in .NET Remoting in .NET Framework 2.0, including the new IpcChannel, the secure TcpChannel, and Version Tolerant Serialization (VTS) to allow authors to version their types without breaking serialization.
Now that you expose the your remote object through a CLR interface, that interface should limit itself to interfaces and serializable types as parameters and return values. This guideline is really just an additional follow-on to rule one about using only CLR interfaces.
Let's expand on the original example from part 1. The original interface from part 1 is below:
public interface IHello{ string HelloWorld(string name);}
This works fine since the the HelloWorld accepts and returns only strings which are serializable. What if we want to add a factory pattern that returns newly created remote objects or make the HelloWorld method take a custom type. For these scenarios we should continue to use interfaces and define serializable data types for passing of information.
First let's add the factory pattern:
public interface IHelloFactory{ IHello CreateHelloService();}
This factory pattern is also an interface and simply returns the original IHello interface. The implementation of this interface would inherit from MBRO and new up a HelloObject but all the clients of this service would continue to use the shared interfaces for programming rather than the implementation classes.
Now we expand HelloWorld to take the new HelloMessage custom data types that is serializable.
public interface IHello{ HelloMessage HelloWorld(HelloMessage message);}
[Serializable]public class HelloMessage{ private string SenderName; private string Text; // property accessors omitted for brevity ...
public HelloMessage(string sender, string text) { ... }}
By sticking to this guidance we continue to deploy only the types necessary to share the contract. Shared interfaces (IHello and IHelloFactory) and serializable data types (HelloMessage) are the only pieces of the contract that consumer of our remote service need ever program against. Even if you move to a different activation, hosting or communications technology these same contract types will be reusable and are not .NET Remoting specific. Upgrading from this model to a future technology will be simple and mechanical since the programming interface will remain constant once an instance of the service is activated and accessible.
The new client code will allow for activation of the factory and then creation and consumption of the IHello service:
IHelloFactory factoryProxy = (IHelloFactory)Activator.GetObject(typeof(IHelloFactory), "tcp://localhost/HelloFactory.rem");IHello helloProxy = factoryProxy.CreateHelloService();HelloMessage returnMessage = helloProxy.HelloWord(new HelloMessage("Me", "Hello"));
In Part 1 it was suggested to use only interfaces to program against your remoted object. Another consideration for enforcing the correct usage of your remote object is to limit access to the implementation except through the interface that you defined for it.
You can do this by marking the implementation internal so that it is cannot be constructed directly except within the same assembly.
Consider the following changed code from Part 1:
Server code:internal class HelloObject : MarshalByRefObject, IHello{ string IHello.HelloWorld(string name) { return "Hello, " + name; }}
Shared code:public interface IHello{ string HelloWorld(string name);}
The same code on the client will allow for activation of an instance of the HelloObject class:
But this will prevent someone from using the type outside the implementation assembly by constructing the class directly: // this will now fail outside the implementation assemblyHelloObject localObject = new HelloObject();
This may seem a bit draconian and unnecessary but it can enforce two good early development practices:
1. If you plan on "remoting" an object in the future don't treat it as "local" during development. This can lead to performance and scalability issues that start with "But it work fine running locally on my dev box...".
2. Enforce your contract (i.e., the IHello interface) as the only way to program against your remote object. If you are planning on "remoting" an object then enforcing a common programming model, whether local or remote, can help ensure consistency and avoid issues when deploying your remote object later.
Even after following this advice you can access the implementation class locally without remoting it by using the Activator class:
IHello localObject = (IHello)Activator.CreateInstance(Type.GetType("HelloObject"));
This allows local developers to use the implementation class but keeps the programming interface common whether local or remote.
One of the easiest ways to avoid locking yourself into .NET Remoting is to avoid exposing its most infamous type in your contract: MarshalByRefObject (MBRO). To marshal object references in .NET Remoting your type needs to inherit from MBRO but that doesn't mean your contract needs to expose types that inherit from MBRO.
Use CLR Interfaces for the remote objects in your contract.
This isn't really new advice. Ingo Rammer has suggested this in his book as well. Interestingly, those of you following the Indigo programming model will have seen a lot of interface usage so this pattern will carry forward nicely.
Let's take an example:
Server code:public class HelloObject : MarshalByRefObject, IHello{ string IHello.HelloWorld(string name) { return "Hello, " + name; }}
Now you can register HelloObject on the server side but get an instance of the remote object with the following call:
There are some major advantages to this approach:
- Only the interface needs to be shared, which allows for greater flexibility in versioning and deployment- The interface (and hence contract) that has been established can be re-used later as part of the migration to Indigo
There is one disadvantage to this approach:
- Interception of new() is not supported
I will talk about how to get this support back in a future section of this series.
Q&A and updates---
Here are some good questions I got on this post with some of my answers...
Q: Why by exposing a type that inherits from MarshalByRefObject I'll get locked into Remoting? What you said in your post is a good code practice but not necessary.
A: .NET Remoting requires the sharing of types between client and server. Imagine that a new programming model came along that used a new infrastructure class for intercepting object creation and proxy generation (MBRO2). Keeping your interface seperate from your implementation allows you switch from MBRO to MBRO2 without changing the contract with the server or the type that you program against (i.e., the interface). You might have to change activation code but the programming experience against the remoted object can remain constant. Like you say, it isn't required but it is a good practice.
Q: MBRO belongs to System namespace and not Remoting, any time you cross app domain boundaries to call your object you need it's ObjRef so it is not remoting specific to inherit from MBRO.
A: Crossing AppDomain boundaries within a process using MBRO *is* .NET Remoting. It isn't the same exact programming model for activation but it is using the .NET Remoting infrastructure.
So you've heard about SOA and Indigo and the future of distributed application development on .NET. You've even seen the long-running discussion of our guidance on Richard Turner's blog. You are now asking yourself:
But how can I use .NET Remoting today but be prepared for Indigo?
Hopefully, I can answer all of your questions in this multi-part series. The idea is to give some practical guidance with some code snippets to show you how to use .NET Remoting today without painting yourself into tomorrow's corner.
Now that I have your attention...
We are seriously considering deprecating the SoapFormatter in .NET Framework 2.0. It is the nexus of a whole host of serialization issues and implies a promise of interop that it does not and will not live up to. It also does not support generics. Additionally, those of you interested in the new Version Tolerant Serialization features in .NF 2.0 will note that it is not supported on the SoapFormatter. This means that types using VTS to introduce new fields would break when serializing between versions over the SoapFormatter. This is also true for framework types. So if you are using a framework type that adds fields in .NF 2.0 and you do not upgrade both apps using the SoapFormatter to .NF 2.0 then you could see serailization errors occuring simply by upgrading to .NF 2.0 on one side. Before you ask, no I don't have a list of framework types that might break in this scenario but the question is whether requiring switching to the BinaryFormatter is unacceptable.
The obvious solution to this is to switch to the BinaryFormatter. It supports VTS, the serialization of generics and is one of the Cross-AppDomain formatters, where our guidance recommends the usage of .NET Remoting for new applications.
This is our stance as of Beta1 for .NET Framework 2.0.
So the questions is: Who has to have the SoapFormatter in .NF 2.0 and why?
I'll be going to TechEd Europe to give a few talks. If you are interested in any of the following then add them to your schedule:
For anyone interested in talking about .NET Remoting specifically contact me through the TechEd site and I would be happy to meet with you.
I'll be in Amsterdam from Monday to Thursday.
Interested in Web Services features in Whidbey? So am I!
Yasser Shohoud, Software Legend, and I will be giving a talk at TechEd to introduce some our favorite new Web Services features to you at TechEd. The new talk (CTS201) is not even in the Session Catalog yet but never fear Yasser and I will be giving it. It is planned for the Friday at 2:45pm slot so mark your calendars!
We'll be covering Web Services, XmlSerialization and System.Net features to make your Whidbey Web Services faster, easier to write, more interoperable and more flexible. See you there!
Those of you scouring the list of talks at TechEd for in-depth .NET Remoting discussions will be disappointed. .NET Remoting will be touched on in the Connected Systems track (CTS300) by Richard Turner but that will be prescriptive guidance for the usage of .NET Remoting. There isn't a session dedicated to .NET Remoting at this TechEd.
But the good news is that I'll be at TechEd and would be happy to sit down with interested folks and talk through current and future .NET Remoting features! I'll be at TechEd all week and would be happy to talk to you about .NET Remoting.
Just post a response to this entry and I'll see if I can setup and impromptu meeting at TechEd for those interested in .NET Remoting to help you out.
As a first blog entry, I figure introductions are in order. I am Matt Tavis, PM at Microsoft working on the .NET Framework 2.0 (Whidbey) and Indigo. My Whidbey features areas are .NET Remoting, runtime serialization and xml serialization. | http://blogs.msdn.com/mattavis/default.aspx | crawl-002 | refinedweb | 2,139 | 55.95 |
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- This is a non-exposed internal module. -- -- This code contains utility function and data structures that are used -- to improve the efficiency of several instances in the Data.* namespace. ----------------------------------------------------------------------------- module Data.Functor.Utils where import Data.Coerce (Coercible, coerce) import GHC.Base ( Applicative(..), Functor(..), Maybe(..), Monoid(..), Ord(..) , Semigroup(..), ($), otherwise ) -- We don't expose Max and Min because, as Edward Kmett pointed out to me, -- there are two reasonable ways to define them. One way is to use Maybe, as we -- do here; the other way is to impose a Bounded constraint on the Monoid -- instance. We may eventually want to add both versions, but we don't want to -- trample on anyone's toes by imposing Max = MaxMaybe. newtype Max a = Max {getMax :: Maybe a} newtype Min a = Min {getMin :: Maybe a} -- | @since 4.11.0.0 instance Ord a => Semigroup (Max a) where {-# INLINE (<>) #-} m <> Max Nothing = m Max Nothing <> n = n (Max m@(Just x)) <> (Max n@(Just y)) | x >= y = Max m | otherwise = Max n -- | @since 4.8.0.0 instance Ord a => Monoid (Max a) where mempty = Max Nothing -- | @since 4.11.0.0 instance Ord a => Semigroup (Min a) where {-# INLINE (<>) #-} m <> Min Nothing = m Min Nothing <> n = n (Min m@(Just x)) <> (Min n@(Just y)) | x <= y = Min m | otherwise = Min n -- | @since 4.8.0.0 instance Ord a => Monoid (Min a) where mempty = Min Nothing -- left-to-right state transformer newtype StateL s a = StateL { runStateL :: s -> (s, a) } -- | @since 4.0 instance Functor (StateL s) where fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v) -- | @since 4.0 instance Applicative (StateL s) where pure x = StateL (\ s -> (s, x)) StateL kf <*> StateL kv = StateL $ \ s -> let (s', f) = kf s (s'', v) = kv s' in (s'', f v) liftA2 f (StateL kx) (StateL ky) = StateL $ \s -> let (s', x) = kx s (s'', y) = ky s' in (s'', f x y) -- right-to-left state transformer newtype StateR s a = StateR { runStateR :: s -> (s, a) } -- | @since 4.0 instance Functor (StateR s) where fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v) -- | @since 4.0 instance Applicative (StateR s) where pure x = StateR (\ s -> (s, x)) StateR kf <*> StateR kv = StateR $ \ s -> let (s', v) = kv s (s'', f) = kf s' in (s'', f v) liftA2 f (StateR kx) (StateR ky) = StateR $ \ s -> let (s', y) = ky s (s'', x) = kx s' in (s'', f x y) -- See Note [Function coercion] (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) (#.) _f = coerce {-# INLINE (#.) #-} {- Note [Function coercion] ~~~~~~~~~~~~~~~~~~~~~~~ Several functions here use (#.) instead of (.) to avoid potential efficiency problems relating to #7542. The problem, in a nutshell: If N is a newtype constructor, then N x will always have the same representation as x (something similar applies for a newtype deconstructor). However, if f is a function, N . f = \x -> N (f x) This looks almost the same as f, but the eta expansion lifts it--the lhs could be _|_, but the rhs never is. This can lead to very inefficient code. Thus we steal a technique from Shachaf and Edward Kmett and adapt it to the current (rather clean) setting. Instead of using N . f, we use N #. f, which is just coerce f `asTypeOf` (N . f) That is, we just *pretend* that f has the right type, and thanks to the safety of coerce, the type checker guarantees that nothing really goes wrong. We still have to be a bit careful, though: remember that #. completely ignores the *value* of its left operand. -} | http://hackage.haskell.org/package/base-4.12.0.0/docs/src/Data.Functor.Utils.html | CC-MAIN-2019-09 | refinedweb | 609 | 69.62 |
Opened 13 years ago
Closed 10 years ago
#2 closed enhancement (fixed)
bzr_buildbot.py: bzr needs a BzrPoller
Description
we don't yet have a way to generate Changes from bzr. We need to find out how to write commit scripts for a bazaar repository and then implement one.
Attachments (2)
Change History (12)
comment:1 Changed 13 years ago by warner
comment:2 Changed 13 years ago by warner
- component changed from website to changesources
comment:3 Changed 13 years ago by warner
some more notes:
~/.bazaar/locations.conf: [/home/warner/full/path/to/tree] post_commit = bzrlib.plugins.buildbot.sendchange buildmaster = host.example.com:12345
post_commit is a space-separated list of fully-qualified function names. Each will be eval()ed in a way that calls sendchange(branch, revision_id).
~/.bazaar/plugins/buildbot.py:
def sendchange(branch, revision_id): pass
However, this hook doesn't seem to be triggered when I push a change in via something like bzr push s. I don't know if push triggers commit or not.
comment:4 Changed 13 years ago by warner
- Summary changed from bzr_buildbot.py: bzr needs a hook script to bzr_buildbot.py: bzr needs a BzrPoller
I spent some time chatting with <lifeless> on IRC today. Some things I learned:
- most of the existing access schemes (file, sftp, http) do not run any code on the "master" host at all. Any post_commit hooks would be run on the client machine. This could be made to work, but you'd have to have buildbot and the hook plugin installed on all developers machines, which would be a nuisance.
- the "Smart Server" that is under development now will make it much easier to run code like this on the central machine after each commit.
- he recommends using 'import bzrlib' to get at things like 'bzr revno', rather than spawning 'bzr' as a shell command. He says they try hard to maintain API compatibility.
So I think we need to write a BzrPoller? first, and defer writing a hook script until after the "smart server" is implemented. The only thing we could implement now (using post_commit=) would be too much of a nuisance to deploy.
comment:5 Changed 12 years ago by warner
- Milestone changed from 0.7.6 to 0.7.7
comment:6 Changed 12 years ago by warner
some comments from an IRC chat a few weeks (months?) ago:
<spiv> warner: that seems ok, but I think you can make the common case of no new revisions faster by first checking b.last_revision() [01:41] <spiv> warner: and really you want to use revision ids rather than revnos, in case someone e.g. did an uncommit. <spiv> warner: also, if you do b.lock_read()/b.unlock() around the whole thing, it should be a little faster because it will be able to cache some things. [01:42] <spiv> warner: also "# NOTE: b.revision_history() does network IO, and is blocking." is a strange comment, given that that's true of the previous line too, but you didn't comment it :) <spiv> (and of the line before)> <spiv> warner: "# branch= ?"... that's just self.location. [01:51] <spiv> warner: "# revision= ?"... either the revno or the revision ID, whichever you prefer. [01:52] <spiv> warner: No other comments spring to mind... if you have specific questions, let me know. <lifeless> whats revision_history ised for? [01:59] <lifeless> if its to get the revno, use get_revision_info, its cheaper <spiv> lifeless: it's to get the all the new revisions since the last poll <lifeless> isn't that update ? :) <spiv> Presumably so that it can send updates or whatever about them. <spiv> Well, I assume the buildmaster doesn't actually need or want to have an actual checkout or branch. <spiv> warner: please feel free to chime in here :) <lifeless> if its just caching metadata about where the branch got to; sure. [02:03]
Changed 12 years ago by warner
removed the obvious MultiService? bug
comment:7 Changed 12 years ago by warner
- Milestone changed from 0.7.7 to 0.7.8
not making enough progress on this one, bumping it to 0.7.8
Changed 12 years ago by ijon
changes to get it work (in simplest scenario -- single branch)
comment:8 Changed 12 years ago by ijon
- Cc ijon added
comment:9 Changed 11 years ago by dustin
- Milestone changed from 0.8.0 to 0.7.+
Any thoughts on this? Since it's going into contrib/, I'm happy to use it if someone says "yeah, it works".
comment:10 Changed 10 years ago by krajaratnam
- Milestone 0.8.+ deleted
- Resolution set to fixed
- Status changed from new to closed
The BzrPoller? went into contrib/ in commit 0da76648effcfbf8e82100b349871b992f02216e and Dustin recently created #708 to promote BzrPoller? to first class citizen, so I'll go ahead and close this ticket.
some useful links:
I think the path here is to create a Bzr plugin for buildbot, distributed with buildbot, and then provide instructions for enabling the plugin from within a Bzr repository. | http://trac.buildbot.net/ticket/2 | CC-MAIN-2019-39 | refinedweb | 839 | 74.49 |
There!'
If you start the server and visit, you will be shown a 404 Not Found error document, but if you visit, you will see the Hello World! message because the public action hello() is able to return the value from the private method _result().', <dl> <dt>Username:</dt> <dd><input type="text" name="username"></dd> <dt>Password:</dt> <dd><input type="password" name="password"></dd> </dl> <input type="submit" name="authform" /> <hr /> </form> </body> </html> """ def public(self): return 'This is public' def private(self): if request.environ.get("REMOTE_USER"): return 'This is private' else: return redirect_to(controller='homegrown', action="signin")
In this example, you can access without signing in, but if you visit, you will be redirected to the sign-in form at to sign in. If you enter a username that is the same as the password, you will be shown the private message. You will be able to continue to see the private message until you clear the Pylons session cookie by closing your browser.
This example works perfectly well for the straightforward case described earlier, but when you start dealing with complex permissions and different authentication methods, it quickly becomes preferable to use an authentication and authorization framework.
AuthKit is a complete authentication and authorization framework for WSGI applications and was written specifically to provide Pylons with a flexible approach to authentication and authorization. AuthKit can be used stand-alone with its user management API or integrated with other systems such as a database. You’ll see both of these approaches in this chapter and the next.
AuthKit consists of three main components:
In this chapter, you’ll learn about each of these components in turn before looking at AuthKit’s more advanced features.
Of course, AuthKit is just one of the authentication and authorization tools available for Pylons. There may be occasions when you want to handle all authentication yourself in your application rather than delegating responsibility to AuthKit. Although AuthKit provides a basic platform on which to build, you should also be willing to look at the AuthKit source code and use it as a basis for your own ideas.
Note
One toolset that is proving to be particularly popular at the time of writing is repoze.who, which is part of the repoze project to help make Zope components available to WSGI projects such as Pylons. If you are interested in repoze.who, you should visit the web site at.
AuthKit is actually very straightforward to integrate into an existing Pylons project. You’ll remember from Chapter 3 that a web browser finds out what type of response has been returned from the server based on the HTTP status code. There are two HTTP status codes that are particularly relevant to authentication and authorization. A 401 status code tells the browser that the user is not authenticated, and a 403 status code tells the browser that the user is not authorized (which you may have seen described in error pages as Forbidden). AuthKit’s authentication middleware works at the HTTP level by responding to 401 status responses so that the authentication middleware can work with any application code that is HTTP compliant, regardless of whether AuthKit is used for the authorization checks.
Let’s create a new project to use with AuthKit. Run the following commands to install AuthKit and create a test project; again, you won’t need SQLAlchemy support:
$ easy_install "AuthKit>=0.4.3,<=0.4.99" $ paster create --template=pylons AuthDemo $ cd AuthDemo $ paster serve --reload development.ini
To set up the authentication middleware, edit the AuthDemo project’s config/middleware.py file, and add the following import at the end of the existing imports at the top of the file:
import authkit.authenticate
Then add this line:
app = authkit.authenticate.middleware(app, app_conf)
just before these lines and at the same indentation level:
# Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app) else: app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])
The authentication middleware has to be set up before the error documents middleware because you don’t want any 401 responses from the controllers being changed to error pages before the authentication middleware has a chance to present a sign-in facility to the user.
If you had set the full_stack option to false in the Pylons config file, you would need to add the AuthKit authenticate middleware before these lines; otherwise, it wouldn’t get added:
if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
Tip
You’ll remember from Chapter 16 that middleware is simply a component that sits between the server and the controller action that is being called and has an opportunity to change the response that the controller action returns.
Now that the authentication middleware is set up, you need to configure it. AuthKit is designed to be completely configurable from the Pylons config file and has a number of required options that tell AuthKit which authentication method you want to use and how AuthKit should check whether the username and password that have been entered are correct.
Add the following options to the end of the [app:main] section:
authkit.setup.method = form, cookie authkit.form.authenticate.user.data = visitor:open_sesame authkit.cookie.secret = secret string
These options set up AuthKit to use form and cookie-based authentication. This also sets up a user named visitor with the password open_sesame. These options will be passed to the authentication middleware via the app_conf argument.
At this stage, you can test that the middleware is set up and ready to be used. Create a new controller called auth:
$ paster controller auth
and add the following action:
def private(self): response.status = "401 Not authenticated" return "You are not authenticated"
If you visit, the 401 status will be returned and intercepted by the AuthKit middleware, and you will see the default sign-in screen for form and cookie authentication displayed at the same URL, as shown in Figure 18-1.
There is just one more change you need to make in order to properly test your authentication setup. At the moment, the private action always returns a 401 HTTP status code, even if a user is authenticated. This means the first time you sign in, you’ll see the error document for a 401 response, but on subsequent requests you’ll see the sign-in form again.
The authenticate middleware automatically adds a key to the environ dictionary named REMOTE_USER if a user is authenticated. The value of the key is the username of the authenticated user. Let’s use this fact to update the private() action so that a user can see the message once they are authenticated:
def private(self): if request.environ.get("REMOTE_USER"): return "You are authenticated!" else: response.status = "401 Not authenticated" return "You are not authenticated"
If you start the server and visit, you will now be able to sign in. If you sign in with the username and password you specified in the config file (visitor and open_sesame), you will see the message You are authenticated!. If you refresh the page, you will notice you are still signed in because AuthKit set a cookie to remember you.
To implement a facility for signing out, you will need to add this line to your config file:
authkit.cookie.signoutpath = /auth/signout
This tells AuthKit that when a user visits the URL, an HTTP header should be added to the response to remove the cookie. AuthKit doesn’t know what else should be included in the response, so you will also need to add a signout() action to the controller at that URL so that the visitor is not shown a 404 Not Found page when they sign out:
def signout(self): return "Successfully signed out!"
After you have restarted the server, you can test the sign-out process by visiting. If you use Firebug to look at the HTTP headers, you’ll notice AuthKit has added this to the response headers to sign you out:
Set-Cookie authkit=""; Path=/
Caution
Setting the header to remove the AuthKit cookie happens in the AuthKit middleware, after the response from the controller action. The controller action itself plays no part in the sign-out process, so it could return the text You are still signed in, but the user would still be signed out. More dangerously, if you entered an incorrect path for the authkit.cookie.signoutpath option, the user would still get a message saying they are signed out when they are actually still signed in. It is therefore very important that you enter the correct path in the authkit.cookie.signoutpath option.
By using the AuthKit middleware, you have been able to quickly implement a fully working authentication system, but so far you have had to perform the authorization by manually checking environ["REMOTE_USER"] to see whether there was a user signed in. AuthKit can help simplify authorization too.
Let’s start by looking at how the @authorize decorator can be used with AuthKit permission objects to protect entire controller actions.
Add the following imports to the top of the auth controller:
from authkit.authorize.pylons_adaptors import authorize from authkit.permissions import RemoteUser, ValidAuthKitUser, UserIn
Next change the private() action to look like this:
@authorize(RemoteUser()) def private(self): return "You are authenticated!"
This code is clearly a lot neater than what you had previously. If you sign out or clear your browser’s cookies, you’ll see it behaves exactly as it did before, allowing you to view the private message You are authenticated, but only after you have signed in.
In this example, the @authorize decorator simply prevents the action from being called if the permission check fails. Instead, it raises a PermissionError, which is derived from an HTTPException and is therefore converted either by Pylons or by AuthKit itself into a response with either a 401 status code or a 403 status code depending on whether the permission failed because of an authentication error or an authorization error. The response is then handled by the authentication middleware triggering a response, resulting in the sign-in screen you’ve just used.
The RemoteUser permission might not be the best permission to use in this case since it simply checks that a REMOTE_USER is set and could therefore potentially grant permission to someone who wasn’t in the list of users specified in the config file if some other part of the system were to set the REMOTE_USER environment variable. Instead, it might be better to use the ValidAuthKitUser permission, which does a similar thing but allows only valid AuthKit users. You imported the ValidAuthKitUser at the same time you imported RemoteUser, so you can use it like this:
@authorize(ValidAuthKitUser()) def private(self): return "You are authenticated!"
You can also use an AuthKit permission object named UserIn to specify that only certain users are allowed. Add another user to the config file like this:
authkit.form.authenticate.user.data = visitor:open_sesame nobody:password
Then change the way the permission is used like this:
@authorize(UserIn(["visitor"])) def private(self): return "You are authenticated!"
This time, even if you signed in as nobody, you would still not be authorized to access the action because the permission check will authorize only the user named visitor.
Tip
You don’t actually need to instantiate a permission in the decorator itself; you can also create a permission instance elsewhere and use it as many times as you like in different authorize() decorators.
You’ve now seen how to use the @authorize decorator to check permissions before an action is called, but there are actually two other ways of checking permissions that automatically raise the correct PermissionError if a permission check fails:
- The authorize middleware for protecting a whole WSGI application
- The authorized() function for checking a permission within a code block
Let’s look at these next.
To protect a whole application, you can use AuthKit’s authorization middleware. You need to set this up in your project’s config/middleware.py file before the authentication middleware to use it. If you set it up after the authentication middleware, any PermissionError raised wouldn’t get intercepted by the authentication middleware. Let’s test this on the AuthDemo project. First import the authorization middleware and ValidAuthKitUser permission at the end of the imports at the top of config/middleware.py:
import authkit.authorize from authkit.permissions import ValidAuthKitUser
Then set up the authorization middleware before the authentication middleware:
permission = ValidAuthKitUser() app = authkit.authorize.middleware(app, permission) app = authkit.authenticate.middleware(app, app_conf)
Now every request that comes through your Pylons application will require the user to be signed in as a valid AuthKit user. To test this, add a new action to the auth controller, which looks like this:
def public(self): return "This is still only visible when you are signed in."
Even though this doesn’t have an @authorize decorator, you still won’t be able to access it until you are signed in because of the presence of the authorization middleware. Try visiting to test it.
Caution
Using the authorization middleware in this way will protect only the WSGI applications defined above it in config/middleware.py. In this case, the middleware is set up above the Cascade, so any requests that are served by the StaticURLParser application will not be covered. This means that files served from your project’s public directory won’t be protected. You can protect them too by moving all the AuthKit middleware to below the Cascade in config/middleware.py.
Of course, sometimes you will want to be able to check a permission from within an action or a template. AuthKit provides a function for doing this too named authorized(). The function returns True if the permission check passes or False otherwise. If you comment out the authorization middleware you set up in config/middleware.py a few moments ago (leaving the authenticate middleware), you will be able to test this function:
# permission = ValidAuthKitUser() # app = authkit.authorize.middleware(app, permission) app = authkit.authenticate.middleware(app, app_conf)
First edit the auth controller to import the authorized() function:
from authkit.authorize.pylons_adaptors import authorized
Then update the public() action to look like this:
def public(self): if authorized(UserIn(["visitor"])): return "You are authenticated!" else: return "You are not authenticated!"
Using the authorized() function will never actually trigger a sign-in; if you want to trigger a sign-in, you either need to manually return a response with a status code of 401 like this:
def public(self): if authorized(UserIn(["visitor"])): return "You are authenticated!" else: response.status = "401 Not authenticated" return "You are not authenticated!"
or raise the appropriate permission error:
def public(self): if authorized(UserIn(["visitor"])): return "You are authenticated!" else: from authkit.permissions import NotAuthenticatedError raise NotAuthenticatedError("You are not authenticated!")
You can test this at.
Caution
Although all the permission objects that come with AuthKit can be used with the authorized() function, it is possible to create custom permissions that will not work. This is because permissions can perform checks on both the request and the response, and although the authorization decorator and authorization middleware both have access to the response, the authorized() function does not and so is not capable of performing checks on permissions that depend on the response.
Sometimes you might want to protect a controller rather than an individual action or an entire WSGI application. Since all Pylons controllers have a __before__() method, adding an @authorize decorator to __before__() is equivalent to protecting the entire controller.
For example:
class AuthController(BaseController): @authorize(ValidAuthKitUser()) def __before__(self): pass def public(self): return "This is still only visible when you are signed in."
So far, you have seen how to authenticate users and how to use permissions to authorize them, but the permissions you’ve used haven’t been very complicated.
One common and extremely flexible pattern used in many authorization systems is that of groups and roles. Under this pattern, each user can be assigned any number of roles that relate to tasks they might use the system for. They can also be a member of one group, usually a company or organization.
As an example, if you were designing a content management web site, you might choose the following roles:
Certain users might have more than one role, and others might not have any roles at all.
An appropriate use for groups would be when you give access to the same web site to users from different companies and each user is either from one company or the other. Of course, you could implement the same functionality by creating a role for each company and checking which role each user had, but using groups is simpler. If you find you need to assign more than one group to the same person, then you should be using roles, not groups.
Tip
The groups and roles pattern even works when conceptually you have more than one application to which each person should be assigned roles. You can append application names to the front of the roles so that, for example, intranet_editor is a role for an editor on an intranet application and website_editor is a role for an editor on a public-facing web site application.
You can specify AuthKit groups and roles in the configuration file along with the user information. Here is the configuration to set up roles for four users of our content management system:
authkit.form.authenticate.user.data = ben:password1 writer editor reviewer admin james:pasword2 writer graham:password3 writer reviewer philip:password4 editor reviewer
As you can see, user information is specified in the format username:password role1 role2 role3, and so on. Each new user is on a new line, and roles are separated by a space character. In this example, Ben and Philip are Editors; Ben, James, and Graham are Writers; Ben, Graham, and Philip are Reviewers; and Ben is the only Admin.
If our imaginary content management system was used by two web framework communities, it might be useful to be able to specify which community each user belonged to. You can do this using AuthKit’s group functionality:
authkit.form.authenticate.user.data = ben:password1:pylons writer editor reviewer admin simon:password5:django writer editor reviewer admin
As you can see, the group is specified after the password and before the roles by using another colon (:) character as a separator.
Caution
You have to be a little careful when using groups because your users can never be members of more than one group. In this instance, you would hope that people from both the Django and Pylons communities might contribute to each others’ projects, so in this instance it might be more appropriate to create two new roles, django and pylons, and assign the pylons role to Ben and the django role to Simon. Then, if at a later date Simon wants to work on Pylons, he can simply be assigned the pylons role too.
Groups and roles can be checked in a similar way to other permissions using the authorization middleware, the @authorize decorator, or the authorized() function.
The two important permissions for checking groups and roles are HasAuthKitRole and HasAuthKitGroup. They have the following specification:
HasAuthKitRole(roles, all=False, error=None) HasAuthKitGroup(groups, error=None)
The roles and groups parameters are a list of the acceptable role or group names. If you specify all=True to HasAuthKitRole, the permission will require that all the roles specified in roles are matched; otherwise, the user will be authorized if they have been assigned any of the roles specified. Here are some examples of using these permission objects:
from authkit.permissions import HasAuthKitRole, HasAuthKitGroup, And # User has the 'admin' role: HasAuthKitRole('admin') # User has the 'admin' or 'editor' role: HasAuthKitRole(['admin', 'editor']) # User has the both 'admin' and 'editor' roles: HasAuthKitRole(['admin', 'editor'], all=True) # User has no roles: HasAuthKitRole(None) # User in the 'pylons' group: HasAuthKitGroup('pylons') # User in the 'pylons' or 'django' groups: HasAuthKitGroup(['pylons', 'django']) # User not in a group: HasAuthKitGroup(None)
It is also possible to combine permissions using the And permission class. This example would require that the user was an administrator in the Pylons group:
And(HasAuthKitRole('admin'), HasAuthKitGroup('pylons'))
In addition to the permissions for roles and groups, AuthKit also comes with permission objects for limiting users to particular IP addresses or for allowing them to access the resource only at particular times of day:
# Only allow access from 127.0.0.1 or 10.10.0.1 permission = FromIP(["127.0.0.1", "10.10.0.1"]) # Only allow access between 6pm and 8am from datetime import time permission = BetweenTimes(start=time(18), end=time(8))
All the examples so far have been using the authkit.users.UsersFromString driver to extract all the username, password, group, and role information from the config file for use with the permission objects. If you had lots of users, it could quickly become unmanageable to store all this information in the config file, so AuthKit also comes with a number of other drivers.
The first driver you will learn about is the UsersFromFile driver from the authkit.users module. This driver expects to be given a filename from which to load all the user information. For example, if you stored your user information in the file C:\user_information.txt, you might set up your config file like this:
authkit.form.authenticate.user.type = authkit.users:UsersFromFile authkit.form.authenticate.user.data = C:/users_information.txt
The users_information.txt file should have the user data specified in the same format as has been used so far in this chapter with one user per line. For example:
ben:password1 writer editor reviewer admin james:pasword2 writer graham:password3 writer reviewer philip:password4 editor reviewer
Of course, you may want to perform checks on the users in your application code as well as on permissions. AuthKit allows you to do this too via a key in the environment called authkit.users, which is simply an instance of the particular instance class you are using.
You can use it like this:
>>> users = request.environ['authkit.users'] >>> users.user_has_role('ben', 'admin') True >>> users.user_has_group('ben', 'django') False >>> users.list_roles() ['admin', 'editor', 'reviewer', 'writer']
The full API documentation is available on the Pylons web site.
The AuthKit cookie-handling code supports quite a few options:
So, for example, to have a cookie that expires after 20 seconds with a cookie name test and the comment this is a comment, you would set these options:
authkit.cookie.secret = random string authkit.cookie.name = test authkit.cookie.params.expires = 20 authkit.cookie.params.comment = this is a comment
If you want a more secure cookie, you can add these options:
authkit.cookie.enforce = true authkit.cookie.includeip = true
The first option enforces a server-side check on the cookie expire time as well as trusting the browser to do it. The second checks the IP address too and will work only if the request comes from the same IP address the cookie was created from.
AuthKit’s default cookie implementation is based on the Apache mod_auth_tkt cookie format. This means the cookie itself contains the username of the signed-in user in plain text. You can set another option called authkit.cookie.nouserincookie if you’d prefer AuthKit used a session store to hold the username, but this option breaks compatibility with mod_auth_tkt and means you have to move the AuthKit authentication middleware to above the SessionMiddleware in your project’s config/middleware.py file so that AuthKit can use the Beaker session.
authkit.cookie.nouserincookie = true
So far, our discussion about authentication, groups, and roles has centered around AuthKit’s User Management API. AuthKit also provides six ways of authenticating users including HTTP basic and digest authentication, and of course, it provides APIs for implementing your own authentication method. To use one of the alternative authentication methods, you just need to change the AuthKit options in your config file.
As an example, to use HTTP digest authentication, you could change the AuthKit options in your config file to look like this:
authkit.setup.method = digest authkit.digest.authenticate.user.data = visitor:open_sesame authkit.digest.realm = 'Test Realm'
Now when you access a controller action that causes a permission check to fail, the browser will display an HTTP digest dialog box prompting you to sign in. Once you are signed in, you will be able to access the controller action as before. The process of handling the sign-in and setting the REMOTE_USER variable is done automatically for you by AuthKit as before, so the rest of your application can remain unchanged.
AuthKit has similar setups for HTTP basic authentication and OpenID authentication and also has other plug-ins that can redirect users to a URL to sign in or forward the request to a controller inside your Pylons application.
As you’ll remember from Chapter 12, creating functional tests for key controllers is highly recommended. If your controller actions are protected by AuthKit, you will need to emulate a user being signed in by setting the REMOTE_USER environment variable when setting up your tests. Here’s how to set up a user called james by passing the extra_environ argument when using the get() method to simulate a GET request:
from authdemo.tests import * class TestAuthController(TestController): def test_index(self): response = self.app.get( url(controller='auth', action='public'), extra_environ={'REMOTE_USER':'james'} ) # Test response... assert "you are signed in" in response.body
Alternatively, AuthKit 0.4.1 supports two further options for helping you handle tests:
authkit.setup.enable = false authkit.setup.fakeuser = james
The first of these options completely disables the AuthKit authenticate middleware and makes all the authorization facilities return that the permission check passed. This enables you to test your controller actions as though AuthKit wasn’t in place. Some of your controller actions might expect a REMOTE_USER environment variable, so this is set up with the value of the authkit.setup.fakeuser option, if it is present. Both these options should be used only in test.ini and never on a production site.
How useful the previous options are depends on the complexity of your setup. For more complex setups, you are likely to want to specify environment variables on a test-by-test basis using the extra_environ argument.
Caution
Always remember to set authkit.setup.enable = true on production sites; otherwise, all authentication is ignored and authorization checks always return that the user has the appropriate permission. Although useful for testing, this makes all your controller actions public, so it is not a good idea on a production site.
So far, everything we have discussed has been around how to authenticate a user and check their permissions in order to authorize them to perform certain actions. A very important aspect of this is making sure the authentication is secure and that no one can get hold of the usernames and passwords your users use. Security as a whole is a huge topic on which many books have been written, but you can take three steps to greatly reduce the risk of an intruder obtaining a user’s username and password:
- Ensure other users of the system cannot read passwords from your Pylons config file. This is especially relevant if you are deploying your Pylons application in a shared hosting environment where other users of the system might be able to read database passwords and other information from your development.ini file.
- Ensure a user never sends their password in any form over an unencrypted connection such as via e-mail or over HTTP.
- Never directly store a user’s password anywhere in your system.
If you are using a form and a cookie or HTTP basic authentication, then the user’s password is transmitted in plain text to the server. This means that anyone on the network could potentially monitor the network traffic and simply read the username and password. It’s therefore important that on a production site using these authentication methods you set up a secure connection for the authentication using Secure Sockets Layer (SSL) to encrypt the communication between the browser and server during authentication.
Even HTTP digest authentication, which does use some encryption on the password, isn’t particularly secure because anyone monitoring the network traffic could simply send the encrypted digest and be able to sign onto the site themselves, so even if you are using digest authentication, it is worth using SSL too.
To set up an SSL certificate, you need two things:
- A private key
- A certificate
The certificate is created from a certificate-signing request that you can create using the private key.
The private key can be encrypted with a password for extra security, but every time you restart the server, you will need to enter the password. The certificate-signing request (CSR) is then sent to a certificate authority (CA) that will check the details in the certificate-signing request and issue a certificate. Anyone can act as a certificate authority, but most browsers will automatically trust certificates only from the main certificate authorities. This means that if you choose a lesser-known certificate authority or you choose to sign the certificate yourself, your users will be shown a warning message asking them whether they trust the certificate.
For production sites, you should always choose one of the major certificate authorities such as VeriSign or Thawte because virtually all browsers will automatically trust certificates issued by them. CAcert.org is an initiative to provide free certificates, but these are not trusted by all commonly used browsers yet.
On a Linux platform with the openssh package installed, you can run the following command from a terminal prompt to create the key:
$ openssl genrsa -des3 -out server.key 1024
You’ll see output similar to the following:
Generating RSA private key, 1024 bit long modulus .....................++++++ .................++++++ unable to write 'random state' e is 65537 (0x10001) Enter pass phrase for server.key:
If you want to use a key without a passphrase, you can either leave out the -des3 option or create an insecure version from the existing key like this:
$ openssl rsa -in server.key -out server.key.insecure
You should keep the private key server.key private and not send it to anyone else.
Once you have a key, you can use it to generate a certificate-signing request like this:
$ openssl req -new -key server.key -out server.csr
The program will prompt you to enter the passphrase if you are using a secure key. If you enter the correct passphrase, it will prompt you to enter your company name, site name, e-mail, and so on. Once you enter all these details, your CSR will be created, and it will be stored in the server.csr file. The common name you enter at this stage must match the full domain name of the site you want to set up the certificate for; otherwise, the browser will display a warning about a domain mismatch. It is worth checking with the certificate authority about the exact details it requires at this stage to ensure the CSR you generate is in the format required by the certificate authority.
Now that you have your certificate-signing request server.csr, you can send it to the certificate authority. The CA will confirm that all the details you’ve entered are correct and issue you a certificate that you can store as server.crt.
If you want to sign the certificate yourself, you can do so with this command:
$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Caution
If you are planning on using your secure server in a production environment, you probably need a CA-signed certificate. It is not recommended to use self-signed certificates because of the warnings the browser will show the user.
Now that you have your private key and the certificate, you can use them to set up your server. How to set up SSL depends on the server you are using to deploy your Pylons application. You should consult your server’s documentation for more information.
Note
If you are using Apache, there is a good entry in the Pylons Cookbook describing how to set up SSL. You can find it at.
The Pylons server (started with the paster serve command) also supports SSL as long as you install the pyOpenSSL package. The Paste HTTP server requires the certificate and the private key to be added to the same file, so if you want to use your certificate and the key you generated earlier, you need to create a server.pem file like this:
$ cat server.crt server.key > server.pem $ chmod 400 server.pem
Edit your project’s development.ini file, and change the [server:main] section so it uses the following options:
[server:main] host = 127.0.0.1 ssl_pem = server.pem port = 443
Port 443 is the default port for HTTPS. If you restart the server and visit, you should be able to access your Pylons application. You’ll need the pyOpenSSL package installed though. Make sure the URL starts with https and not http; otherwise, you won’t be able to connect to your Pylons application. Also make sure you change the host to 0.0.0.0 if you want to be able to access the server from a different machine on the network.
As was mentioned earlier, it is a good idea never to store users’ passwords anywhere on your system in case the worst happens and someone breaks in and steals that information. One way to avoid this is to set up a function to encrypt the passwords before they are stored. One drawback to this approach is that if the user forgets their password, you are not able to send them a reminder by e-mail because you do not ever store the original password. Instead, you have to randomly generate a new password for them and send them an e-mail asking them to sign in with the new password and then change the password to something more memorable.
You can set up encrypted passwords with form authentication by adding the following to your AuthKit config:
authkit.setup.method = form, cookie authkit.cookie.secret = secret string authkit.form.authenticate.user.data = visitor:9406649867375c79247713a7fb81edf0 authkit.form.authenticate.user.encrypt = authkit.users:md5 authkit.form.authenticate.user.encrypt.secret = some secret string
The authkit.form.authenticate.user.encrypt.secret option allows you to specify a string that will be used to make the password encryption even harder to break.
Once this option is enabled, you will need to manually convert all existing passwords into their encrypted forms. Here is a simple program that converts the passwords you have used so far in this chapter into their encrypted forms using the secret "some secret string". As you can see the encrypted password in the previous example corresponds to password1:
from authkit.users import md5 passwords = [ 'password1', 'password2', 'password3', 'password4', 'password5', ] for password in passwords: print md5(password, "some secret string")
The result is as follows:
9406649867375c79247713a7fb81edf0 4e64aba9f0305efa50396584cfbee89c aee8149aca17e09b8a741654d2efd899 2bc5a9b5c05bb857237d93610c98c98f 873f0294070311a707b941c6315f71f8
You can try replacing the passwords in the config file with these passwords. As long as you set the config options listed here, everything should still work without the real passwords being stored anywhere. This is more secure because an attacker would still need the original password in order to sign in, even if they knew the encrypted version.
Although the tools and techniques you’ve learned about in this chapter will enable you to write fairly advanced authorization and authentication systems that will be adequate for a lot of cases, you may sometimes need to do things slightly differently. AuthKit also supports custom authentication functions and a SQLAlchemy driver for storing the user information.
In the next chapter, you’ll apply some of the knowledge you’ve gained in this chapter to the SimpleSite application you’ve been working on throughout the book, and you’ll see some more techniques involving AuthKit, including how it integrates with SQLAlchemy and how to use a template to give the sign-in screen a theme.
Chapter 17: Pylons’ Internal Architecture
Chapter 19: SimpleSite Tutorial Part 3
Enter search terms or a module, class or function name. | https://thejimmyg.github.io/pylonsbook/en/1.1/authentication-and-authorization.html | CC-MAIN-2017-39 | refinedweb | 6,096 | 51.28 |
This action might not be possible to undo. Are you sure you want to continue?
4)
JavaBeat Home SCJP 1.4 Home Objectives Forums Mock Exams Online Mock Exam Resources
Mock Exams MockQuestions MockQuestions MockQuestions MockQuestions MockQuestions 1 5 9 13 17 MockQuestions MockQuestions MockQuestions MockQuestions MockQuestions 2 6 10 14 18 MockQuestions MockQuestions MockQuestions MockQuestions MockQuestions 3 7 11 15 19 MockQuestions MockQuestions MockQuestions MockQuestions MockQuestions 4 8 12 16 20? Select 1 correct option
(1) false false true false true (2) false true true false true (3) true true true true true (4) true true true false true (5) None of the above
Answer : -------------------------
2 Any class may be unloaded when none of it's instances and class objects that represent this class are
reachable. True Or False?
(1) True (2) False
Answer : -------------------------?
(1) True (2) False
Answer : -------------------------; } }
Select 1 correct option
(1) The progarm will fail to compile (2) Class cast exception at runtime (3) It will print 30, 20 (4) It will print 30, 30 (5) It will print 20, 20
Answer : -------------------------
5 The following code snippet will print true.
String str1 = "one"; String str2 = "two"; System.out.println( str1.equals(str1=str2) );
(1) True (2) False
Answer : -------------------------
6 Which of the following statements are true? (1) An anonymous class cannot be inherited (2) An anonymous class may extend another class (3) An anonymous class may not create and start a Thread (4) An anoymous class may not declare a constructor
Answer : -------------------------
7 Given:); } }
What will be the output of the following program? Select 1 correct option.
(1) It will throw NullPointerException when run (2) It will not compile (3) It will print 2 and then will throw NullPointerException (4) It will print 2 and null (5) None of the above
Answer : -------------------------
8 Which of the following statements about NaNs are true ? (1) Float.NaN == Float.NaN (2) Float.NaN == Double.NaN (3) Float.NaN >= 0 (4) Float.NaN < 0 (5) None of the above
Answer : -------------------------
9
What is the result of executing the following fragment of code:
boolean b1 = false; boolean b2 = false; if (b2 != b1 = !b2) {
System.out.println("true"); } else { System.out.println("false"); }
Select 1 correct option
(1) Compile time error (2) It will print true (3) It will print false (4) Runtime error (5) It will print nothing
Answer : -------------------------
10 Given two collection objects referenced by c1 and c2, which of these statements are true?
Select 2 correct options
(1) c1.retainAll(c2) will not modify c1 (2) c1.removeAll(c2) will not modify c1 (3) c1.addAll(c2) will return a new collection object, containing elements from both c1 and c2 (4) For: c2.retainAll(c1); c1.containsAll(c2); 2nd statement will return true (5) For: c2.addAll(c1); c1.retainAll(c2); 2nd statement will have no practical effect on c1
Answer : -------------------------
11 What happens when the following code gets executed:
class TechnoSample { public static void main(String[] args) { double d1 = 1.0; double d2 = 0.0; byte b =1; d1 = d1/d2; b = (byte) d1; System.out.print(b); } }
(1) It results in the throwing of an ArithmeticExcepiton
(2) It results in the throwing of a DivedeByZeroException (3) It displays the value 1.5 (4) It displays the value –1
Answer : -------------------------
12
Class finalization can be done by implementing the following method: static void classFinalize() throws Throwable; True Or False?
(1) True (2) False
Answer : -------------------------?
Options Select 1 correct option
(1) The second thread should call getLocks(obj2, obj1) (2) The second thread should call getLocks(obj1, obj2) (3) The second thread should call getLocks() only after first thread exits out of it (4) The second thread may call getLocks() any time and passing parameters in any order (5) None of the above
Answer : -------------------------
14 Which of these statements concerning nested classes and interfaces are true?
Select 3 correct options
(1) An instance of a top-level nested class has an inherent outer instance (2) A top-level nested class can contain non-static member variables (3) A top-level nested interface can contain static member variables (4) A top-level nested interface has an inherent outer instance associated with it (5) For each instance of the outer class, there can exist many instances of a non-static inner class
Answer : -------------------------
15 Given the following definition of class, which member variables are accessible from OUTSIDE the package
com.technopark?
package com.technopark; public class TestClass { int i; public int j; protected int k; private int l; }
Select 2 correct options
(1) Member variable i (2) Member variable j (3) Member variable k (4) Member variable k, but only for subclasses (5) Member variable l
Answer : -------------------------
16 Which of the following are wrapper classes for primitive types?
Select 1 correct option
(1) java.lang.String (2) java.lang.Void (3) java.lang.Null
(4) java.lang.Object (5) None of the above
Answer : -------------------------
17 Which of the following statements are true? Select 2 correct options. (1) Private methods cannot be overriden in subclasses (2) A subclass can override any method in a non-final superclass (3) An overriding method can declare that it throws a wider spectrum of exceptions than the method it is
overriding overriding clause
(4) The parameter list of an overriding method must be a subset of the parameter list of the method that it is (5) The over riding method may opt not to declare any throws clause even if the original method has a throws
Answer : -------------------------
18 Will the following code compile ? If yes , what is the output ?
class sample { sample(int i){ System.out.println(i); this.i = i; } public static void main(String args[]){ sample object = new sample(10); } }
(1) 0 (2) 10 (3) null (4) Compile error "sample.java:10: No variable i defined in class sample"
Answer : -------------------------
1] 4 Explanation: A class or interface may be unloaded if and only if its class loader is unreachable (the definition of unreachable is given in JLS 12.6.1). Classes loaded by the bootstrap loader are not unloaded. (credit:) ****
3] 2 Explanation: First the value of str1 is evaluated (ie. one). Now, before the method is called the operands are evaluated, so str1 becomes "two". so "one".equals("two") is false. ****
6] 1,2,4 Explanation: NaN is unordered, so a numeric comparison operation involving one or two NaNs always returns false and any != comparison involving NaN returns true, including x != x when x is NaN. ****
9] 1 Explanation: Note that, boolean operators have more precedence than =. (In fact, = has least precedenace) so, in (b2 != b1 = !b2) first b2 != b1 is evaluated which returns a value 'false'. Explanation: 1.0/0.0 results in Double.POSITIVE_INFINITY. Double.POSITIVE_INFINITY is converted to Integer.MAX_VALUE ('0' followed by 31 '1's). Integer.MAX_VALUE is then cast to byte value, which simply takes the last 8 bits(11111111) and is -1. ****
12] 2 Explanation: (1) This may result in a deadlock (3) The is not necessary. Option 2 works just fine ****
14] 2,3,5 Explanation: (source:) ****
JavaBeat 2005, India () Submit a Site - Directory - Submit Articles
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/376833/Java-mock-tests-for-SCJP | CC-MAIN-2016-40 | refinedweb | 1,223 | 61.87 |
make a code block use 3 or more tildes (~) or backticks (`) on a line before and after the text (syntax details)., with ways to tell the highlighter what language to use for the code block.
The language will be detected automatically, if possible. Or you can specify it on the first line with 3 colons and the language name.
:::python import abc
Output:
import abc
If the first line of the codeblock contains a shebang, the language is derived from that and line numbers are used. If shebang line contains a full path, it will be included in the output. If it does not contain a path (a single / or even a space), then that shebang line will be omitted from output.
#!/usr/bin/python import abc
Output:
If using a code block of tildes or backticks, you can also specify the language on the first divider line
~~~html <a href="#">My code</a> ~~~
```html <a href="#">My code</a> ```
Output:
<a href="#">My code</a>
Many languages are supported. See all the "short names" listed in the Pygments docs. | https://sourceforge.net/p/timeslottracker/support-requests/markdown_syntax | CC-MAIN-2017-22 | refinedweb | 180 | 77.47 |
The main idea is to set up some arrays keep the place that has been occupied by queen and use a backtracking method to get all solutions.
import java.util.Arrays; public class Solution { public static void main(String[] args) { System.out.print(new Solution().totalNQueens(8)); } static int result = 0; public int totalNQueens(int n) { int[] row = new int[n];/*row represent the row which has been occupied*/ int[] col = new int[n];/*col represent the col which has been occupied*/ int[] biasl = new int[2*n-1]; int[] biasr = new int[2*n-1];/*biasl and biasl represent the bials which have been occupied*/ Arrays.fill(row, 0); Arrays.fill(col, 0); Arrays.fill(biasl, 0); Arrays.fill(biasr, 0);/*initiate all arrays*/ launch(row, col, biasl, biasr, 0,n); return result; } private void launch(int[] row, int[] col, int[] biasl, int[] biasr, int x,int n) { /*x represents the row which should been put in queen*/ for(int j = 0;j < n;j++) { if(row[x] == 1 || col[j] == 1 || biasl[x+j] == 1 || biasr[x-j+n-1] == 1) { /*if there's a queen has occupied the row or col or bias,then continue*/ continue; } else if(x == n-1) { /*if it's the last row,we have get one validate solution*/ result++; } else { row[x] = 1; col[j] = 1; biasl[x+j] = 1; biasr[x-j+n-1] = 1; launch(row, col, biasl, biasr, x+1,n); row[x] = 0; col[j] = 0; biasl[x+j] = 0; biasr[x-j+n-1] = 0; /*backtracking*/ } } } } | https://discuss.leetcode.com/topic/5111/my-code-is-correct-in-eclipse-but-it-is-wrong-when-i-put-it-to-oj | CC-MAIN-2017-43 | refinedweb | 259 | 52.53 |
26 May 2011 14:41 [Source: ICIS news]
LONDON (ICIS)--European polyethylene terephthalate (PET) prices are still decreasing but the market is likely to see less price volatility after a period of huge swings, sources said on Thursday.
“The speculative bubble has been broken,” one PET customer said, echoing comments made by other buyers and sellers.
This was likely to lead to a more stable environment, they added.
Prices adopted an unusual pattern during the first part of 2011, when they increased in the low season before decreasing just as the high season began.
During the slow winter months, domestic PET prices leapt by more than €300/tonne ($423/tonne) to €1,650/tonne FD (free delivered) ?xml:namespace>
A series of force majeure declarations on upstream purified terephthalic acid (PTA) hampered PET production to such an extent that Spain’s Artenius declared force majeure at its European PET plants and other producers went on allocation.
To secure volumes, customers risked importing additional material from Asia and the
“There are a lot of imports coming in,” one producer said.
Decreasing feedstock prices and a collapse in Asian values has sent European PET prices tumbling during the busy preparation period for bottlers.
PET availability is currently more manageable, too, and domestic prices have fallen into the €1,400s/tonne. European spot slipped just below this, while freely-negotiated domestic prices are recorded either side of €1,450/tonne.
A second customer said European producers have finally woken up and would like to match the import prices.
A large spread of PET import prices were reported, depending on the timing of each import purchase and which exchange rate was used. Imports are in the €1,290–1,450/tonne range between May and July. The later the arrival date, the lower the price.
“I doubt customers are booking a lot [of imports] now because they are afraid [of prices falling further],” a second producer said.
Bearish fundamentals behind decreasing demand for PTA in
“PTA Asia is probably the answer to why we have got imports excited again. But with the dollar strengthening, I do feel the market will show [some bounce back],” the second producer said.
Cotton prices soared and this pushed up demand for PET textile applications, particularly in
“[The cotton price] is still high but is more linked to market availability than to speculation,” one customer explained.
The market awaits news from the summer cotton harvest in
“There is no time pressure to buy. We are comfortable about the volumes on the way or being offered. We are all waiting,” the second customer said.
Speculation caused prices to rise more than necessary in early spring. Then a slump in demand for textiles in
“I don’t see it lasting long because people will need to buy clothes eventually. In June and July there will be a new trend, either up or down, because of the cotton crops,” he surmised.
($1 = €0.71)
For more on PET and PTA, visit ICIS chemical | http://www.icis.com/Articles/2011/05/26/9463752/europe-pet-market-expects-more-stability-after-huge.html | CC-MAIN-2014-42 | refinedweb | 501 | 60.35 |
You can use q[./] instead of \'./\' (especially useful so that it will work on both Windows and Unix
But in this case it is even better to use -I and -M p6 -I. -MRunNoShell -e '( my $a, my $b ) = RunNoShell::RunNoShell("ls *.pm6"); say $a;' On Sun, Jun 3, 2018 at 4:47 PM, ToddAndMargo <[email protected]> wrote: >>> On Sun, Jun 3, 2018 at 5:28 PM ToddAndMargo <[email protected] >>> <mailto:[email protected]>> wrote: >>> >>> Hi All, >>> >>> What am I doing wrong here? >>> >>> >>> $ p6 'lib \'./\'; use RunNoShell; ( my $a, my $b ) = >>> RunNoShell::RunNoShell("ls *.pm6"); say $a;' >>> >>> bash: syntax error near unexpected token `=' >>> >>> Huh ??? >>> >>> >>> This is RunNoShell.pm6 >>> >>> sub RunNoShell ( $RunString ) is export { >>> ... >>> return ( $ReturnStr, $RtnCode ); >>> } >>> >>> Many thanks, >>> -T > > > On 06/03/2018 02:36 PM, Brandon Allbery wrote: >> >> bash doesn't like nested single quotes, even with escapes. So the first \' >> gave you a literal backslash and ended the quoted part, then the second \' >> gave you a literal ' and continued without quoting. The final ' would then >> open a new quoted string, but bash doesn't get that far because it sees the >> (now unquoted) parentheses and tries to parse them as a command expansion. >> >> allbery@pyanfar ~/Downloads $ echo 'x\'y\'z' >> > ^C >> >> Note that it thinks it's still in a quoted string and wants me to >> continue. >> > > p6 does not like `lib ./`, meaning use the current directory > without the single quotes. Any work around? | https://www.mail-archive.com/[email protected]/msg04967.html | CC-MAIN-2019-18 | refinedweb | 238 | 67.15 |
Makes a symbolic link to a file.
Standard C Library (libc.a)
#include <unistd.h> int symlink (Path1, Path2) const char *Path1; const char *Path2;
The symlink subroutine creates a symbolic link with the file named by the Path2 parameter, which refers to the file named by the Path1 parameter.
As with a hard link (described in the link subroutine),. In addition, a symbolic link can cross file system boundaries.
When a component of a path name refers to a symbolic link rather than a directory, the path name contained in the symbolic link is resolved. If the path name in the symbolic link starts with a / (slash), it is resolved relative to the root directory of the process. If the path name in the symbolic link does not start with / (slash), it is resolved relative to the directory that contains the symbolic link.
If the symbolic link is not the last component of the original path name, remaining components of the original path name are resolved from the symbolic-link point.
If the last component of the path name supplied to a subroutine refers to a symbolic link, the symbolic link path name may or may not be traversed. Most subroutines always traverse the link; for example, the chmod, chown, link, and open subroutines. The statx subroutine takes an argument that determines whether the link is to be traversed.
The following subroutines refer only to the symbolic link itself, rather than to the object to which the link refers:
Since the mode of a symbolic link cannot be changed, its mode is ignored during the lookup process. Any files and directories referenced by a symbolic link are checked for access normally.
Upon successful completion, the symlink subroutine returns a value of 0. If the symlink subroutine fails, a value of -1 is returned and the errno global variable is set to indicate the error.
The symlink subroutine fails if one or more of the following are true:
The symlink subroutine can be unsuccessful for other reasons. See "Base Operating System Error Codes For Services That Require Path-Name Resolution" for a list of additional errors.
This subroutine is part of Base Operating System (BOS) Runtime.
The chown, fchown, chownx, or fchown subroutine, link subroutine, mkdir subroutine, mknod subroutine, openx, open, or create subroutine, readlink subroutine, rename subroutine, rmdir subroutine, statx subroutine, unlink subroutine.
The ln command.
The limits.h file.
Files, Directories, and File Systems for Programmers in AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs. | https://sites.ualberta.ca/dept/chemeng/AIX-43/share/man/info/C/a_doc_lib/libs/basetrf2/symlink.htm | CC-MAIN-2022-40 | refinedweb | 420 | 62.38 |
Opened 4 years ago
Closed 17 months ago
#23222 closed Bug (wontfix)
Empty BinaryField != b'' on Python 2
Description (last modified by )
Problem
In Python 2, at least under SQLite, the initial value for an empty binary field behaves inconsistently. The ORM thinks it's an empty
bytes:
b''. The database connection manager thinks it's a buffer. Now, the buffer evaluates to
False and has zero length. So it'll mostly work. But not always -- and most importantly to me, not in my unit tests!
See
Note this was not a problem under Python 3.4.
Steps to Reproduce
Using Python 2.7.8, SQLite, and either Django 1.7rc2 or Django @ edcc75e5ac5b9dc2f174580e7adacd3be586f8bd (HEAD at the time of this writing; the error exists in both places)
- Make a new project and a new app and add the app to settings.py
- Fill in
app/models.pyas follows
from django.db import models class BinModel(models.Model): data = models.BinaryField()
- Run from the command line:
(venv) $ ./manage.py makemigrations app && ./manage.py migrate && ./manage.py shell
- Run from the resulting Python shell
>>> from app import models; m = models.BinModel(); m.save(); n = models.BinModel.objects.get() >>> m.data '' >>> m.data == b'' True >>> n.data <read-write buffer ptr 0x10eaa62b0, size 0 at 0x10eaa6270> >>> n.data == b'' False >>> bool(n.data) False >>> len(n.data) 0 >>> bytes(n.data) ''
Note that the same problem persisted when I had a default value for the field. There was no problem under Python 3.4.
Change History (9)
comment:1 Changed 4 years ago by
comment:2 Changed 4 years ago by
I dont think it's SQLite related, I have the same output using PostgreSQL
comment:3 Changed 4 years ago by
comment:4 Changed 4 years ago by
Marking this as accepted per previous comments.
This seem like it might be caused by six using buffers on python 2 [1].
Thanks.
[1]
comment:5 Changed 3 years ago by
I'm not sure, if it's only a problem with empty BinaryField.
I try to add a test function in model_fields.tests.BinaryFieldTests, as below:
def test_retrieve_compare_non_empty_field(self): dm = DataModel(data=b'test') self.assertTrue(dm.data == b'test') dm.save() dm = DataModel.objects.get(pk=dm.pk) self.assertTrue(dm.data == b'test')
On python2, the first assertion will be passed, and the second one will be failed.
As the data field is a buffer type after retrieving, we can't do a simple compare.
We can see the definition:
class BinaryField(Field): ... def get_db_prep_value(self, value, connection, prepared=False): value = super(BinaryField, self).get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value
I can't go further as I know little about six, and hope this can help:)
comment:6 Changed 3 years ago by
comment:7 Changed 3 years ago by
comment:8 Changed 2 years ago by
comment:9 Changed 17 months ago by
Closing due to the end of Python 2 support in master in a couple weeks.
I'm seeing the same behavior on django 1.6.0 and stable/1.6.x, so I don't think this is a release blocker. | https://code.djangoproject.com/ticket/23222 | CC-MAIN-2018-22 | refinedweb | 534 | 60.61 |
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
Haskell Spacegoo
Using this library you can quickly create code to take part in a game of Rocket Scissor Spacegoo; see for more details on the game.
To install this library, just call
cabal install haskell-spacegoo (and
apt-get install cabal-install first if required). Then you can write your
Haskell clients.
Here is a minimal example, that just sends all ships from one planet to an enemy planet:
import Game.Spacegoo import Data.List (find) main = client 8000 "spacegoo.rent-a-geek.de" "username" "password" myStrategy myStrategy s = do aPlanet <- find (\p -> planetOwner p == me s) (planets s) otherPlanet <- find (\p -> planetOwner p == he s) (planets s) return (planetId aPlanet, planetId otherPlanet, planetShips aPlanet)
See the documentation of the
Game.Spacegoo
modules for more information on how to write strategies, and for more examples. | https://bitbucket.org/nomeata/haskell-spacegoo | CC-MAIN-2017-26 | refinedweb | 159 | 56.35 |
Cheers bud, once i know how to do 2d arrays i should be fine :)
Type: Posts; User: jonathanfox
Cheers bud, once i know how to do 2d arrays i should be fine :)
The whole coordinate shit and how you populate certain areas on you 2d array with integers or characters, like say im doing a sudoku puzle, how the hell do i populate the grid with random numbers in...
think i know what im doing wrong now, when i use a method i create i never make a new object that uses the method, hopefully that made sense
Hey guys, hows it goin
im pretty new to java and programming, ive gotten better at writing methods individualy, however if i get a big project that uses a good few methods and within other methods...
hey left it a day and came to it and finally solved it thanks guys :D
ive been thinking about this and i think i know a way, but is a function the same as a method? could i return a method ? or do i sound really stupid haha
i know i should return the second list aswell put im not sure how to theres a lot of small things in java i have to learn
import java.util.ArrayList;
public class Split
{
private ArrayList<Integer> numbers;
public Split()
{
numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(5);
o ya sry stupid mistake, but how do i split the list in two? id say ill hav to make another two lists?
Hey everyone im stuck on a java problem and i could use some help
public class Split
{
private ArrayList<Integer> numbers;
public Split()
{
numbers = new ArrayList<Integer>();...
it works :D, thought the answer for it was way too easy but screw it it does what its supposed too, thanks guys
okay first of all how do i post my code neatly like yours and ill show u the question we were given, ur code is hard to understand cus im terrible at java, and i didnt post all the code.
In a...
I tried doing that but when i made two sets and gave them values and tried to use the method , it said "cannot return value that is void"
for(int i=0;i<entries.size();i++){
//if it has java or the correct answer it will say its valid
// if not it will remove the element from the array
if(entries.get(i).contains("java")){
...
public class match
{
public int match(Set<Integer> myNumbers, Set<Integer> winningNumbers)
{
myNumbers.retainAll(winningNumbers);
return myNumbers.size();
}
}
hey guys im here cus i need some extra help with java to pass my first year of college | http://www.javaprogrammingforums.com/search.php?s=b2d8ec8e7541332a4b5088ce8f7ff366&searchid=203504 | CC-MAIN-2016-30 | refinedweb | 450 | 59.77 |
pyt 0.7.1
easily run python unit tests
=============================================
Pyt's goal is to make writing and running Python unit tests fun and easy
:)
Currently, there are two main components, the ``pyt`` command line test
runner, and the ``Assert`` class
pyt testrunner
--------------
So here was my problem, I would work on big Python projects, and I would
be adding a new python file to a module in this big project, for
example, my new file might be something like this:
::
/project/foo/bar/che/baz/newmodule.py
I would be adding the ``Happy`` class with a ``sad`` method to
``newmodule`` and I would want to test it, so I would then have to add a
test for it:
::
/project/test/foo/bar/che/baz/newmodule_test.py
Then I would want to test my new class method:
::
$ python -m unittest test.foo.bar.che.baz.newmodule_test.HappyTestCase.test_sad
This got really annoying! Everytime, I would have to remember the syntax
to call unittest from the command line, and then I would have to
remember what I named the test case (let's see, was that
``HappyTestCase`` or ``HappyTest``), so I decided to take a bit of time
and simplify it, that's when ``pyt`` was born.
With ``pyt``, I just need to remember what I'm working on:
::
$ pyt Happy.sad
and ``pyt`` will do the rest, it will check every test module it finds
in the working directory and see if it has a Happy test case with a
``test_sad`` method. No more having to remember the unittest syntax, no
more typing long test paths. Hopefully, if tests are easy to run, I'll
write more of them.
More examples
~~~~~~~~~~~~~
Continuing the above example
To run all the ``Happy`` tests:
::
$ pyt Happy
To run all the ``newmodule`` tests:
::
$ pyt newmodule
To run more than one test:
::
$ pyt test1 test2 ...
Things to be aware of
~~~~~~~~~~~~~~~~~~~~~
- ``pyt`` uses Python's `PEP
8 <http:"" dev="" peps="" pep-`__ style conventions to
decide what is the module and class, so, given input like this:
::
$ pyt foo.bar.Baz.che
``pyt`` will consider ``foo.bar`` to be modules, ``Baz`` to be a
class because it starts with a capital letter, and ``che`` to be a
method since it comes after a class.
- ``pyt`` can fail on vague input and will run the first satisfactory
test it finds, so if you have:
::
/project
__init__.py
/user.py
/foo/
__init__.py
user.py
and you want to run tests for ``foo.user`` and you run:
::
$ pyt user
it will run the first ``user_test`` it finds, even if you meant a
different one, the solution is to just be more verbose when you have
to be:
::
$ pyt foo.user
pyt Assert
----------
This is a helper class designed to make writing assert statements in
your test cases a lot more fluid:
.. code:: python
from pyt import Assert
v = 5
a = Assert(v)
a == 5 # assertEqual(v, 5)
a != 5 # assertNotEqual(v, 5)
a > 5 # assertGreater(v, 5)
a >= 5 # assertGreaterEqual(v, 5)
a < 5 # assertLess(v, 5)
a <= 5 # assertLessEqual(v, 5)
+a # self.assertGreater(v, 0)
-a # self.assertLess(v, 0)
~a # self.assertNotEqual(v, 0)
v = "foobar"
a = Assert(v)
"foo" in a # assertIn("foo", v)
"foo not in a # assertNotIn("foo", v)
a % str # assertIsInstance(v, str)
a % (str, unicode) # to use multiple, put them in a tuple
a ^ str # assertNotIsInstance(v, str)
a / regex # assertRegexpMatches(v, re)
a // regex # assertNotRegexpMatches(v, re)
# assertRaises(ValueError)
with Assert(ValueError):
raise ValueError("boom")
a == False # assertFalse(v)
a == True # assertTrue(v)
a * 'foo', 'bar' # assert foo and bar are keys/attributes in v
a ** {...} # assert v has all keys and values in dict
a *= 'foo', 'bar' # assert foo and bar are the only keys in v
a **= {...} # assert v has only the keys and values in dict
a.len == 5 # assertEqual(len(v), 5)
# it even works on attributes and methods of objects
o = SomeObject()
o.foo = 1
a = Assert(o)
a.foo == 1
a.bar() == "bar return value"
Installation
------------
Use ``pip``:
::
$ pip install pyt
You can also get it directly from the repo:
::
$ pip install git+
TODO
----
Glob support
^^^^^^^^^^^^
add support for globs, so you could do:
::
pyt *
to run all commands. Or:
::
pyt mod*.Foo.bar*
to run all test modules that start with ``mod``, have a ``Foo`` class,
and ``test_bar*`` methods
Tests don't run in windows
^^^^^^^^^^^^^^^^^^^^^^^^^^
I used ``/`` in the tests, and ``os.sep`` in all the pyt stuff, so it
runs on windows, it just doesn't pass the tests :(
- Downloads (All Versions):
- 0 downloads in the last day
- 91 downloads in the last week
- 958 downloads in the last month
- Author: Jay Marcyes
- License: MIT
- Categories
- Package Index Owner: Jaymon
- DOAP record: pyt-0.7.1.xml | https://pypi.python.org/pypi/pyt/0.7.1 | CC-MAIN-2016-18 | refinedweb | 795 | 65.76 |
HTTP API interface for üWave.
$ cnpm install u-wave-api-v1
REST API plugin for üWave, the collaborative listening platform.
Getting Started - API - Building - License
Note: üWave is still under development. Particularly the
u-wave-coreand
u-wave-api-v1modules will change a lot before the "official" 1.0.0 release. Make sure to always upgrade both of them at the same time.
npm install u-wave-api-v1
The module exports a middleware that can be used with express-style HTTP request handlers.
Creates a middleware for use with Express or another such library. The first parameter is a
u-wave-core instance. Available options are:
server- An HTTP server instance.
u-wave-api-v1uses WebSockets, and it needs an HTTP server to listen to for incoming WebSocket connections. An example for how to obtain this server from an Express app is shown below.
socketPort-.
import express from 'express'; import stubTransport from 'nodemailer-stub-transport'; import uwave from 'u-wave-core'; import createWebApi from 'u-wave-api-v1'; const app = express(); const server = app.listen(); const secret = fs.readFileSync('./secret.dat'); const uw = uwave({ secret: secret, }); const api = createWebApi(uw, { secret: secret, // Encryption secret server: server, // HTTP server recaptcha: { secret: 'AABBCC...' }, // Optional mailTransport: stubTransport(), // Optional onError: (req, error) => {}, // Optional }); app.use('/v1', api);
Returns a middleware that attaches the üWave core object and the üWave api-v1 object to the request. The
u-wave-core instance will be available as
req.uwave, and the
u-wave-api-v1 instance will be available as
req.uwaveApiV1. This is useful if you want to access these objects in custom routes, that are not in the
u-wave-api-v1 namespace. E.g.:
app.use('/v1', api); // A custom profile page. app.get('/profile/:user', api.attachUwaveToRequest(), (req, res) => { const uwave = req.uwave; uwave.getUser(req.params.user).then((user) => { res.send(`<h1>Profile of user ${user.username}!</h | https://developer.aliyun.com/mirror/npm/package/u-wave-api-v1 | CC-MAIN-2021-04 | refinedweb | 317 | 51.34 |
[ <<BACK] [ CONTENTS] [ NEXT>>]
In the last lesson you saw how the
Applet class provides a
Panel component so you can design the applet's user interface. This lesson expands the basic application from Lessons 1 and 2 to give it a user interface using the Java Foundation Classes (JFC) Project Swing APIs that handle user events.
Note: See Project Swing and Java 2D Graphics for information that builds on the concepts presetned here.Note: See Project Swing and Java 2D Graphics for information that builds on the concepts presetned here.
Project Swing APIs
In contrast to the applet in Lesson 3 where the user interface is attached to a panel object nested in a top-level browser, the Project Swing application in this lesson attaches its user interface to a panel object nested in a top-level frame object. A frame object is a top-level window that provides a title, banner, and methods to manage the appearance and behavior of the window.
The Project Swing code that follows builds this simple application. The window on the left appears when you start the application, and the window on the right appears when you click the button. Click again and you are back to the original window on the left.
Import Statements
Here is the SwingUI.java code. At the top, you have four lines of import statements. The lines indicate exactly which Java API classes the program uses. You could replace four of these lines with this one line:
import java.awt.*;, to import the entire
awt package, but doing that increases compilation overhead than importing exactly the classes you need and no others.
import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*;
Class Declaration
The class declaration comes next and indicates the top-level frame for the application's user interface is a
JFrame that implements the
ActionListener interface.
class SwingUI extends JFrame implements ActionListener{
The
JFrame class extends the
Frame class that is part of the Abstract Window Toolkit (AWT) APIs. Project Swing extends the AWT with a full set of GUI components and services, pluggable look and feel capabilities, and assistive technology support. For a more detailed introduction to Project Swing, see the Swing Connection, and Fundamentals of Swing, Part 1.
The Java APIs provide classes and interfaces for you to use. An interface defines a set of methods, but does not implement them. The rest of the
SwingUI class declaration indicates that this class will implement the
ActionListener interface. This means the
SwingUI class must implement all methods defined in the
ActionListener interface. Fortunately, there is only one,
actionPerformed, which is discussed below.
Instance Variables
These next lines declare the Project Swing component classes the
SwingUI class uses. These are instance variables that can be accessed by any method in the instantiated class. In this example, they are built in the
SwingUI constructor and accessed in the
actionPerformed method implementation. The
private boolean instance variable is visible only to the
SwingUI class and is used in the
actionPerformedmethod to find out whether or not the button has been clicked.
JLabel text, clicked; JButton button, clickButton; JPanel panel; private boolean _clickMeMode = true;
Constructor
The constructor (shown below) creates the user interface components and
JPanel object, adds the components to the
JPanel object, adds the panel to the frame, and makes the
JButton components event listeners. The
JFrame object is created in the
main method when the program starts.
When the
JPanel object is created, the layout manager and background color are specified. The layout manager in use determines how user interface components are arranged on the display area.
The code uses the
BorderLayout layout manager, which arranges user interface components in the five areas shown at left. To add a component, specify the area (north, south, east, west, or center).
To find out about some of the other available layout managers and how to use them, see the JDC article Exploring the AWT Layout Managers.
The call to the
getContentPane method of the
JFrame class is for adding the
Panel to the
JFrame. Components are not added directly to a
JFrame, but to its content pane. Because the layout manager controls the layout of components, it is set on the content pane where the components reside. A content pane provides functionality that allows different types of components to work together in Project Swing.
Action Listening
In addition to implementing the
ActionListener interface, you have to add the event listener to the JButton components. An action listener is the SwingUI object because it implements the ActionListener interface. In this example, when the end user clicks the button, the underlying Java platform services pass the action (or event) to the actionPerformed method. In your code, you implement the actionPerformed method to take the appropriate action based on which button is clicked..
The component classes have the appropriate add methods to add action listeners to them. In the code the JButton class has an addActionListener method. The parameter passed to addActionListener is this, which means the SwingUI action listener is added to the button so button-generated actions are passed to the actionPerformed method in the SwingUI object.
button = new JButton("Click Me"); //Add button as an event listener button.addActionListener(this);
Event Handling
The actionPerformed method is passed an event object that represents the action event that occurred. Next, it uses an if statement to find out which component had the event, and takes action according to its findings.
You can find information on event handling for the different components in The Java Tutorial section on Event Handling.
Main Method
The
main method creates the top-level
frame, sets the title, and includes code that lets the end user close the window using the frame menu.
The code for closing the window shows an easy way to add event handling functionality to a program. If the event listener interface you need provides more functionality than the program actually uses, use an adapter class. The Java APIs provide adapter classes for all listener interfaces with more than one method. This way, you can use the adapter class instead of the listener interface and implement only the methods you need. In the example, the WindowListener interface has 7 methods and this program needs only the windowClosing method so it makes sense to use the WindowAdapter class instead.
This code extends the WindowAdapter class and overrides the windowClosing method. The new keyword creates an anonymous instance of the extended inner class. It is anonymous because you are not assigning a name to the class and you cannot create another instance of the class without executing the code again. It is an inner class because the extended class definition is nested within the SwingUI class.
This approach takes only a few lines of code, while implementing the WindowListener interface would require 6 empty method implementations. Be sure to add the WindowAdapter object to the frame object so the frame object will listen for window events.
Applets Revisited
Using what you learned in Lesson 3: Building Applets and this lesson, convert the example for this lesson into an applet. Give it a try before looking at the solution.
In short, the differences between the applet and application versions are the following:
publicso
appletviewercan access it.
Appletand the application class descends from
JFrame.
mainmethod.
startand
initmethods.
Applet; whereas, in the case of an application, GUI components are added to the content pane of its
JFrameobject.
More Information
For more information on Project Swing, see the Swing Connection, and Fundamentals of Swing, Part 1.
Also see The JFC Project Swing Tutorial: A Guide to Constructing GUIs.
To find out about some of the other available layout managers and how to use them, see the JDC article Exploring the AWT Layout Managers. | http://www.oracle.com/technetwork/java/front-139339.html | CC-MAIN-2016-26 | refinedweb | 1,301 | 53.21 |
Python and Math
Contents
Welcome to Python and Math![edit]
Python and Math is an introductory approach to learning how to apply programming skills to solving math problems, while presenting high-level content with low-level terminology. Both experienced and beginner programmers will benefit from what this Wiki-book has to offer.
Here are the main objectives:
(1) Introduce programmers to solving math problems using programming.
(2) Practice problem-solving skills using programming.
(3) Introduce new skills and techniques that increase the efficiency of programs.
So as a starter, here is an example of a problem you would solve using programming:
Find the 10001th prime number, given that 2 is the first and 3 is the second.
Programming + Math[edit]
The main benefit of using programming in problem-solving is where the limitations of pencil/paper become apparent: time. Solving problems by hand can take a long time, especially solving a problem as the one above. Because there are no patterns in prime numbers (as we know), in order to get the 10001th prime, we must write them all out, in hand, one by one. Won't that take a long time! Essentially computers are just fast-number crunchers - we use them to calculate numbers really fast, but only combined with the programmer's mathematical genius can really hard problems be solved.
If you are well-versed in programming, then you will find skills picked up in this book easy to learn; math and programming come hand-in-hand. You may skip to the second step.
If you are unfamiliar with how to program, don't be afraid! I wont necessarily teach you myself, but through personal experience, i will supply you with internet sources that are the most helpful for a young programmer. I suggest learning Python as it is easy to pick up, user-friendly, and simple. Although it is not as powerful as C++ for example, it still gets the job done. In the end, it is the brain of the programmer than contributes to the best (and fastest) solution.
So first of all, download the latest 2.x.x version of Python from and install it. Then, read this entire Wiki-book on the basics of programming:. If you want, you will also find this site helpful for other syntax tricks: (Read Sections 1-5, or more if you wish).
Practice[edit]
As for practicing solving problems with programming skills, this Wiki-book will use and abuse the ProjectEuler site:. Essentially, this site has hundreds of different problems that can only (99% of the time) be solved using programming. They increase in difficulty, as they start relying more on statistical maths and programming tricks.
BUT
This Wiki-book will not give the answers to these problems out; such action will only hinder your skill-development. Instead, tips and strategies will be offered here and there that help in general problem solving ability, but not explicitly give away the method of obtaining the answer. Remember: solving a problem with your own strategy is 99% of the fun (the other 1% being the bragging-rights).
Dynamic Programming[edit]
The main bulk of what this Wiki-book will discuss will be on how to improve your programs so that they run faster and more efficiently. A more formal introduction to this will be made later, but below is an example of what I mean.
A function evaluating if input integer is prime (in Python script):
def prime(input): for n in range(2, input): if input%n == 0: return False return True
Essentially, this evaluates whether integer x can be divisible by any number less than it (n = [2, 3, 4, ... , x-2, x-1]). However, there are two redundancies in this method:
1. If input is not divisible by 2, it will not be divisible to any other even number (4, 6, 8, ...).
2. It is not needed to evaluate integers above the square root of the input number. To elaborate, here is an example:
Evaluate if 127 is prime: 127 divisible by 2? No. 127 divisible by 3? No. 127 divisible by 5? No. 127 divisible by 7? No. 127 divisible by 9? No. 127 divisible by 11? No. Therefore 127 is prime.
We do not need to evaluate if 127 is divisible by 13, because 1271/2 is around 11.27, which is smaller than 13. If 127 was divisible by 13, then 127/13 would be less than 13 itself and therefore must give an integer already tested. As another example, 143 will be checked if it is prime. Here it will be shown that 13 is not needed to be evaluated once again (1431/2 ≈ 11.96).
143 divisible by 3? No. 143 divisible by 5? No. 143 divisible by 7? No. 143 divisible by 9? No. 143 divisible by 11? Yes → 143/11 = 13 (143 divisible by 13 not evaluated) Therefore, 143 is not prime
Hence, our original prime function can be improved using these two suggestions, and now runs at a greater speed! For example, when evaluating if 10001 is prime, the function went through 10000 different numbers. But with these improvements, it only has to go through 50!
from math import ceil def prime(input): for n in [2] + range(3, int(ceil(input**0.5)), 2): if input%n == 0: return False return True
Now, this only tests odd numbers (≥3) and ≤ the square root of the input (hence the ceil function, which can be replaced with a simple "+1").
So here is the lesson to learn from this: the gun is only as accurate as you are.
Conclusion[edit]
So, start off by creating a ProjectEuler account, then sort the problems list in ascending difficulty. Starting with the easy ones first will help you go through a lot of troubles in the beginning. So here is your assignment for the next chapter:
- Finish Problems 1 and 2 (without cheating!!!) | https://en.wikibooks.org/wiki/Python_and_Math | CC-MAIN-2017-17 | refinedweb | 990 | 64.2 |
Hm, yes, it looks interesting. Thank you.
Do you know if that functionality is planned to be distributed?
Anthony.
----- Mail original -----
De: "Harsh J" <[email protected]>
À: "<[email protected]>" <[email protected]>
Envoyé: Dimanche 21 Avril 2013 14:06:45
Objet: Re: HDFS load-balancing
Are you speaking of load balancing of the metadata requests served by
the NameNode? There isn't a direct way right now but HDFS Federation
features would interest you, as it helps divide the namespace itself
into several different NNs.
Read more about Federation at
On Sun, Apr 21, 2013 at 3:31 PM, <[email protected]> wrote:
> Hello everybody.
>
> I am wondering how HDFS deals with load balancing. I mean, there is on primary namenode
and only one secondary namenode (if I well understood the documentation).
>
> Is that right?
>
> But with only one server answering all requests, I can't imagine it could be enough.
> I have also read that facebook use that FS so it might be possible, isn't it?
>
> Regards.
>
> Anthony.
--
Harsh J | http://mail-archives.apache.org/mod_mbox/hadoop-mapreduce-user/201304.mbox/%3C2138056470.86607526.1366546633795.JavaMail.root@zimbra59-e10.priv.proxad.net%3E | CC-MAIN-2018-09 | refinedweb | 177 | 59.09 |
This tutorial will add the flip mechanism to the GameSprite module to flip the game character along the y axis as well as includes the script to move the game character along the x axis in our main game module.
In order to flip the gaming character we need to use the below method
pygame.transform.flip(sub_surface, self.flip, False)
where sub_surface is the surface return by the
self.sprite.subsurface(self.sprite.get_clip())
method which we have mentioned in our previous tutorial. Besides the sub_surface, the pygame.transform.flip method also takes in two other parameters, the first one is the xboolean uses to flip the surface along the y axis and the second one is the yboolean uses to flip the surface along the x axis, we will only use the xboolean in this example so the yboolean value is always set to False. By setting the xboolean to True or False we can flip the surface along the y axis which will make the game character facing left or right.
There is only one minor change to your original GameSprite module which is to add in another boolean parameter to it so you can use that boolean parameter to control the flipping x-direction.
import pygame class GameSprite(object): def __init__(self, image, rect, flip): self.image = image self.rect = rect self.flip = flip self.sprite = pygame.image.load(image).convert_alpha() def getImage(self): # this method will return a subsurface which represents a portion of the spritesheet self.sprite.set_clip(self.rect) # clip a portion of the sprite with the rectangle object sub_surface = self.sprite.subsurface(self.sprite.get_clip()) return pygame.transform.flip(sub_surface, self.flip, False)
In order to move our game character we need to get all the keys a user has pressed with this statement.
pressed_keys = pygame.key.get_pressed() # get all the keys from key-press events
Then we will see whether the left arrow key is within the pressed_keys list or not.
if pressed_keys[K_LEFT]: flip = True # if the user pressed the left arrow key then makes the object facing left v = Vector2D(-1., 0.) # move the object one unit to the left
Or else whether the right arrow key is within the pressed_keys list or not.
elif pressed_keys[K_RIGHT]: flip = False # if the user pressed the right arrow key then makes the object facing right v = Vector2D(1., 0.) # move the object one unit to the right
The rest of the script in our main game module is the same as the 1) animate the stand still sprite and the 2) moving the game sprite tutorial.
#! flip = False clock = pygame.time.Clock() # initialize the clock object player_pos = Vector2D(320, 240) # initial position of the sprite player_speed = 70. # speed per second object facing left v = Vector2D(-1., 0.) # move the object one unit to the left elif pressed_keys[K_RIGHT]: flip = False # if the user pressed the right arrow key then makes the object facing right v = Vector2D(1., 0.) # move the object one unit to the right screen.fill((205, 200, 115)) rect = Rect((sprite_counter * 64, 0), (64, 64)) # the rectangle object used to clip the sprite area game_sprite = GameSprite(robot_sprite_sheet, rect, flip) time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 player_pos+= v * player_speed * time_passed_seconds pygame.display.flip()
Now run the above module and press the left or right arrow key to see how the game character flip and move around. | http://gamingdirectional.com/blog/2016/09/10/how-to-move-and-flip-the-gaming-character-with-pygame/ | CC-MAIN-2019-18 | refinedweb | 568 | 62.68 |
Openfire Plugin Developer's GuideIntroduction
Openfire features plug-ins are enhanced. This document is a guide to developers to create plug-ins.
The structure of a plug-in
Plug-ins Plug-ins openfireHome stored in the directory. When deploying a plug-in jar or war file, it will automatically unzip to install. The document in the plug-in directory structure is as follows:
Plug-in structure
myplugin /
| - Plugin.xml plugin definition file
| - Readme.html Optional plug-ins readme file, it will be displayed to end-users
| - Changelog.html Optional plug-ins to modify the file, it will be displayed to the end-user
| - Icon_small.gif optional small (16x16) icon and plug-ins (may also be a PNG file)
| - Icon_large.gif Optional large (32x32) icon and plug-ins (may also be a PNG file)
| Classes / resources required plug-ins (ie, property documents)
|-Database / optional database architecture document, you need to plug-ins
|-I18n / plug configuration language internationalization.
|-Lib / your plugin jar package
|-Web resources integrated management console, and if so
| - WEB-INF /
| - Web.xml generated web.xml containing compiled JSP entries
|-Web-custom.xml optional user-defined custom web.xml in servlets
|-Images / picture file storage directory
web directory of plug-ins exist, need to add to the Openfire Admin Console. Further details are as follows.
Plugin.xml file in the main plug-in type. Sample file may look as follows:
Sample plugin.xml
<?xml version="1.0" encoding="UTF-8"?>
<plugin>
<! Requires plug-in class -->
<class>org.example.ExamplePlugin</class>
<!-- Plugin metadata -->
<name>Example Plugin</name>
<description>This is an example plugin.</description>
<author>Jive Software</author>
<version>1.0</version>
<date>07/01/2006</date>
<url></url>
<minServerVersion>3.0.0</minServerVersion>
<licenseType>gpl</licenseType>
<!-- Management Console entry -->
<adminconsole>
<!-- More on this below -->
</adminconsole>
</plugin>
The meta-data fields can be set in the plugin.xml file:
Name - the name of plug-ins.
Description - description of plug-ins.
Author - the author of plug-ins.
Version - the version of the plug-ins.
Date - such as release date July 1, 2006.
Url - web site plug-ins.
MinServerVersion - minimum Openfire version
DatabaseKey - if plug-ins required its own data sheet, the databaseKey architecture should be the establishment of a principal name (usually the same name are plug-ins). Database architecture document for each supported database, then placed in the database plug-ins directory. For example, "foo", file will be called the architecture "foo_mysql.sql", "foo_oracle.sql" and so on, we propose to you that your table prefix of, in order to avoid possible conflicts with other applications installed on the same database. Table ofVersion script should be entered using the key, this version of the architecture can track information, such as:
INSERT INTO ofVersion (name, version) VALUES ( 'foo', 0); databaseVersion - database version number (if the database schema definition). The new plug-ins with the database architecture should begin in the version. If in the future versions of required plug-ins updates, these updates can be defined to create a subdirectory in the upgrading of the database directory for each version. For example, the directory will contain database/upgrade/1 and database/upgrade/2 script, such as "foo_mysql.sql" and "foo_oracle.sql" contained in the relevant databases, for each version change. Each script should be updated versions of Table ofVersion information, such as:
UPDATE ofVersion set version = 1 where name = 'foo';
ParentPlugin - Father layer plug-in (as a "foo" of the "foo.jar" plug-ins). When a plug-Have a parent plug-in, plug-in class loader will be used to rather than set up a new class loader. This allows plug-ins work together more closely. Sub-plug-plug-ins will not affect his father.
"LicenseType": display the license agreement, the plug-ins are from. Valid values are as follows:
o "commercial": commercial "commercial": Plug-ins are released under the commercial license agreement.
o "gpl": "General Public License": the use of plug-ins released GNU Public License (GPL).
o "apache": The Apache plug-in permits issued.
o "internal": (internal) plug-ins are for internal use only of an organization and will not be re-distributed.
o "other": (other) plug-ins are released under the license agrement does not belong to one of the other categories. The details of the license agreement should be in the plug-in readme.
If the license type is not set, it is assumed that the other.
Some extra documents are available in the plug-ins provide more information to end-users (all placed in the main plug-ins directory):
Readme.html - optional plug-ins readme file, it will show to end-users.
Changelog.html - optional plug-ins to modify the file, it will show to end-users.
Icon_small.png - Optional small (16x16) icon associated plug-ins. Can also be yes. GIF file.
Icon_large.png - Optional large (32x32) icon associated plug-ins. Can also be yes. GIF file.
interface from the
Sampling plug-in implementation of
package org.example;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import java.io.File;
/**
* A sample plugin for Openfire.
*/
public class ExamplePlugin implements Plugin {
public void initializePlugin (PluginManager manager, File pluginDirectory) {
// Your code
}
public void destroyPlugin () {
// Your code
}
}
General Plugin Best Practices best practices in general plug-ins
Choose the name of the package for your plug-ins, we recommend that you select a number of unique to you and / or your organization to help as much as possible to avoid conflict. For example, if each person go with org.example.PluginName, even if PluginName are different, you may start running into some conflicts here and there, the class name. Especially when working with the cluster.
.
Modify management console
Plug-ins can add tags, section, and page management console. There are several steps to accomplish this:
The first <adminconsole/> must be added to the plugin.xml file.
JSP document must be prepared and implemented by the plug-in classpath. The compilation of the Arab-Israeli web.xml file, which contains the JSP servlet entries must be put to the page / directory under the plug-ins. Note: Openfire script can be set up to assist in the preparation and the creation of web.xml in JSPs. This is described in detail below.
Any images required for JSP pages must live in the pages / images / directory. Only GIF and PNG images support.
<adminconsole /> Part of the definition of plugin.xml extra tags, branches and project management framework console. Sample plugin.xml file may look as follows:
Sample plugin.xml
<? xml version = "1.0" encoding = "UTF-8"?>
<plugin>
<! - Main plugin class ->
<class> org.example.ExamplePlugin </ class>
<! - Management console entries ->
<adminconsole>
<tab name="Example" url="my-plugin-admin.jsp" description="Click to manage...">
<sidebar name="My Plugin">
<item name = "My Plugin Admin"
url = "my-plugin-admin.jsp"
description = "Click to administer settings for my plugin" />
</ sidebar>
</ tab>
</ adminconsole>
</ plugin>
In this example, we define a new tag "Example", a tool section "my plug-ins" and a page "My Plug-management." We have already registered, admin.jsp plug-ins page. You can overwrite the existing label, section, item ID using the existing property values in their own definition of <adminconsole>.
Management Console Best Practices
There are several best practices, the need to consider changes to Openfire Admin Console through a plug-in. The general subject are seamlessly integrated plug-ins should:
Integrated into the existing tags and sidebar sections whenever possible instead of creating your own. Only create new tag a very important new features.
Do not use "plug-in" the name, tag, sidebars and projects. For example, has a project called "gateway plug-in", or it may be the so-called "Gateway Settings."
Try to comply with the existing user interface management console in your custom plug-ins page.
There is no need to set up a management console to enter the view meta-data plug-ins. Instead, let Openfire inform users about the plug-in installation, and provides plug-ins management.
Writing pages Management Console
Openfire use
Set up web pages, and are Sitemesh easy. As long as the HTML page to create an effective, then the use of meta tags to send instructions Sitemesh. When rendering the output, Sitemesh will use the instructions provided by you, so that the decoration of any content, in your HTML page. The following meta tags can be used to:
PageID - the ID of the page, which must comply with the management console entry in the XML described above. PageID subPageID either or must be specified.
SubPageID - the ID group page, which must comply with the management console entry in the XML described above. Sub-page for the administrative acts relating to the parent page ID. For example, to edit or delete a particular group. PageID subPageID either or must be specified.
ExtraParams (optional) - extra parameters, should be through the web page. For example, in one group pages may delete the ID Group. Parameters must be URL encoded.
Decoration (optional) - overwrite the page to use Sitemesh decoration. Decoration is not named, will be able to provide a simple page is not decoration.
The following HTML code segment shows an effective website:
Example
<html>
<head>
<title>My Plugin Page</title>
<meta name="pageID" content="myPluginPage"/>
</head>
<body>
Body here !
</body>
</html>
Plug-ins you use in the localization
This may put you into various languages of the plug-ins (i18n). To do this, use the following procedure:
Create a "i18n" directory in the root directory of plug-ins.
Resource file for each purchase, and use% [plugin_name]% _i18n "_" language ". Properties". Property "naming convention, where [plugin_name] are the names of plug-ins directory. See
Convert a string in your JSP document refers to the international key. For example:
<% @ Taglib uri = "" prefix = "c"%>
<% @ Taglib uri = "" prefix = "fmt"%>
...
<fmt:message
Internationalization of Java in your document using LocaleUtils class:
org.jivesoftware.util.LocaleUtils.getLocalizedString ( "some.key.name", "[plugin_name]");
Internationalization plugin.xml file in your use of $ (leaf) format:
<sidebar name="${plugin.sidebar.name}" description="${plugin.sidebar.description}">
<description> $ (plugin.description) </ description>
Use Openfire build script
In Openfire script will help you set up the establishment and development of plug-ins. It looks to develop plug-ins directory of the following format:
Plug-in structure
myplugin/
|- plugin.xml <- Plug-ins definition file
|- readme.html <- Plugin Readme file
|- changelog.html <- A plugin to modify the log
|- icon_small.gif <- Thumbnail pictures (16x16)
|- icon_large.gif <- Picture (32x32)
|- classes/ <- The plug-in needed resources (that is, the properties file)
|- lib/ <- Package
|- src/
|- database <- Optional database scripting plug-in
|- java <- Plug-in Java source code
| |- com
| |- mycompany
| |- *.java
|- web
|- *.jsp <- jsp Page
|- images/ <- Picture files
|- WEB-INF
|- web.xml <- Optional file custom servlets can register
Build script will compile the source files and JSPs, and the establishment of an effective plug-in structure and JAR files. Put your plug-in directory src / plugins directory of the source distribution, and then use ant plugins to build your plug-ins.
Any plug-ins required JAR files should be placed in the compilation of the directory lib. These
- 20:57
- Browser (15)
- Category: Openfire
- Related recommend
Comment
zyjwy02
- View: 11478 times
- Gender:
- From: Canton
- Details book
Search this blog
Recent visitors
dlboy
wuxuping
NewTamato
skying007
>> More Visitors
Blog Categories
- All blog (42)
- Technical Digest (35)
- Living Diary (0)
- Flex (2)
- Openfire (3)
Other classification
- My Favorites (7)
- My Forum Posts (3)
- Me the essence of a good paste (0)
Recently joined the circle of
- struts2
Archive
- 2009-02 (1)
- 2009-01 (8)
- 2008-12 (4)
- More archives ...
Latest Comments
- ClassLoader mechanism to understand
Yes! ! Study, it is best to scan each and every trip is also about Translations
- By neusoft
- ExtJS DWR Spring Qiangqiang together ...
How can download ah? LZ
- By wyyacyy
- JVM tuning Summary (transgenic)
Good article, ORZ
- By yumi301
- By the model to talk about the principle of object-oriented ...
Model is a collection of experience in problem-solving methods for exploration
- By picnic
- Aptana Ajax libraries plugin --- EXT ...
Aptana already has this plug-ins. why is it necessary to hand-written or if the effect of the Komodo IDE ...
- By smellcode
- JVM tuning Summary (transgenic)
- By the model to talk about the principles of object-oriented as much as using combination of the use of following ...
- ClassLoader mechanism to understand
- Cairngorm
- JavaScript and the DOM operation jQuery
Statement: JavaEye article copyright belong to the author, are protected by law. Without the written permission of the author may not be reproduced. If the consent of the author are reproduced, it is necessary to identify the article hyperlink form original source and authors.
© 2003 -2009 JavaEye.com. All rights reserved. Shanghai jiong resistant computer software Co., Ltd. [ ICP 05023328 ] | http://www.codeweblog.com/openfire-plugin-developer-s-guide/ | CC-MAIN-2014-10 | refinedweb | 2,103 | 50.23 |
Go to: Synopsis. Return value. Related. Flags. Python examples.
objectType(
object
, [isAType=string], [isType=string], [tagFromType=string], [typeFromTag=int], [typeTag=boolean])
Note: Strings representing object names and arguments must be separated by commas. This is not depicted in the synopsis.
objectType is undoable, NOT queryable, and NOT editable.This command returns the type of elements. Warning: This command is incomplete and may not be supported by all object types.
import maya.cmds as cmds # create an object to query type of cmds.sphere( n='sphere1' ) # To query the type of an object: cmds.objectType( 'sphere1Shape' ) # Result: nurbsSurface # # To confirm that sphere1Shape really is a nurbs surface: cmds.objectType( 'sphere1Shape', isType='nurbsSurface' ) # Result: 1 # | http://download.autodesk.com/global/docs/maya2014/en_us/CommandsPython/objectType.html | CC-MAIN-2019-18 | refinedweb | 113 | 52.76 |
On Wed, Mar 14, 2012 at 9:26 AM, Justin Mclean <[email protected]>wrote:
> > My vote is to keep the spark ns in the 4.x branch and then have a new
> > namespace when we decide to create a new set of components.
> 100% agree with that. Again not suggestion we change existing name space
> just that we add one or two.
>
> I'm actually thinking we don't add any names right now, just stick with
spark. I wouldn't want to see us get name crazy. I know you say "one or
two", but that is a slipper slope to a few dozen pretty quickly. If
something doesn't fit the current model well enough that it needs it's own
namespace should it even be included in the core?
> > I do agree with Daniel in that we don't use "apache" or any derivation as
> > we are then stuck for the next set of components.
> Stuck how exactly? Package names may be a bit longer but is that really an
> issue?
>
>
Stuck as in if we name some set of components "apache" and then after some
time we make a new set.. we call them apache2? I'd prefer to just come up
with a more 'marketing' style name.
> > Though I may be convinced to have a namespace for experimental
> components.
> Any idea what you would name it?
No idea. This is just talking out loud but it may be good for one of the
branches that are more in development rather than the trunk. The trunk
would always have finalized names and packages. This would be more for
those developers that like to live on the edge.
--
Jonathan Campos | http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201203.mbox/%3CCAAd0WrZGo74x88c69gm0KGPOwJqZD6YXCsFDmzvK-UgzQ4OEJA@mail.gmail.com%3E | CC-MAIN-2014-10 | refinedweb | 284 | 91.51 |
more complex PySide2 applications into distributable macOS app bundles. You can choose to follow it through completely, or skip to the parts that are most relevant to your own project.
We finish off by building a macOS Disk Image, the usual method for distributing applications on macOS.
You always need to compile your app on your target system. So, if you want to create a Mac .app you need to do this on a Mac, for an EXE you need to use Windows.
Example Disk Image Installer for macOS
If you're impatient, you can download the Example Disk Image for macOS first.
Requirements
PyInstaller works out of the box with. For PySide2 you would use — macOS). --windowed app.py
The
--windowed flag is necessary to tell PyInstaller to build a macOS
.app bundle.
You'll see a number of messages output, giving debug information about what PyInstaller is doing. These are useful for debugging issues in your build, but can otherwise be ignored. The output that I get for running the command on my system is shown below.
martin@MacBook-Pro pyside2 % pyinstaller --windowed app.py 74 INFO: PyInstaller: 4.8 74 INFO: Python: 3.9.9 83 INFO: Platform: macOS-10.15.7-x86_64-i386-64bit 84 INFO: wrote /Users/martin/app/pyside2/app.spec 87 INFO: UPX is not available. 88 INFO: Extending PYTHONPATH with paths ['/Users/martin/app/pyside2'] 447 INFO: checking Analysis 451 INFO: Building because inputs changed 452 INFO: Initializing module dependency graph... 455 INFO: Caching module graph hooks... 463 INFO: Analyzing base_library.zip ... 3914 INFO: Processing pre-find module path hook distutils from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks/pre_find_module_path/hook-distutils.py'. 3917 INFO: distutils: retargeting to non-venv dir '/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9' 6928 INFO: Caching module dependency graph... 7083 INFO: running Analysis Analysis-00.toc 7091 INFO: Analyzing /Users/martin/app/pyside2/app.py 7138 INFO: Processing module hooks... 7139 INFO: Loading module hook 'hook-PyQt6.QtWidgets.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7336 INFO: Loading module hook 'hook-xml.etree.cElementTree.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7337 INFO: Loading module hook 'hook-lib2to3.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7360 INFO: Loading module hook 'hook-PyQt6.QtGui.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7397 INFO: Loading module hook 'hook-PyQt6.QtCore.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7422 INFO: Loading module hook 'hook-encodings.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7510 INFO: Loading module hook 'hook-distutils.util.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7513 INFO: Loading module hook 'hook-pickle.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7515 INFO: Loading module hook 'hook-heapq.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7517 INFO: Loading module hook 'hook-difflib.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7519 INFO: Loading module hook 'hook-PyQt6.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7564 INFO: Loading module hook 'hook-multiprocessing.util.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7565 INFO: Loading module hook 'hook-sysconfig.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7574 INFO: Loading module hook 'hook-xml.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7677 INFO: Loading module hook 'hook-distutils.py' from '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks'... 7694 INFO: Looking for ctypes DLLs 7712 INFO: Analyzing run-time hooks ... 7715 INFO: Including run-time hook '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks/rthooks/pyi_rth_subprocess.py' 7719 INFO: Including run-time hook '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgutil.py' 7722 INFO: Including run-time hook '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py' 7726 INFO: Including run-time hook '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks/rthooks/pyi_rth_inspect.py' 7727 INFO: Including run-time hook '/usr/local/lib/python3.9/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pyqt6.py' 7736 INFO: Looking for dynamic libraries 7977 INFO: Looking for eggs 7977 INFO: Using Python library /usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/Python 7987 INFO: Warnings written to /Users/martin/app/pyside2/build/app/warn-app.txt 8019 INFO: Graph cross-reference written to /Users/martin/app/pyside2/build/app/xref-app.html 8032 INFO: checking PYZ 8035 INFO: Building because toc changed 8035 INFO: Building PYZ (ZlibArchive) /Users/martin/app/pyside2/build/app/PYZ-00.pyz 8390 INFO: Building PYZ (ZlibArchive) /Users/martin/app/pyside2/build/app/PYZ-00.pyz completed successfully. 8397 INFO: EXE target arch: x86_64 8397 INFO: Code signing identity: None 8398 INFO: checking PKG 8398 INFO: Building because /Users/martin/app/pyside2/build/app/PYZ-00.pyz changed 8398 INFO: Building PKG (CArchive) app.pkg 8415 INFO: Building PKG (CArchive) app.pkg completed successfully. 8417 INFO: Bootloader /usr/local/lib/python3.9/site-packages/PyInstaller/bootloader/Darwin-64bit/runw 8417 INFO: checking EXE 8418 INFO: Building because console changed 8418 INFO: Building EXE from EXE-00.toc 8418 INFO: Copying bootloader EXE to /Users/martin/app/pyside2/build/app/app 8421 INFO: Converting EXE to target arch (x86_64) 8449 INFO: Removing signature(s) from EXE 8484 INFO: Appending PKG archive to EXE 8486 INFO: Fixing EXE headers for code signing 8496 INFO: Rewriting the executable's macOS SDK version (11.1.0) to match the SDK version of the Python library (10.15.6) in order to avoid inconsistent behavior and potential UI issues in the frozen application. 8499 INFO: Re-signing the EXE 8547 INFO: Building EXE from EXE-00.toc completed successfully. 8549 INFO: checking COLLECT WARNING: The output directory "/Users/martin/app/pyside2/dist/app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)y On your own risk, you can use the option `--noconfirm` to get rid of this question. 10820 INFO: Removing dir /Users/martin/app/pyside2/dist/app 10847 INFO: Building COLLECT COLLECT-00.toc 12460 INFO: Building COLLECT COLLECT-00.toc completed successfully. 12469 INFO: checking BUNDLE 12469 INFO: Building BUNDLE because BUNDLE-00.toc is non existent 12469 INFO: Building BUNDLE BUNDLE-00.toc 13848 INFO: Moving BUNDLE data files to Resource directory 13901 INFO: Signing the BUNDLE... 16049 INFO: Building BUNDLE BUNDLEcrypto.1.1.dylib │ ├── PySide2 │ ... │ ├── app │ └── Qt5Core
.so files.
Since we provided the
--windowed flag above, PyInstaller has actually created two builds for us. The folder
app is a simple folder containing everything you need to be able to run your app. PyInstaller also creates an app bundle
app.app which is what you will usually distribute to users.
The
app folder is a useful debugging tool, since you can easily see the libraries and other packaged data files.
You can try running your app yourself now, either by double-clicking on the app bundle, or by running the executable file, named
app.exe from the
dist folder. In either case, and the
--windowed flag.') app = BUNDLE(coll, name='app.app', icon=None, bundle_identifier=None).
Because we used the
--windowed command line flag, the
EXE(console=) attribute is set to
False. If this is
True a console window will be shown when your app is launched -- not what you usually want for a GUI application. app (and
dist folder) by editing the
.spec file to add a
name= under the EXE, COLLECT and BUNDLE blocks.') app = BUNDLE(coll, name='Hello World.app', icon=None, bundle_identifier=None)
The name under EXE is the name of the executable file, the name under BUNDLE is the name of the app bundle.
Alternatively, you can re-run the
pyinstaller command and pass the
-n or
--name configuration flag along with your
app.py script.
pyinstaller -n "Hello World" --windowed app.py # or pyinstaller --name "Hello World" --windowed app.py
The resulting app file will be given the name
Hello World.app and the unpacked build placed in the folder
dist\Hello World\.
Application with custom name "Hello World"
The name of the
.spec file is taken from the name passed in on the command line, so this will also create a new spec file for you, called
Hello World.spec in your root folder.
Make sure you delete the old
app.spec file to avoid getting confused editing the wrong one.
Application icon
By default PyInstaller app bundles come with the following icon in place.
Default PyInstaller application icon, on app bundle
You will probably want to customize this to make your application more recognisable. This can be done easily by passing the
--icon command line argument, or editing the
icon= parameter of the BUNDLE section of your
.spec file. For macOS app bundles you need to provide an
.icns file.
app = BUNDLE(coll, name='Hello World.app', icon='Hello World.icns', bundle_identifier=None)
To create macOS icons from images you can use the image2icon tool.
If you now re-run the build (by using the command line arguments, or running with your modified
.spec file) you'll see the specified icon file is now set on your application bundle.
Custom application icon on the app bundle
On macOS application icons are taken from the application bundle. If you repackage your app and run the bundle you will see your app icon on the dock!
Custom application icon on the dock
Data files and Resources
So far our application consists of just a single Python file, with no dependencies. Most real-world applications a bit more complex, and typically ship with associated data files such as icons or UI design files. In this section we'll look at how we can accomplish this with PyInstaller, starting with a single file and then bundling complete folders of resources.
First let's update our app with some more buttons and add icons to each.
from PySide2.QtWidgets import QMainWindow, QApplication, QLabel, QVBoxLayout, QPushButton, QWidget from PySide2.QtGui import QIcon import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Hello World") layout = QVBoxLayout() label = QLabel("My simple app.") label.setMargin(10) layout.addWidget(label) button1 = QPushButton("Hide") button1.setIcon(QIcon("icons/hand.png")) button1.pressed.connect(self.lower) layout.addWidget(button1) button2 = QPushButton("Close") button2.setIcon(QIcon("icons/lightning.png")) button2.pressed.connect(self.close) layout.addWidget(button2) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) self.show() if __name__ == '__main__': app = QApplication(sys.argv) w = MainWindow() app.exec_()
In the folder with this script, add a folder
icons which contains two icons in PNG format,
hand.png and
lightning.png. You can create these yourself, or get them from the source code download for this tutorial.
Run the script now and you will see a window showing two buttons with icons.
Window with two buttons with icons. two buttons with icons it will be started with it's current working directory as the root
/ folder --.QtWidgets import QMainWindow, QApplication, QLabel, QVBoxLayout, QPushButton, QWidget from PySide1 = QPushButton("Hide") button1.setIcon(QIcon(os.path.join(basedir, "icons", "hand.png"))) button1.pressed.connect(self.lower) layout.addWidget(button1) button2 = QPushButton("Close") button2.setIcon(QIcon(os.path.join(basedir, "icons", "lightning.png"))) button2.pressed.connect(self.close) layout.addWidget(button2) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) self.show() if __name__ == '__main__': app = QApplication(sys.argv) w = MainWindow() app.exec_()
Try and run your app again from the parent folder -- you'll find that the icons now appear as expected on the buttons, no matter where you launch the app from.
Packaging the icons
So now we have our application showing icons, and they work wherever the application is launched from. Package the application again with
pyinstaller "Hello World.spec" and then try and run it again from the
dist folder as before. You'll notice the icons are missing again.
Window with two buttons with icons missing.
The problem now is that the icons haven't been copied to the
dist/Hello World folder -- take a look in it. Our script expects the icons to be a specific location relative to it, and if they are not, then nothing will be shown.
This same principle applies to any other data files you package with your application, including Qt Designer UI files, settings files or source data. You need to ensure that relative path structures are replicated after packaging.
Bundling data files with PyInstaller
For the application to continue working after packaging, the files it depends on need to be in the same relative locations.
To get data files into the
dist folder we can instruct PyInstaller to copy them over.
PyInstaller accepts a list of individual paths to copy, together with a folder path relative to the
dist/<app name> folder where it should to copy them to. As with other options, this can be specified by command line arguments or in the
.spec file.
Files specified on the command line are added using
--add-data, passing the source file and destination folder separated by a colon
:.
The path separator is platform-specific: Linux or Mac use
:, on Windows use
;
pyinstaller --windowed --name="Hello World" --icon="Hello World.icns" --add-data="icons/hand.png:icons" --add-data="icons/lightning.png:icons" app.py
Here we've specified the destination location as
icons. The path is relative to the root of our application's folder in
dist -- so
dist/Hello World with our current app. The path
icons means a folder named
icons under this location, so
dist/Hello World/icons. Putting our icons right where our application expects to find them!
You can also specify data files via the
datas list in the Analysis section of the spec file, shown below.
a = Analysis(['app.py'], pathex=[], binaries=[], datas=[('icons/hand.png', 'icons'), ('icons/lightning.png', 'icons')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False)
Then rebuild from the
.spec file with
pyinstaller "Hello World.spec"
In both cases we are telling PyInstaller to copy the specified files to the location
./icons/ in the output folder, meaning
dist/Hello World/icons. If you run the build, you should see your
.png files are now in the in
dist output folder, under a folder named icons.
The icon file copied to the dist folder
If you run your app from
dist you should now see the icon icons in your window as expected!
Window with two buttons with icons, finally!
Bundling data folders
Usually you will have more than one data file you want to include with your packaged file. The latest PyInstaller versions let you bundle folders just like you would files, keeping the sub-folder structure.
Let's update our configuration to bundle our icons folder in one go, so it will continue to work even if we add more icons in future.
To copy the
icons folder across to our build application, we just need to add the folder to our
.spec file
Analysis block. As for the single file, we add it as a tuple with the source path (from our project folder) and the destination folder under the resulting folder in
dist.
# ... a = Analysis(['app.py'], pathex=[], binaries=[], datas=[('icons', 'icons')], # tuple is (source_folder, destination_folder) hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) # ...
If you run the build using this spec file you'll see the
icons folder copied across to the
dist\Hello World folder. If you run the application from the folder, the icons will display as expected -- the relative paths remain correct in the new location.
Alternatively, you can bundle your data files using Qt's QResource architecture. See our tutorial for more information.
To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!
For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!
Building the App bundle into a Disk Image
So far we've used PyInstaller to bundle the application into macOS app, along with the associated data files. The output of this bundling process is a folder and an macOS app bundle, named
Hello World.app.
If you try and distribute this app bundle, you'll notice a problem: the app bundle is actually just a special folder. While macOS displays it as an application, if you try and share it, you'll actually be sharing hundreds of individual files. To distribute the app properly, we need some way to package it into a single file.
The easiest way to do this is to use a
.zip file. You can zip the folder and give this to someone else to unzip on their own computer, giving them a complete app bundle they can copy to their Applications folder.
However, if you've install macOS applications before you'll know this isn't the usual way to do it. Usually you get a Disk Image
.dmg file, which when opened shows the application bundle, and a link to your Applications folder. To install the app, you just drag it across to the target.
To make our app look as professional as possible, we should copy this expected behaviour. Next we'll look at how to take our app bundle and package it into a macOS Disk Image.
Hello World.spec file.
pyinstaller "Hello World.spec"
This packages everything up as an app bundle in the
dist/ folder, with a custom icon. Run the app bundle to ensure everything is bundled correctly, and you should see the same window as before with the icons visible.
Window with two icons, and a button.
Creating an Disk Image
Now we've successfully bundled our application, we'll next look at how we can take our app bundle and use it to create a macOS Disk Image for distribution.
To create our Disk Image we'll be using the create-dmg tool. This is a command-line tool which provides a simple way to build disk images automatically. If you are using Homebrew, you can install create-dmg with the following command.
brew install create-dmg
...otherwise, see the Github repository for instructions.
The
create-dmg tool takes a lot of options, but below are the most useful.
create-dmg --help create-dmg 1.0.9 Creates a fancy DMG file. Usage: create-dmg [options] <output_name.dmg> <source_folder> All contents of <source_folder> will be copied into the disk image. Options: --volname <name> set volume name (displayed in the Finder sidebar and window title) --volicon <icon.icns> set volume icon --background <pic.png> set folder background image (provide png, gif, or jpg) --window-pos <x> <y> set position the folder window --window-size <width> <height> set size of the folder window --text-size <text_size> set window text size (10-16) --icon-size <icon_size> set window icons size (up to 128) --icon file_name <x> <y> set position of the file's icon --hide-extension <file_name> hide the extension of file --app-drop-link <x> <y> make a drop link to Applications, at location x,y --no-internet-enable disable automatic mount & copy --add-file <target_name> <file>|<folder> <x> <y> add additional file or folder (can be used multiple times) -h, --help display this help screen
The most important thing to notice is that the command requires a
<source folder> and all contents of that folder will be copied to the Disk Image. So to build the image, we first need to put our app bundle in a folder by itself.
Rather than do this manually each time you want to build a Disk Image I recommend creating a shell script. This ensures the build is reproducible, and makes it easier to configure.
Below is a working script to create a Disk Image from our app. It creates a temporary folder
dist/dmg where we'll put the things we want to go in the Disk Image -- in our case, this is just the app bundle, but you can add other files if you like. Then we make sure the folder is empty (in case it still contains files from a previous run). We copy our app bundle into the folder, and finally check to see if there is already a
.dmg file in
dist and if so, remove it too. Then we're ready to run the
create-dmg tool.
#!/bin/sh # Create a folder (named dmg) to prepare our DMG in (if it doesn't already exist). mkdir -p dist/dmg # Empty the dmg folder. rm -r dist/dmg/* # Copy the app bundle to the dmg folder. cp -r "dist/Hello World.app" dist/dmg # If the DMG already exists, delete it. test -f "dist/Hello World.dmg" && rm "dist/Hello World.dmg" create-dmg \ --volname "Hello World" \ --volicon "Hello World.icns" \ --window-pos 200 120 \ --window-size 600 300 \ --icon-size 100 \ --icon "Hello World.app" 175 120 \ --hide-extension "Hello World.app" \ --app-drop-link 425 120 \ "dist/Hello World.dmg" \ "dist/dmg/"
The options we pass to
create-dmg set the dimensions of the Disk Image window when it is opened, and positions of the icons in it.
Save this shell script in the root of your project, named e.g.
builddmg.sh. To make it possible to run, you need to set the execute bit with.
chmod +x builddmg.sh
With that, you can now build a Disk Image for your Hello World app with the command.
./builddmg.sh
This will take a few seconds to run, producing quite a bit of output.
No such file or directory Creating disk image... ............................................................... created: /Users/martin/app/dist/rw.Hello World.dmg Mounting disk image... Mount directory: /Volumes/Hello World Device name: /dev/disk2 Making link to Applications dir... /Volumes/Hello World Copying volume icon file 'Hello World.icns'... Running AppleScript to make Finder stuff pretty: /usr/bin/osascript "/var/folders/yf/1qvxtg4d0vz6h2y4czd69tf40000gn/T/createdmg.tmp.XXXXXXXXXX.RvPoqdr0" "Hello World" waited 1 seconds for .DS_STORE to be created. Done running the AppleScript... Fixing permissions... Done fixing permissions Blessing started Blessing finished Deleting .fseventsd Unmounting disk image... hdiutil: couldn't unmount "disk2" - Resource busy Wait a moment... Unmounting disk image... "disk2" ejected. Compressing disk image... Preparing imaging engine… Reading Protective Master Boot Record (MBR : 0)… (CRC32 $38FC6E30: Protective Master Boot Record (MBR : 0)) Reading GPT Header (Primary GPT Header : 1)… (CRC32 $59C36109: GPT Header (Primary GPT Header : 1)) Reading GPT Partition Data (Primary GPT Table : 2)… (CRC32 $528491DC: GPT Partition Data (Primary GPT Table : 2)) Reading (Apple_Free : 3)… (CRC32 $00000000: (Apple_Free : 3)) Reading disk image (Apple_HFS : 4)… ............................................................................... (CRC32 $FCDC1017: disk image (Apple_HFS : 4)) Reading (Apple_Free : 5)… ............................................................................... (CRC32 $00000000: (Apple_Free : 5)) Reading GPT Partition Data (Backup GPT Table : 6)… ............................................................................... (CRC32 $528491DC: GPT Partition Data (Backup GPT Table : 6)) Reading GPT Header (Backup GPT Header : 7)… ............................................................................... (CRC32 $56306308: GPT Header (Backup GPT Header : 7)) Adding resources… ............................................................................... Elapsed Time: 3.443s File size: 23178950 bytes, Checksum: CRC32 $141F3DDC Sectors processed: 184400, 131460 compressed Speed: 18.6Mbytes/sec Savings: 75.4% created: /Users/martin/app/dist/Hello World.dmg hdiutil does not support internet-enable. Note it was removed in macOS 10.15. Disk image done
While it's building, the Disk Image will pop up. Don't get too excited yet, it's still building. Wait for the script to complete, and you will find the finished
.dmg file in the
dist/ folder.
The Disk Image created in the dist folder
Running the installer
Double-click the Disk Image to open it, and you'll see the usual macOS install view. Click and drag your app across the the
Applications folder to install it.
The Disk Image contains the app bundle and a shortcut to the applications folder
If you open the Showcase view (press F4) you will see your app installed. If you have a lot of apps, you can search for it by typing "Hello"
The app installed on macOS
Repeating the build
Now you have everything set up, you can create a new app bundle & Disk Image of your application any time, by running the two commands from the command line.
pyinstaller "Hello World.spec" ./builddmg.sh
It's that simple!
Wrapping up
In this tutorial we've covered how to build your PySide2 applications into a macOS app bundle using PyInstaller, including adding data files along with your code. Then we walked through the process of creating a Disk Image to distribute your app to others. Following these steps you should be able to package up your own applications and make them available to other people.
For a complete view of all PyInstaller bundling options take a look at the PyInstaller usage documentation. | https://www.pythonguis.com/tutorials/packaging-pyside2-applications-pyinstaller-macos-dmg/ | CC-MAIN-2022-40 | refinedweb | 4,143 | 50.94 |
At 04:22 PM 10/24/2001 -0400, Geoff Talvola wrote:
.
I agree with this line of thought regarding modularity and ease of extension.
How about the idea of an "applet" which is an instance that can be attached
to an application via either configuration or run time code (often found in
your initializeContext() function)?
class Applet:
def __init__(self):
self._app = None
def app(self):
return self._app
def name(self):
return self.__class__.__name__
def wasInstalled(self, app):
self._app = app
def shutDown(self):
pass
app.addApplet(MyApplet())
The application would maintain a list of these and send them all shutDown()
when it shutdown.
Application.applet('foo') would return an applet by name, possibly
returning a list in the case of name collisions. As the application
developer you would decide if such name collisions would/could happen and
either deal with it, or not.
Basically, this approach allows you to attach arbitrary instances to the
application for whatever purposes you desire and hook into application
level events like shutDown(). I'm not sure if there would be any other
events in the future.
I'd also like to provide a file system structure for applications where it
would be easy to drop in a custom subclass of Application for your project.
Inheritance and composition are both valid ways to extend a class and
WebKit should make both easy for Application.
If Applet is well received and remains fairly simple, we could sneak it
into the 0.6 release. If it's not well received or blows up in complexity
(as these things often do), then we'd wait for 0.7.
Let the e-mails begin...
-Chuck
View entire thread | http://sourceforge.net/p/webware/mailman/message/10274991/ | CC-MAIN-2014-52 | refinedweb | 282 | 66.23 |
Can you imagine the programming process without the possibility of debugging program code at run-time? It is obvious that such programming may exist, but programming without debugging possibility is too complicated when we are working on big and complex projects. In addition to standard approaches of debugging program code such as an output window on Visual Studio IDE or the macros of asserts, I propose a not new method for debugging your code: to output your debugging data to an application which is separated from Visual Studio IDE and the project you are currently working on.
Launch the application of trace messages catcher (next: trace catcher) before you start working with this module. Tracing data, sent to the trace catcher application, will be saved if the catcher application was inactive or was terminated during the trace operations. All the data which have been saved during the critical situations, as described above, will be kept and popped-out to trace catcher application when it starts again. There�s a possibility to start the trace catcher application with the creation of the trace module, and terminate it when the trace module is being destructed.
As I mentioned, this trace module allows you to put your trace data to several output windows in trace catcher application (next: trace channels). Trace channel is a simple window which helps to visualize your tracing data by the trace catcher application. In order to add your trace data to a certain trace channel, you must describe it as follows:
_Log.setSectionName( "channel_#1" ); _Log.dump( "%s", "My trace data" );
or
_Log.dumpToSection( "channel_#1", "%s", "My trace data" );
If you send your trace data to the new trace channel which is not created in the trace catcher application, new trace channel will be created automatically.
In addition to sending your trace data to the catcher, there�s a possibility to manipulate the trace catcher application with commands help. Commands are divided into two parts: global commands, and commands which depend to the trace channel.
closeRoot� close the trace catcher application;
onTop.ON� enable always on top state for the catcher application;
onTop.OFF� disable always on top state for the catcher application.
Example:
_Log.sendCmd( "closeRoot" ); _Log.sendCmd( "onTop.ON");
clear- deleting the entry of given trace channel;
close- closing the given trace channel;
save<path to output stream> - saving the entry of the given trace channel to output stream described by you.
Example:
_Log.sendCmd( "Channel_1", "clear" ); _Log.sendCmd( "Channel_2", "save c:\\channel2.log" ); _Log.sendCmd( "close" ); /** close the current output window (section) */
In order to fully use this trace module, you have to do only two steps:
An example:
#include "path_by_you\LogDispathc.dir\LogDispath.h"</pre>
To call all this messages described below, you must use variable names as follows: [_Log]. The trace object is created once during the project life-time (using singleton pattern).
Let's say, calling the dump message will be described like that:
_Log.dump( "System time is %d %d %5.5f ", 15, 10, 08.555121 );
dump� formatted trace data (
sprintfformat) are sent to catcher application. The tracing data will be placed to the section named as the result of calling method "
setSectionName" before that, or if the method "
setSectionName" wasn�t called, tracing data will be placed to the default section named as "
output@default".
dumpToSection� the principle is the same as dump message. The difference is that this message will place your data to the channel by name which you described in this message.
setSectionName� set the working (active) channel name.
getCmdPrefix� sets the prefix of the command.
setCmdPrefix� returns the prefix of the command.
sendCmd� sends your message to the receiver application.
setCloseOnExit� enables/disables the possibility to send the message to the catcher application on exit.
setCloseCMDOnExit� sets the command of the catcher application which will be send when the trace module will be destroyed.
setClassNameOfCatcher� set the class name of the catcher application. That class name will be used in search of the catcher application where the tracing data will be sent.
runCatcher� executing the catcher application from the described path.
This trace module and the strategy we are using on it is very flexible, and is an effective trace tool for debugging big projects. In my opinion, this tool will be a very effective strategy to trace release versions of the projects where all debugging data are removed. Very easy and comfortable to use it :].
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/debug/LogDispatch.aspx | crawl-002 | refinedweb | 748 | 55.34 |
Left unchecked, tight coupling between components (especially when distributed around your application) can slowly kill your software; rendering it hard to maintain and much more likely to suffer from bugs.
In software engineering, coupling is the manner and degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules.
When developing software, we tend to keep a mental picture of the software we write as we go along. This is why developers so often complain about interruptions; because it takes time to build that mental map of the problem you’re working on and any interruption can set you back causing you to pick up the pieces and start building the picture again.
Even when you split your code into multiple classes you have knowledge of the “other half” of the equation (the calling or called classes).
Born together
As a result, it’s easy to couple the software together. At the exact moment you write the code, the coupling is hidden from you because your mental map encompasses both halves of the solution. In effect it is entirely possible to simply take an implementation, divide it in half and spread it between two classes. The two classes end up depending on each other and consequently they are forever joined and rippling changes are inevitable.
Probably the most blatant coupling you’ll ever see in code is magic strings. As soon as we use “Apple” in two places we’ve coupled our code together. It only takes one of them to be renamed to break our application.
When it comes to how damaging this coupling is, distance matters.
We can weaken the coupling by bringing it closer together. If these two strings exist within the same small method then the coupling may well be manageable. Anyone who looks at the code will see both usages of the string and understand that changes to the declaration will affect the usage.
But when the coupling is spread around your app then the risk of bugs dramatically increases.
Coupling is usually contrasted with cohesion. Low coupling often correlates with high cohesion, and vice versa. Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability.
Exceptional coupling
Magic strings are easy enough to spot; here’s a different example.
public class ShoppingCart { private Dictionary<string, int> _products = new Dictionary<string, int>(); private int _total; public ShoppingCart() { _products["apple"] = 10; _products["pear"] = 20; } public void Scan(string item) { if (!_products.ContainsKey(item)) throw new UnknownItemException(); else _total += _products[item]; } }
Our favourite Kata presents a different problem. If the calling code attempts to scan a non-existent item, what should happen?
The approach taken here introduces a few issues.
- Tight coupling between the exception being thrown and the code which handles it.
- The calling code has to assume knowledge of which exceptions might be thrown and then handle them.
- The exception may bubble up through the application and may not be handled at all.
- If the exception is eventually caught, the handling code may be a long way away from the shopping cart where the problem originated.
- When reasoning about the code starting at the top of the application it’s entirely possible we’ll have to click through several layers to find what might throw such an exception in the first place.
We can weaken this coupling by ensuring that our calling code doesn’t rely on knowledge of the logic inside our shopping cart. One way is to use a delegate method.
public class ShoppingCart { public void Scan(string item, Action itemNotFound) { if (!_products.ContainsKey(item)) itemNotFound(); else _total += _products[item]; } }
By providing our shopping cart with a coping strategy for missing items, we’ve ensured that the calling application retains control of the details of how to handle the error and our shopping cart need only execute the provided coping strategy when it makes sense to do so.
public class Application { public void Main() { var cart = new ShoppingCart(); cart.Scan("mango", () => Render.ErrorMessage("Item not recognised")); } }
Bonus C# 6 Feature
There is one slight wrinkle with our code, if null is passed as the second argument to our scan method our code will blow up. We should really check if we have a handler before calling it.
public void Scan(string item, Action itemNotFound) { if (!_products.ContainsKey(item)) { if(itemNotFound != null) itemNotFound(); } else _total += _products[item]; }
Luckily, if you happen to be using C# 6 you can take advantage of the null-conditional operator to seamlessly handle this possibility without the conditional if statement.
public void Scan(string item, Action itemNotFound) { if (!_products.ContainsKey(item)) { itemNotFound?.Invoke(); } else _total += _products[item]; }
In summary
Of course there are many other forms of coupling. Put the effort into learning to spot them. By identifying and reducing coupling in your code, your application can live a long and happy life.
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #2049()
Pingback: We're not gonna link. We can't link, Bendis. You know why? Because we are so very pretty. We are just too pretty for God to let us link - Magnus Udbjørg()
Pingback: Les liens de la semaine – Édition #175 | French Coding()
Pingback: Dew Drop – March 14, 2016 (#2207) | Morning Dew()
Pingback: Reduce coupling: Free your code and your tests - JonHilton.Net() | https://jonhilton.net/2016/03/09/why-coupling-will-destroy-your-application-and-how-to-avoid-it/ | CC-MAIN-2017-30 | refinedweb | 911 | 61.56 |
What am I doing wrong here?? Am I reading the file in correctly? What if any thing is wrong with the Bucket Sort part? It is supposed to output what the array looks like after each pass and then again after the array is sorted making the minimum # of passes. Also, I am supposed to output what the largest # is and how many digits it is. Thanks again guys!
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
ifstream infile ("/u3/svlasnik/values");
const int size = 6;
int array[size] = { 0 };
for ( int x = 0; x < size ; x++ )
infile >> array[x];
int *bucketData;
*bucketData = array[size - 1];
for(int i = 0; i < array[size - 1]; i++)
{
bucketData[i] = (rand() % 1000) / 1000.0;
for ( int x = 0; x < size ; x++ )
cout << "Look, here's value " << x << ": " << array[x] << endl;
}
return 0;
} | http://cboard.cprogramming.com/cplusplus-programming/15605-bucket-sort-printable-thread.html | CC-MAIN-2016-18 | refinedweb | 142 | 75.4 |
Better Scaffolding with jQuery - Part II
In Part I of this series I showed how we can improve the user experience by changing the default scaffolding when saving the many side of a one-to-many association. The server side code changes were minimal and jquery made the client side changes very simple and elegant. There are still some improvements that can be made and the most glaringly obvious one is how we handle validation errors. I'm going to be using the same code base as last time and just making changes to it. It might be helpful to have the first article open in a tab especially if you missed it the first time around.
The first area we need to talk about is the server side. Remember that before all we had to change was when there was a successful save on the reminder we simply wanted to return an instance of the reminder back to the client as JSON. Now that we need to display errors if validation fails we need a bit more than the domain instance. Even though the domain instance should contain our errors, picking them out in JavaScript is not a fun task and we also want an easier way to determine if errors exist. Remember that with JSON we get object properties but not object methods. So we can't call hasErrors() in JavaScript. We want to create a wrapper object that can hold the information we need in a very simple way that can then be returned to the client as JSON. I call this object AjaxPostResponse.groovy.
class AjaxPostResponse {
boolean success
String message
def domainInstance
def errors = [:]
}
Complicated, right? I think most of the properties are self explanitory. But just for clarity:
- success - whether or not save was successful
- message - a generic optional message
- domainInstance - we'll need properties of the domain instance if all was good to use in JavaScript
- errors - a map of the errors if validation fails
We will need to change ReminderController to use this class however, since there's a little bit of code involved with digging out the errors from a domain, I prefer to place the code in a service class. In some applications I use a generic service for these kinds of purposes but for simplicity and less confusion for this tutorial we'll create a ReminderService, since that is the only place the code is relavent right now.
class ReminderS
}
}
This code appears a bit gnarly but it's really quite simple. We need to define a variable to hold our grails ApplicationTagLib because we're not inside a controller so this isn't already injected for us. We then need an instance of our AjaxPostResponse. We then check the domainInstance for errors and if we found some we wire up the errors map in AjaxPostResponse with the errors utalizing some grails taglibs along the way. Add the success value and message value depending on the error state, our domainInstance, and just return the postResponse. This service is called from our ReminderController. The save method is much simpler than it was before:
def save = {
def reminderInstance = new Reminder(params)
reminderInstance.save(flush: true)
render reminderService.prepareResponse(reminderInstance) as JSON
}
Since we're putting all the validation logic in the service and AjaxPostResponse the controller doesn't care if validation failed or not. We delegate the responsibility back to the client since that's it what needs to know about it. There's one more addition we need on the server side and that's to make our error messages less generic than the grails defaults. Add the following to your messages.properties file in the i18n directory:
com.Reminder.duration.nullable=Please enter a Duration
typeMismatch.com.Reminder.duration=Duration must be a number
On the client we need to make a handful of changes. First we need a place to show any error messages that might come back. Add a div with a class of 'errors' to the dialog form. If you recall this is in the event/edit.gsp:
<div id="dialog-form" title="Create new Reminder">
<div class="errors"></div>
<g:form
<% -- more code below here --%>
</div>
Next, we need to modify what happens when our response comes back from our ajax request. Remember that before we were simply returning Reminder as JSON but now we're returning AjaxPostResponse as JSON. Here is what that bit of code looks like now:
if (data.success) {
var item = $("<li>");
var link = $("<a>").attr("href", contextPath + "/reminder/show/" + data.domainInstance.id).html(data.domainInstance.reminderType.name + " : " + data.domainInstance.duration);
item.append(link);
$('#reminder_list').append(item);
cleanup();
$('#dialog-form').dialog('close');
} else {
showErrors("#dialog-form .errors", data.errors);
}
It's not much different although instead of data.id we have to call data.domainInstance.id (because domainInstance is a property of AjaxPostResponse). We also check if data.errors is true first. If it is, we append a reminder to the list, just like before, we do some cleanup (explained in a bit) and close the dialog. If there were errors we need to show them. I've created a function called showErrors that accepts a target and the map of errors:
function showErrors(target, errors) {
var errorList = $("<ul>");
for (field in errors) {
errorList.append("<li>" + errors[field] + "</li>")
}
$(target).html("").append(errorList).show(500);
}
We create a UL, loop over each key in the errors map, and create a list item containing the error message that was populed from the server. Then we clear out any existing messages and append our list and show it. Speaking of showing the errors list; tt needs to be hidden when the dialog is displayed the first time. You can do this simply by calling $("#dialog-form .errors").hide() manually at the top of your JavaScript code or setting a style. Keep in mind that grails uses the'.error' class also, which is nice for us because it is already styled, but that also means you must take care and use a better selector at getting to them, as I did. Otherwise you might change existing markup when not expecting to.
If the save was successful we need to do some cleanup. If there were errors previously these errors need to be cleared out and the dialog's form needs to be reset. Remember that this dialog is being built when the edit page is first rendered so if you don't reset the form you'll get old data every time you display it. Our cleanup() method takes care of this, which actually consists of 2 seperate methods, both shown below:
function cleanup() {
$('#dialog-form .errors').html("");
$('#dialog-form .errors').hide();
clearForm('#dialog-form form');
}
function clearForm(target) {
$(':input', target)
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
cleanup() clears the errors, hides the div and calls clearForm which simply filters down through all our form elements and sets their values to empty strings and unchecks/unselects any items. When all is said and done you'll end up with a dialog that looks something like this if you have validation errors:
There was a little more involved in getting this from the server to the client but most of the techniques are very reusable across all similar situations. In the next installment in this series we'll change the code so that the dialog is pulled from an ajax request and in the final installment, Part IV, I'll show how we can edit a reminder using the same dialog. I hope you are enjoying the series thus far. Please feel free to offer recommendations for improvement and any general feedback is much appreciated.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Tony Ross replied on Tue, 2010/05/04 - 7:23am
Aaron Epps replied on Fri, 2011/03/18 - 10:04am
groovy.lang.MissingPropertyException: No such property: lastName for class: org.springframework.validation.BeanPropertyBindingResult
I've modified your code to use my own Customer class, which looks like:
package grailsapplication1
class Customer {
static constraints = { firstName(blank:false,maxSize:50) lastName(blank:false,maxSize:50) age(nullable:true) emailAddress(nullable:true) } String firstName String lastName Integer age String emailAddress }
Here's the CustomerService
package grailsapplication1
class CustomerS } }
It's throws the error on the line:
g.eachError(bean: domainInstance) {
Any idea what I'm doing wrong here?
Gregg Bolinger replied on Fri, 2011/03/18 - 12:38pm
Aaron Epps replied on Fri, 2011/03/18 - 3:34pm
in response to:
Gregg Bolinger
def save2 = {
def customerInstance = new Customer(params)
customerInstance.save(flush: true)
render customerService.prepareResponse(customerInstance) as JSON
}
...for what's it worth I'm usinig NetBeans 6.9.1 and Grails 1.3.7
Aaron Epps replied on Fri, 2011/04/08 - 1:49pm
Aaron Epps replied on Mon, 2011/04/11 - 1:06am
in response to:
Aaron Epps | http://java.dzone.com/articles/better-scaffolding-jquery-part-0 | CC-MAIN-2013-48 | refinedweb | 1,494 | 63.09 |
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site.
spawnerItem = new SlimeSpawnerItem(EntitySlime)
public class SlimeSpawnerItem extends Item {
private static final Entity entityToSpawn = null;
public SlimeSpawnerItem(Entity par1Entity)
{
final Entity entityToSpawn = par1Entity;
}
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
if (!par3EntityPlayer.capabilities.isCreativeMode)
{
--par1ItemStack.stackSize;
}
par2World.playSoundAtEntity(par3EntityPlayer, "mob.wither.spawn", 0.5F, 0.4F);
if (!par2World.isRemote)
{
par2World.spawnEntityInWorld(entityToSpawn);
entityToSpawn.setLocationAndAngles(par3EntityPlayer.posX, par3EntityPlayer.posY + 1, par3EntityPlayer.posZ, MathHelper.wrapAngleTo180_float(par2World.rand.nextFloat() * 360.0F), 0.0F);
}
return par1ItemStack;
}
}
new EntitySlime(par2World);
I'm working on an open-source mod called Craft++. Check it out!
spawnerItem = new SlimeSpawnerItem(new EntitySlime(par2World))
Quote from im2awsm»Uhm.. that doesn't seem to work.
spawnerItem = new SlimeSpawnerItem(new EntitySlime(par2World)) par2World cannot be resolved to a variable. Please note that both these lines of code aren't in the same class... I don't know how I'll acess par2World
spawnerItem = new SlimeSpawnerItem(new EntitySlime(par2World))
Quote from Vic_»Also, @ShadowedEclipsis, no offense, but if you don't have any productive reply to a topic you better just NOT reply to it.
Quote from Vic_»
There was a time when wasting space in the id range was a bad thing and I still hold on to this practice even tho there aren't any ids left to be concerned of. Feel free to do it by instancing an Item type, It just doesn't feel right to me, I guess it's a style choice mostly.
Quote from Vic_»TileEntities? The "runtime logic sorcery" has no limits
[url=2482915-wip-arkcraft-survival-evolved-dinos-taming]
package main;
public ItemEntitySpawn extends Item
{
}
private final Class<!--? extends EntityLivingBase--> clazz;
public ItemEntitySpawn(Class<!--? extends EntityLivingBase--> clazz)
{
//all the stuff you normally do for an Item.
this.clazz = clazz.
}
EntityLivingBase entity = clazz.getConstructor(World.class).newInstance(world);
Item pigSpawner = new ItemEntitySpawn(EntityPig.class);
Hello!
Quote from CosmicDan»Mmm if it's a heck load of similar items then I don't see why you can't just have parameters to your constructor and use final class fields for the stuff that differs between each item. That's wise if all the items are functionally identical, but if they can have very different behaviors then it's more efficient to have a base class and extend it multiple times as needed. You could always do a combination of both too.
Quote from wildbill22»
I took Java in school, but that was awhile ago, so I just looked up why you would use a final class fields.
I found this tutorial that explains it well:
public class MyGui extends GuiScreen {
static final ResourceLocation MyGuiBackground = new ResourceLocation("mymod:textures/gui/mygui.png");
[...]
}
Quote from Vic_»
To be honest, I don't care much about about assign performance (the difference here, one or two ops is like... nothing), there are more severe bottlenecks I have to fight, for example how to sync a circuit board without using a ridiculous amount of bandwidth, saving precious ram by using bitshifts, how to render a circuit board with 64 ^ 2 components and repetitive background without killing the performance or letting the ram usage explode... I wish I could care about one or two opcodes more or less!
because it gives the error "EntitySlime cannot be resolved to a variable" FFFFFFFF-
Here's the code for 'SlimeSpawnerItem':
Replace EntitySlime with
I'm working on an open-source mod called Craft++. Check it out!
par2World cannot be resolved to a variable. Please note that both these lines of code aren't in the same class... I don't know how I'll acess par2World
Make the variables public then access it from the class you want (I think)
If you thought something was missing in Minecraft, think again.
MoreMine is coming soon for Minecraft 1.7.10
If I helped you, hit that green arrow!
Look at ItemMonsterPlacer (mob eggs).
None taken, just trying to help. .-.
If you thought something was missing in Minecraft, think again.
MoreMine is coming soon for Minecraft 1.7.10
If I helped you, hit that green arrow!
You can check out my custom spawn egg tutorial here:
In that tutorial, when I create the item instance to the constructor I pass a string for the name of the entity I want to spawn, and I pass the colors for the egg and spots.
So I only have one class, but can use it for multiple different entities.
EDIT: Also you *need* to do subclasses in some things, TileEntities for example.
Oh good point, more relevant before 1.7.x. I would prefer to subclass myself still, just easier to work with - but clearly a matter a taste. I can see how putting a bunch of items/blocks into one class keeping it compact has appeal, and I may very well do it one day.
But Java/Minecraft/CPU number of ops per cycle does :\
One improvement to the code would to replace: ArrayList spawndata = Lists.newArrayList();
With the generic version of ArrayList: ArrayList<EntitySpawData> spawndata = Lists.newArrayList();
This allows you to do: spawndata.get(I).id
Instead of ((EntitySpawData) spawndata.get(I)).id
[url=2482915-wip-arkcraft-survival-evolved-dinos-taming]
I was surprised how much you were able to do. I still haven't mastered putting more than one code segment in.
[url=2482915-wip-arkcraft-survival-evolved-dinos-taming]
Then for the constructor, you can have it like this.
Then when you go to spawn the entity in the item use or right click function or wherever you spawn it. You can create the entity by using the class like so:
This will give you a new instance of whatever class of entity you put in.
Now to create the item, in your mod file (or wherever you create items) write:
Hopefully this will work. To setup the whole entity rotation and positioning to is doesn't spawn in the wall, look into the ItemMonsterSpawner class.
Thanks for reading!
Hope this helps! If not, let me know! I HAVE NOT TESTED THIS! It's just a way I would test it. If you already have something from this whole thread, and don't want to throw it away. Forget this comment and continue getting help on the other way you're doing it! Again, thanks for reading, Happy Modding!
Hello!
Item item1 = new Item(...);
Item item2 = new Item(...);
Item item3 = new Item(...);
etc..
But great answers!
Hello!
I took Java in school, but that was awhile ago, so I just looked up why you would use a final class fields.
I found this tutorial that explains it well:
[url=2482915-wip-arkcraft-survival-evolved-dinos-taming]
Yeah. It's not just for better performance, but it's just the right way to do things. If you have a variable that you only need to set once, make it final. Always make class fields final when possible, especially if they are read a lot. The Java JIT is stressed to heck by Minecraft, and these help a lot with it.
Another thing. If you access a non-final class field in a method more than a few times, it's technically better to assign that class field to a new local final variable. Reason is that a fetch from a local final variable is only one Java op, but a fetch from a class field is at least 2 ops. Assignment to a new local field is at least 2 ops. So say, if you've got a TileEntity or something that reads a class field 20+ times every tick (in onUpdate), *definitely* set it to a new local final variable at the top of onUpdate. Here's a technical discussion on this from StackOverflow if you want some more info.
Also, if you *assign* a class field immediately, it's good to make it static. E.g:
But I digress... a lot, again. Obviously, Java performance and convention are important to me - Modded Minecraft ain't getting any faster
I agree that when it comes to performance optimization, while it is good to keep it in mind during coding you shouldn't let it get in the way of proper coding style unless it is necessary -- and necessary means you have proven that it is actually causing performance problems.
Making unchanging class variables final is both proper programming and also better performance so is something definitely you should do as normal practice. However, the metadata strategy in Minecraft is an example where necessity (due to sheer number of blocks in the world) created a somewhat overly cryptic and limited approach -- default programming strategy would have used a much more readable and extensible way to store data per block, but they quickly realized that they needed a compact method like metadata.
I see a lot of people doing overly tricky things for "performance" on things that are not real performance issues -- things that are only done occasionally, etc. First principle of programming (in my humble opinion) is to create readable, simple, well structured code and only get tricky when pushed due to necessity. | https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/minecraft-mods/modification-development/2279316-minecraft-forge-using-less-classes-with-similar?page=2 | CC-MAIN-2019-13 | refinedweb | 1,527 | 63.7 |
have configured Adyen as a payment gateway for your account. This will allow your developers to enter their credit card details, and you can automatically charge them through Adyen for access to your API, according to the calculated invoices.
Setting up your payment gateway is a key step enabling credit card charging for use of your paid API. There are a number of alternative payment gateways you can use with your 3scale account. Here we cover the steps for Adyen.
3.1. Prerequisites
Before you start these steps, you’ll need to open an account with Adyen. You need a Company account and a Merchant account within it (sub-account). There are a number of requirements that must be fulfilled before you can apply for a live account with Adyen. You can see what those requirements are here.: Enable the "alias" additional data in the Adyen API response
By default when credit card authorization requests are sent from 3scale to Adyen, the returned response does not include the unique identifier of the credit card. To ensure that the correct credit card reference is saved in 3scale and the correct card is charged, this additional data needs to be enabled. In order to do this, you should ask Adyen support to enable the "alias" additional data in the response for the authorization request.
3.2.3. Step 4: Test your billing workflow
Make sure you accelerate the test cycle by enabling Prepaid Mode to generate the charge within a day or so. Then choose an existing test account and create an invoice with a line item charge added. Charge the account immediately. This testing approach will incur some minor costs, but it is worth it for the peace of mind that everything works fine, before you have real paying developers using your API.
The payment gateway is now set up, but your users might not be able to use it yet since it is not configured in the CMS. Go to the developer portal tab, and find the template called Payment Gateway / Show on the left navigation pane.
If it’s not there already, add the following snippet after the block of code beginning with
{% when "stripe" %}
{% when "adyen12" %} {% if current_account.has_billing_address? %} {% adyen12_form %} {% else %} <p><a href="{{ current_account.edit_adyen12_billing_address_url }}">First add a billing address</a></p> {% endif %}
- For accounts created before 11th May 2016 you must add the snippet above manually. After said date this will be included in the template by default.
- In order to map your data from Adyen with your data on 3scale, you can use the Adyen field called
shopperReferencewhich is composed of
3scale-[PROVIDER_ID]-[DEVELOPER_ACCOUNT_ID]..
6.1. Prerequisites
Before you start these steps, you will need to open an account with Stripe.
6.2. Step 1: Get_13<<.
_18<<.
6.3.1. Note
In order to map your data from Stripe with your data on 3scale, you can use the Stripe field called
metadata.3scale_account_reference which is composed of
3scale-[PROVIDER_ID]-[DEVELOPER_ACCOUNT. | https://access.redhat.com/documentation/en-us/red_hat_3scale/2.3/html/billing/ | CC-MAIN-2018-51 | refinedweb | 495 | 62.07 |
Posts20
Joined
Last visited
Days Won1
Everything posted by Gandalf64
I want to disable a specific day on calendar HELP
Gandalf64 replied to ms115's topic in PHP Coding HelpI developed my own calendar and if I am understanding you correctly then you could do something like the following: protected function checkForEntry($calDate, $page = 'index.php') { $this->username = isset($_SESSION['user']) ? $_SESSION['user']->username : \NULL; $this->query = 'SELECT 1 FROM cms WHERE page=:page AND DATE_FORMAT(date_added, "%Y-%m-%d")=:date_added'; $this->stmt = static::pdo()->prepare($this->query); $this->stmt->execute([':page' => $page, ':date_added' => $calDate]); $this->result = $this->stmt->fetch(); /* If result is true there is data in day, otherwise no data */ if ($this->result) { return \TRUE; } else { return \FALSE; } } then simply disable the day though you don't have to use a database table to do this as I was just showing it's pretty simple. That is if I'm understanding correctly?
Namespace and PSR-4 Autoloader
Gandalf64 replied to NotionCommotion's topic in PHP Coding HelpI found this link explaining Namespace and PSR-4 Autoloader to be pretty informative.
Event calendar- adding blank white cells after the last date
Gandalf64 replied to hgkhkhk's topic in PHP Coding HelpI have a repository (actually a couple of repositories) on creating a calendar in php at I basically start of the premise of have 7 rows as the calendar I want to display for it will cover the previous month days (Starting with the first week of the selected month) and continuing to fill in the days as needed which more than likely will cover future month's days.
Need help-Strobogrammatical numbers
Gandalf64 replied to adrianpat's topic in PHP Coding HelpHere's my version -> <?php function IsPrime($n) { for ($x = 2; $x < $n; $x++) { if ($n % $x == 0) { return 0; } } return 1; } function isStrob($num) { $myNumber = str_split($num); for ($i = 0; $i <= count($myNumber) / 2; $i++) { $c = $myNumber[$i]; $b = $myNumber[count($myNumber) - 1 - $i]; if (!isValid($c, $b)) { return FALSE; } } return TRUE; } function isValid ($c, $b) { switch ($c) { case '1': return $b == '1'; case '6': return $b == '9'; case '9': return $b == '6'; case '8': return $b == '8'; case '0': return $b == '0'; default: return FALSE; } } function get_strobogrammatic_numbers($total = 10000) { for ($i = 0; $i <= $total; $i++) { $status = isStrob($i); if ($status) { $strob_numbers[] = $i; } } return $strob_numbers; } $result = get_strobogrammatic_numbers(1000); //echo "<pre>" . print_r($result, 1) . "</pre>"; ?> <!DOCTYPE html> <html lang="en"> <head> <title>Test Upside Up</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div>Strobogrammatic Numbers</div> <?php echo "<p>"; for ($x = 0; $x < count($result); $x++) { if ($x === count($result) - 1) { echo $result[$x] . ".<p>"; } else { echo $result[$x] . ", "; } } ?> </body> </html>
Add 3 days to date
Gandalf64 replied to toolman's topic in PHP Coding HelpOr you could use DateTime() -> <?php $variableDate = "October 8, 2017"; /* * DateTime & DateTimezone are classes built into PHP. */ $myDate = new DateTime($variableDate, new DateTimeZone("America/Detroit")); /* * N is a numeric representation -> 1 (for Monday) through 7 (for Sunday) */ if ( $myDate->format("N") < 6) { $myDate->modify("+3 days"); // modify is a method (function) that does what it says { similar to strtotime } } else { $myDate->modify("+5 days"); } echo $myDate->format("l, F j, Y") . "<br>"; // Display it in the format of your choosing:
Insert Into statement
Gandalf64 replied to sraidr69's topic in PHP Coding HelpFirst simply turning on error reporting (without exemptions) should had help you out or pointing into you into the right direction. Second I would minimize at first what you are trying to insert into database. Here's an example of of a tutorial that I starting on php pdo function createLogin(array $data, $pdo) { /* Secure the Password by hashing the user's password. */ $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT, array("cost" => 15)); try { /* Set the query variable */ $query = 'INSERT INTO myUsers (name, password, email, security, confirmation, date_added) VALUES (:name, :password, :email, :security, :confirmation, NOW())'; /* Prepare the query */ $stmt = $pdo->prepare($query); /* Execute the query with the stored prepared values */ $result = $stmt->execute([ ':name' => $data['name'], ':password' => $data['password'], ':email' => $data['email'], ':security' => $data['security'], ':confirmation' => $data['confirmation'] ]); // End of execution: return TRUE; } catch (PDOException $error) { // Check to see if name is already exists: $errorCode = $error->errorInfo[1]; if ($errorCode == MYSQL_ERROR_DUPLICATE_ENTRY) { error_log("Duplicate Name was Enter", 1, "[email protected]"); } else { throw $error; } } } thirdly I would take a look at your database table structure, for example here's the structure of the above in MySQL: $sql = "CREATE TABLE IF NOT EXISTS myUsers (" . "ID int(11) AUTO_INCREMENT PRIMARY KEY," . "name varchar(60) NOT NULL," . "password varchar(255) NOT NULL," . "email varchar(60) NOT NULL," . "security varchar(25) NOT NULL," . "confirmation varchar(255) NOT NULL," . "date_added datetime NOT NULL DEFAULT '0000-00-00 00:00:00')"; the above is part of a script that I wrote for an install script, but you can get the structure using phpMyAdmin. Looking over the structure should give you an idea where you forgot to cross a t or dot an i. HTH John
PHP MVC structure and dynamic URL re-writing
Gandalf64 replied to Tahhan's topic in PHP Coding HelpThat for me was the hardest part in writing clean URLS and I don't know why? I would have this in my .htaccess file RewriteRule ^(index|about|blog|calendar|contact|edit|login|order)$ $1.php [NC,L] RewriteRule ^edit/(\d+)$ edit.php?id=$1 [NC,L] but forget I had to do this echo '<a class="edit" href="edit/' . $this->row->id . '">Edit</a>'; I would spend days trying to get it work and finally a light bulb turned on, but until I did figure it out it was like I was myself.
Blank Page in Script slide show
Gandalf64 replied to sagar_24's topic in Javascript HelpIt just so happens I developed a script that does just that, by that I mean takes images from a particular directory and made a very simple slideshow (actually it rotates). I recently took it down from my website, so I can't show it in action but here's a test script that I made. <style> /* essential styles: these make the slideshow work */ #slides { position: relative; height: 400; } </style> <?php $supported_file = [ 'gif', 'jpg', 'jpeg', 'png' ]; $files = glob("assets/uploads/*.*"); echo '<ul id="slides">' . "\n"; for ($i = 0; $i < count($files); $i++) { $image = $files[$i]; // Just making it easier to understand that $files[$i] are the individual image in the loop: $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION)); if (in_array($ext, $supported_file)) { /* * echo basename($image); ### Shows name of image to show full path use just $image: */ if ($i === 0) { echo '<li class="slide showing"><img src="' . htmlspecialchars($image) . '" alt="Slide Show Image"></li>' . "\n"; } else { echo '<li class="slide"><img src="' . htmlspecialchars($image) . '" alt="Slide Show Image"></li>' . "\n"; } } else { continue; } } echo "</ul>\n"; ?> <script> var slides = document.querySelectorAll('#slides .slide'); var currentSlide = 0; var slideInterval = setInterval(nextSlide, 3000); function nextSlide() { slides[currentSlide].className = 'slide'; currentSlide = (currentSlide + 1) % slides.length; slides[currentSlide].className = 'slide showing'; } </script> No Javascript Library needed (I been developing pure javascript lately).
ajax auto search and display dropdown
Gandalf64 replied to dishadcruze's topic in Javascript HelpI personally would use an addEventListener instead of inline javascript like this example: selectBtn.addEventListener("change", function (event) { event.preventDefault(); selectCompany(); // Ajax or what have you function. }, false); // End of addEventListener Function: the Ajax would be something that you will have to figure out. However, doing it this way it would be easier to daisy chain or do whatever you are trying to do. For example I generate blog postings based on the person selected and the following is the ajax portion based on what the visitor of the website chooses. Me bad, The following is the callback portion of the Ajax. function displayBlog(url, formData, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 2) { //console.log(xhr.status); } if (xhr.readyState == 4 && xhr.status == 200) { //console.log(xhr.readyState); callback(xhr.responseText); } }; // End of Ready State: xhr.open('POST', url, true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(formData); } Here's the Ajax CALL of the javascript. /* * Display Blog that user selects */ function selectUser() { removeElementsByClass('cms'); var url = 'select_user.php'; var form_data = serializeFormById('selectBlog'); displayBlog(url, form_data, function (result) { //console.log(result); var json = JSON.parse(result); generateHTML(json) }); } This is the function that the addEventListener function is calling. I use a callback function though I could had easily just created another selection element or called another selection element. (maybe even using a callback function?)
PHP Login System?
Gandalf64 replied to chadrt's topic in PHP Coding HelpI have a repository at Github of my website that I think incorporates a nice secure login system -> You might be able to modify it to your liking? The only thing it won't really stop is a brute force attack, but from what I read about brute force attacks is that it takes a long time to crack a user who uses a strong password. That's is why it's important for users to have strong passwords and brute force attacks are almost impossible to defend against (at least I haven't found a real good solution).
PHP output in JSON
Gandalf64 replied to RandomDNA's topic in PHP Coding HelpSomeone awhile back told me that I should do something like the following (Just an example): <?php require_once '../private/initialize.php'; use Library\Display\Display; $status = FALSE; $display = new Display(); if (is_logged_in()) { $status = TRUE; } /* Makes it so we don't have to decode the json coming from Javascript */ header('Content-type: application/json'); /* Start of your php routine(s) */ $submit = filter_input(INPUT_POST, 'submit', FILTER_SANITIZE_FULL_SPECIAL_CHARS); if (isset($submit)) { $user_id = filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data = $display->readBlog("blog.php", $user_id); if ( (isset($_SESSION['user']) && $_SESSION['user']->id === (int)$user_id) || (isset($_SESSION['user']) && $_SESSION['user']->security_level === 'sysop') ) { $temp = true; } else { $temp = false; } array_unshift($data, $temp); output($data); } /* End of your php routine(s) */ /* * If you know you have a control error, for example an end-of-file then simply output it to the errorOutput() function */ function errorOutput($output, $code = 500) { http_response_code($code); echo json_encode($output); } /* * If everything validates OK then send success message to Ajax / JavaScript */ function output($output) { http_response_code(200); echo json_encode($output); } And so far it was work out like a charm for me, it forces you to be structure and it's also pretty easy to debug doing it this way.
Help really needed please
Gandalf64 replied to accesstv's topic in PHP Coding HelpIt's bad practice to send a password over a url. Though I don't know what you're after, but why not have them login at the redirect?
updating database
Gandalf64 replied to Justafriend's topic in PHP Coding HelpAnother way to go about doing this is when you display the record(s). For example on my website I have a CMS for my web page(s) and I do this -> if (isset($_SESSION['user']) && ($_SESSION['user']->security_level === 'sysop' || $_SESSION['user']->id === $this->row->user_id)) { echo '<div class="system">' . "\n"; echo '<a class="edit" href="edit/' . urlencode($this->row->id) . '">Edit</a>' . "\n"; echo '<a class="delete" href="delete_page.php?id=' . urlencode($this->row->id) . '">Delete</a>' . "\n"; echo "</div>\n"; } then on top of my edit page (edit.php) I have the following <?php require_once '../private/initialize.php'; use Library\CMS\CMS; protected_page(); $cms = new CMS(); if (isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT)) { $id = filter_var($_GET['id']); $result = $cms->readId($id); } elseif (isset($_GET['id'])) { header("Location: members_page.php"); exit(); } like I said this is just one way of doing it.
Enhancing my submit button
Gandalf64 replied to cinque8's topic in HTML HelpA good way to practice HTML/CSS and Javascript is using jsfiddle -> A great way to test out small designs and javascript code.
ModRewrite pagination
Gandalf64 replied to lovephp's topic in PHP Coding HelpI personally like this website to generate the ModRewrite rule - I find it easier to visualize what the php portion should be after I generate the rule.
$_SESSION variables
Gandalf64 replied to CB150Special's topic in PHP Coding HelpHave a configuration file at the very top of each page called something like config.php, utilize.inc.php or something that is logical. Mine is require_once '../private/initialize.php'; have session_start() in that configuration file/page.
Failed to write session data (user) ...
Gandalf64 replied to vm101's topic in PHP Coding HelpJust want to add after you accomplish what Jacques1 and gizmola said then regenerate the session id after the user has successfully has login. That way even if a person by chance hijacked that account the login would still be invalid. For example -> // Regenerate session ID to invalidate the old one. // Super important to prevent session hijacking/fixation. session_regenerate_id(); $_SESSION['logged_in'] = true;
Validating a form. Cant validate right?
Gandalf64 replied to xfire123's topic in PHP Coding HelpHere's how I basically check my dates in my calendar that I developed for my website (I know shameless plug ). This hasn't been tested, for I don't use it this way. Which means there might be some modifications that has to be done to the script. <?php $myDate = "1964-08-28"; /* Check date is actually a date */ function checkIsAValidDate($myDate) { return (bool) strtotime($myDate); } $valid = checkIsAValidDate($myDate); // Call the Function: /* Check to see if date is set, is ten characters in length for a format of 0000-00-00 and is truly a valid date. */ if (isset($myDate) && strlen($myDate) === 10 && $valid) { echo "Date is Valid!<br>\n"; }
NULL Byte Poison Information Disclosure Vulnerability
Gandalf64 replied to gtaid1's topic in PHP Coding HelpI could be wrong, for I only did a quick search on the internet but it looks like PHP Manager is obsolete or not being supported? (Someone correct me if I'm wrong) To me from your standpoint I think your problem is more of an update issue than a coding issue (again I could be wrong). All I know is if I had your job I would be looking into updating the applications on the server than trying to correct the issue rather than splicing in a code fix, for I think it doing it that way would solve your problem(s) and satisfy the auditor(s). This is especially truly if you are just an IT administrator with no programming skills?
Help needed installing Google Recaptcha onto my basic php form
Gandalf64 replied to Andrew7v's topic in PHP Coding HelpI'll help you with what I thought was the tricky part of Google ReCaptcha (How I resolved it was not only going to Google, but searching the internet. You'll be surprised how many before you have had the same issue), for I think you can get the rest by going to Google themselves. When the user clicks on the I'm human checkbox this is how I would set up the response. if (isset($submit) && $submit === 'submit') { /* The Following to get response back from Google Recaptha */ $url = ""; $remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL); $response = file_get_contents($url . "?secret=" . PRIVATE_KEY . "&response=" . \htmlspecialchars($_POST['g-recaptcha-response']) . "&remoteip=" . $remoteServer); $recaptcha_data = json_decode($response); /* The actual check of the recaptcha */ if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) { /* Example data gather from the form (actually my contact form) */ $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['phone'] = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['website'] = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['reason'] = filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['comments'] = filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_FULL_SPECIAL_CHARS); /* The following would be your way of sending the email */ $send = new Email($data); // This is my way, by sending it to a class: } else { $errMessage = "You're not a human!"; } } | https://forums.phpfreaks.com/profile/204725-gandalf64/content/ | CC-MAIN-2022-27 | refinedweb | 2,623 | 51.78 |
After months of developing reports with the various Beta's, its nice to finally see the official product launch.
I really have a high-opinion of this product, especially considering that it is Microsoft's first forray into a general-purpose server-based report-generator.
The flexibility of Sql Server Reporting Services, along with its integration into VisualStudio.NET gives us a huge step-up....especially at the cost (FREE if you already have SqlServer 2000 licenses). I hear that this was developed by the same team who created the other excellent Sql Server product Sql Notification Services
Those of us coming from a background in ASP and Visual Basic have been hamstrung a bit with the .NET Framework because most of us don't have much experience with the Win32 API, and therefore didnt understand what functions each class or namespace was wrapping within the OS. Its one of the reasons I believe that many C++ programmers (esp. MFC) have seemed to have a leg-up on the rest of us.
Based upon their latest MSDN article, Microsoft must have finally recognized this. The latest MSDN posting "Microsoft Win32 to Microsoft .NET Framework API Map" is a much appreciated contribution, that I only wish was available a year or two ago.
This SlashDot article "Parens on Patents" really struck a chord with me, and brought back alot of anger I have repressed for some time. (yes, I am seeking professional help now :p )
Basically, it discusses the fad of patenting software or its various features, and the subsequent stifling affect it has upon development. Many of the comments about this article really cover the main points, so I won't rehash, but I will give you an anecdote of how this affected me once:
So, I'm working on a project at my company where we want to help our customers organize their business by automating the sending of E-Cards as a meeting invitation. We started developing this application, but were forced to abandon it because some company has patented the concept of “Sending an Email with a Link back to a web-page that contains an invitation“ and were requiring a royalty of 25-cents per email. Since we wanted to offer this for Free to our customers, and didnt like paying people for their “Concept-Patent“, we asked our legal department to research the claim. They spent months researching ways around it, but basically told us to we were screwed, and that we must either "come up with a different implimentation", or pay the royalty.
Now, its bad enough having management try to dictate code & functionality, but when Legal starts changing programs I get really upset.
So, the moral of this story is: If you are a fan of Open Source, then Patents should be the bane of your existance. Even if you are just an average developer with no care of open-source, you should at least be concerned about how this affects your future employment.
Write to your congressmen & congresswomen about the current abuse of Patents with software!
Many of us have heard the occasional rumors and comments about Microsoft working on a new XML-based programming language.
Here is an interesting article discussing the MS Research project “Xen” which replaced the X# project, and includes full language support of C#.
Is this our future, or just an alternate reality?
Lastnight while working on some new RSS-related projects, I created a simple app to Export your entire list of IE Favorites to OPML (XML).
Enjoy!
Standard Disclaimer: THIS UTILITY IS PROVIDED AS-IS. USE AT YOUR OWN RISK!
I just posted an update to the utility to fix a bug that left the /bin folder empty after a build.
Thanks for the quick feedback!
Have you ever wanted to build a project or solution without opening up Visual Studio.NET?
There are plenty of command-line utilities (including “devenv.exe /build“) to do this, but I couldnt find anything that worked from within Windows Explorer.
Lastnight, I finally whipped-up a new utility much like the “Command Prompt Here“ Power Toy that Microsoft created. It gives you a “VS.NET 2003 Build Here“ Prompt which invokes the command-line call to build. It is associated with the following file-extensions: .csproj, .csdproj, vbproj, vbdproj, jsproj, and .sln.
(added screenshot)
To setup this functionality, download and Save my new “VS.NET 2003 Build Here” installer, Right-Click the file and choose “Install”.
NOTE: The utility expects Visual Studio.NET 2003 to be installed on drive “C” using the “Program Files” folder and using the default directory names.
Disclaimer: THIS UTILITY IS PROVIDED AS-IS. USE AT YOUR OWN RISK!
TheServerSide.NET has an excellent article on Unit Testing in .NET. Having used NUnit for some time, I found alot of statements I agree with, and even a few techniques and philosophies I hadnt explored.
Great job!
in the latest MSDN Flash newsletter, there is an offer from Infragistics for a FREE CD-Key for their UltraWinTree control. | http://weblogs.asp.net/lhunt/archive/2004/01.aspx | crawl-003 | refinedweb | 843 | 62.48 |
pcap_open_live.3pcap man page
pcap_open_live — open a device for capturing
Synopsis
#include <pcap/pcap.h> char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf);
Description
pcap_open_live()() returns a pcap_t * on success and NULL on failure. If NULL is returned, errbuf is filled in with an appropriate error message. errbuf may also be set to warning text when pcap_open_live() succeeds; to detect this case the caller should store a zero-length string in errbuf before calling pcap_open_live() and display the warning to the user if errbuf is no longer a zero-length string. errbuf is assumed to be able to hold at least PCAP_ERRBUF_SIZE chars.
See Also
pcap(3PCAP), pcap_create(3PCAP), pcap_activate(3PCAP) | https://www.mankier.com/3/pcap_open_live.3pcap | CC-MAIN-2017-22 | refinedweb | 119 | 61.46 |
Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.
One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.
private void btnLoadPeopleWhile_Click(object sender, EventArgs e) { List<Person> people = Data.GetPeople(); int counter = 0; while (counter < people.Count) { ListViewItem lviPerson = new ListViewItem(people[counter].FirstName); lviPerson.SubItems.Add(people[counter].LastName); lviPerson.SubItems.Add(people[counter].Position); lviPerson.SubItems.Add(people[counter].Homeworld); counter++; listView2.Items.Add(lviPerson); } } //=================== public static List<Person> GetPeople() { List<Person> people = new List<Person>(); people.Add(new Person{FirstName = "Luke", LastName= "Skywalker", Position = "Jedi Knight", Homeworld = "Hw1"}); people.Add(new Person{FirstName = "Darth", LastName= "Vader", Position = "Jedi Knight", Homeworld = "Hw2"}); people.Add(new Person{FirstName = "Yoda", LastName= string.Empty, Position = "Jedi Master", Homeworld = "Hw3"}); people.Add(new Person{FirstName = "Han", LastName= "Solo", Position = "Captain", Homeworld = "Hw4"}); people.Add(new Person{FirstName = "Boba", LastName= "Fett", Position = "Bounty Hunter", Homeworld = "Hw5"}); people.Add(new Person{FirstName = "Princess", LastName= "Leila", Position = "Heir", Homeworld = "Hw6"}); people.Add(new Person{FirstName = "Lando", LastName= "Calrissian", Position = "General", Homeworld = "Hw7"}); people.Add(new Person{FirstName = "Garth", LastName= "Schulte", Position = ".NET Developer", Homeworld = "Hw8"}); return people; } //======================= public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string Position { get; set; } public string Homeworld { get; set; } }
private void btnLoadPeopleForeach_Click(object sender, EventArgs e) { List<Person> people = Data.GetPeople(); foreach (Person p in people) { ListViewItem lviPerson = new ListViewItem(new string[] { p.FirstName, p.LastName, p.Position, p.Homeworld }, 0); listView2.Items.Add(lviPerson); } }
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
I tried your code without issue. Have you configured the ListView correctly? This is how I configured the ListView to work. I set the following from there defaults View property to Details, I added columns by modifying the Columns property as shown in the screen shot below. Then ran the application.
I had done the same thing but instead of FirstName for example I have First Name for the text property. After I removed the blank space, it works now.
I am preparing another question where a recursive function audits files and folders, say in C:\Documents, and shows them in a treeView structure. This question will be handled possible in a few threads. The starting version will be to find out what control (if not listView) the treeView is build and where the file and folder icons could be found. These two items possibly will be tested for a simple sample like:
C:\Folder1
C:\Folder2
-Budget.xls
-Budget.doc
- Subfolder1
-Production.xls
-Calculation.mdb
I will provide a link for you shortly.
Thanks,
Mike
Thank you,
Mike
You stated, "I had done the same thing but instead of FirstName for example I have First Name for the text property. After I removed the blank space, it works now.", I think you mean Name property because it is used as a variable name for the item where the Text property is used to assign a header. The below screen shot shows columns headers with spaces.
This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.
I have located a good link to do my next project (file/folder threeView). So, the statement of my question has dramatically changed. I hope you are not spending time answering them which are no longer important. | https://www.experts-exchange.com/questions/28586642/Listview-c.html | CC-MAIN-2018-26 | refinedweb | 609 | 50.94 |
hello
i am a beginner to jboss,i write a simple class and publish it as webservice in weblogic7,i can write weblogic client to access the service,now i want to write a client servlet that run on jboss to visit the service.
from the "WebLogic Webservice standard testing home page",i get following code block:
import {package}.Demo1;
...
String wsdlUrl = "";
Demo1 service = new Demo1_Impl( wsdlUrl );
Demo1Port port = service.getDemo1Port();
result = port.testInOut( ... );
i can use it in my client code to access the webservice,it works well in weblogic,but now in jboss,it don't work,how can i do?should i add the weblogic lib to jboss's class path?or if does the jboss have the special method of its onwn to access webservice?
who can help me,the code snippet is appreciated!
thank you!
continue
i use jbuilder8+weblogic7 as the developer environment.
first,i write a simple bean and publish it as weblservice,at this time,the jbuilder generate the client side jar file.i write a weblogic side client to test it,it works well.
second,i write a simple servlet that run in jboss to access the webservice that run in weblogic,i have add the client side jar file that is generated by the jbuilder to the jboss classpath,but the servlet can't run,because the client side jar file need the weblogic lib support.
i wonder if i must add the weblogic lib to jboss classpath?i don't think it is a reasonable solution,i think that the jboss must have the special lib to enable the webservice access,but i don't know how? | https://developer.jboss.org/thread/70891 | CC-MAIN-2018-13 | refinedweb | 278 | 62.07 |
flo
Redis powered node.js autocompleter inspired by soulmate
npm install flo
flo
flo is a redis powered node.js autocompleter inspired by soulmate. You can use this anywhere you want since this is just a module. If you look into the examples folder, I have provided an example on how to get it work with express.
If you want see a real world example of this, you should try out the search box at SeatGeek or Quora.
Documentations
First, connect to the redis instance:
Sets up a new Redis Connection.
var flo = require('flo').connect();
options - Optional Hash of options.
redis- An existing redis connection to use.
host- String Redis host. (Default: Redis' default)
port- Integer Redis port. (Default: Redis' default)
password- String Redis password.
namespace- String namespace prefix for Redis keys. (Default: flo).
mincomplete- Minimum completion of keys required for auto completion. (Default: 1)
database- Integer of the Redis database to select.
Returns a Connection instance.
These are the public functions:
Add a new term
add_term(type, id, term, score, data, callback):
type- the type of data of this term (String)
id- unique identifier(within the specific type)
term- the phrase you wish to provide completions for
score- user specified ranking metric (redis will order things lexicographically for items with the same score)
data- container for metadata that you would like to return when this item is matched (optional)
callback- callback to be run (optional)
Returns nothing.
search_term(types, phrase, limit, callback):
types- types of term that you are looking for (Array of String)
phrase- the phrase or phrases you want to be autocompleted
limit- the count of the number you want to return (optional, default: 5)
callback(err, result)- err is the error and results is the results
This call:
search_term(["chinese", "indian"], "rice", 1, cb);
will return a result in json format like:
{ term: "rice" chinese: [ { id: 3, term: "mongolian fried rice", score: 10, data: { name: "Gonghu Chinese Restaurant", address: "304, University Avenue, Palo Alto" } } ], indian: [ { id: 1, term: "Briyani Chicken Rice", score: 5, data: { name: "Bombay Grill", address: "100 Green St, Urbana" } } ] }
Remove a term
remove_term(type, id, callback):
type- the type of data of this term (String)
id- unique identifier(within the specific type)
callback- callback to be run (optional)
Returns nothing.
Get the IDs for a term
get_ids (type, term, callback):
type- the type of data for this term
term- the term to find the unique identifiers for
callback(err, result)- result is an array of IDs for the term. Empty array if none were found
Get the data for an ID
get_data(type, id, callback):
type- the type of data for this term
id- unique identifier (within the specific type)
callback(err, result)- result is the data
For more information, you can read it here.
Tests
To run tests, first make sure your local redis is running, then:
./node_modules/expresso/bin/expresso test/*.test.js | https://www.npmjs.org/package/flo | CC-MAIN-2014-10 | refinedweb | 483 | 58.52 |
A datat is an intuitive data table for Python, inspired by R's data frames. The module can be installed from PyPI, and development takes place on Bitbucket. Detailed module documentation is also available.
To create a datat from scratch, give it the names of the columns you want. Each row is a dictionary.
from datat import Datat peopledatat = Datat(["Name", "Age", "Smoker?"]) fred = {"Name": "Fred B.", "Age": 31, "Smoker?": False} peopledatat.append(fred) anne = {"Name": "Anne M."} # Any missing fields will be set to None peopledatat.append(anne)
In the interactive interpreter, you can get a preview of the first ten rows (or all of them, if there are ten or fewer) just by referring to the datat:
>>> peopledatat
You can refer to rows and fields by indexing:
anne = peopledatat[1] # Anne's dictionary, now with all fields created fred_age = peopledatat[0]["Age"]
Or loop over the records:
for mortal in peopledatat: print(mortal["Name"]) for name, age, issmoker in peopledatat.tuples: # Get tuples instead of dictionaries print("{0} is {1} years old".format(name, age))
Alternatively, you can work with columns. The datat's
.columns property behaves somewhat like a standard Python
dict (although it isn't):
peopledatat.columns["Name"] # --> ['Fred B.', 'Anne M.'] for colname in peopledatat.columns: print(colname) peopledatat.columns["Smoker?"] = [False, True] # Overwrite an existing column peopledatat.columns["Eye colour"] = None # New, blank column
The
.filter() method of a datat returns a new datat filtered by the conditions you specify. You can specify exact values with keywords, or put expressions in strings:
twentythreeyearolds = peopledatat.filter(Age=23) freds = peopledatat.filter("Name.lower().startswith('fred')")
To refer to rows by name, rather than in a sequence, use the
DatatNamedRows class. This behaves like a Python dictionary, with the extra properties of a datat.
from datat import DatatNamedRows metalsdatat = DatatNamedRows(["Melting point", "Alloy?", "Magnetic?"]) metalsdatat["Iron"] = {"Melting point": 1811, "Alloy?": False, "Magnetic?": True} metalsdatat["Bronze"] = {"Alloy?":True} for rowname in metalsdatat: print(rowname, metalsdatat[rowname]["Alloy?"])
In Python 2.7/3.1 or later, or if you have the ordereddict module installed, rows will stay in the order they were added. Otherwise, the order is liable to be ignored.
CSV (Comma Separated Value) is the standard format for transferring tables of data between programs, including spreadsheets. It's simple to load a datat from CSV, and to save back to it:
peopledatat.save_csv("those_people.csv") from datat import load_csv leaftable = load_csv("leaf_measurements_211009.csv")
To load a table with row names, specify the name of the column containing row names. Each row name should be unique.
leaftable = load_csv("leaf_measurements_211009.csv", namescol="Sample code")
R is a powerful language for doing statistics, and producing plots of your data. Its 'data frames' inspired Datat for Python. So, it's possible to translate a datat into an R data frame using the rpy2 module (also on PyPI). You need to have that module installed to do this:
leaf_rdataframe = leaftable.translate_to_R()
This attempts to work out the type of each column (integer, float, boolean, text), and will default to text (factor) columns if there's a mixture of types within a column. Python's
None will be translated to
NA (which represents missing values in R). | http://packages.python.org/Datat/ | crawl-003 | refinedweb | 535 | 59.9 |
Image file formats¶
The Python Imaging Library supports a wide variety of raster file formats. Nearly 30 different file formats can be identified and read by the library. Write support is less extensive, but most common interchange and presentation formats are supported.
The
open() function identifies files from their
contents, not their names, but the
save() method
looks at the name to determine which format to use, unless the format is given
explicitly.
Fully supported formats¶
BMP¶
PIL reads and writes Windows and OS/2 BMP files containing
1,
L,
P,
or
RGB data. 16-colour images are read as
P images. Run-length encoding
is not supported.
The
open() method sets the following
info properties:
- compression
- Set to
bmp_rleif the file is run-length encoded.
EPS¶
PIL identifies EPS files containing image data, and can read files that contain embedded raster images (ImageData descriptors). If Ghostscript is available, other EPS files can be read as well. The EPS driver can also write EPS images.
If Ghostscript is available, you can call the
load()
method with the following parameter to affect how Ghostscript renders the EPS
- scale
Affects the scale of the resultant rasterized image. If the EPS suggests that the image be rendered at 100px x 100px, setting this parameter to 2 will make the Ghostscript render a 200px x 200px image instead. The relative position of the bounding box is maintained:
im = Image.open(...) im.size #(100,100) im.load(scale=2) im.size #(200,200)
GIF¶
PIL reads GIF87a and GIF89a versions of the GIF file format. The library writes run-length encoded files in GIF87a by default, unless GIF89a features are used or GIF89a is already in use.
Note that GIF files are always read as grayscale (
L)
or palette mode (
P) images.
The
open() method sets the following
info properties:
- background
- Default background color (a palette color index).
-.
Reading local images¶
The GIF loader creates an image memory the same size as the GIF file’s logical
screen size, and pastes the actual pixel data (the local image) into this
image. If you only want the actual pixel rectangle, you can manipulate the
size and
tile
attributes before loading the file:
im = Image.open(...) if im.tile[0][0] == "gif": # only read the first "local image" from this GIF file tag, (x0, y0, x1, y1), offset, extra = im.tile[0] im.size = (x1 - x0, y1 - y0) im.tile = [(tag, (0, 0) + im.size, offset, extra)]
IM¶
IM is a format used by LabEye and other applications based on the IFUNC image processing library. The library reads and writes most uncompressed interchange versions of this format.
IM is the only format that can store all internal PIL formats.
JPEG¶
PIL reads JPEG, JFIF, and Adobe JPEG files containing
L,
RGB, or
CMYK data. It writes standard and progressive JFIF files.
Using the
draft() method, you can speed things up by
converting
RGB images to
L, and resize images to 1/2, 1/4 or 1/8 of
their original size while loading them.
The
open() method may set the following
info properties if available:
- jfif
- JFIF application marker found. If the file is not a JFIF file, this key is not present.
- jfif_version
- A tuple representing the jfif version, (major version, minor version).
- jfif_density
- A tuple representing the pixel density of the image, in units specified by jfif_unit.
- jfif_unit
Units for the jfif_density:
- 0 - No Units
- 1 - Pixels per Inch
- 2 - Pixels per Centimeter
- dpi
- A tuple representing the reported pixel density in pixels per inch, if the file is a jfif file and the units are in inches.
- adobe
- Adobe application marker found. If the file is not an Adobe JPEG file, this key is not present.
- adobe_transform
- Vendor Specific Tag.
- progression
- Indicates that this is a progressive JPEG file.
- icc-profile
- The ICC color profile for the image.
- exif
- Raw EXIF data from the image., the image is stored with the provided ICC profile. If this parameter is not provided, the image will be saved with no profile attached. To preserve the existing profile:
im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))
- exif
- If present, the image will be stored with the provided raw EXIF data.
- subsampling
If present, sets the subsampling for the encoder.
keep: Only valid for JPEG files, will retain the original image setting.
4:4:4,
4:2:2,
4:1:1: Specific sampling values
-1: equivalent to
keep
0: equivalent to
4:4:4
1: equivalent to
4:2:2
2: equivalent to
4:1:1
- qtables
If present, sets the qtables for the encoder. This is listed as an advanced option for wizards in the JPEG documentation. Use with caution.
qtablescan be one of several types of values:
- a string, naming a preset, e.g.
keep,
web_low, or
web_high
- a list, tuple, or dictionary (with integer keys = range(len(keys))) of lists of 64 integers. There must be between 2 and 4 tables.
New in version 2.5.0.
Note
To enable JPEG support, you need to build and install the IJG JPEG library before building the Python Imaging Library. See the distribution README for details.
JPEG 2000¶
New in version 2.4.0. to
convert the image to either
RGB or
RGBA rather than choosing for
itself. It is also possible to set
reduce to the number of resolutions to
discard (each one reduces the size of the resulting image by a factor of 2),
and
layers to specify the number of quality layers to load.
The
save() method supports the following options:
- offset
- The image offset, as a tuple of integers, e.g. (16, 16)
- tile_offset
- The tile offset, again as a 2-tuple of integers.
- tile_size
- The tile size as a 2-tuple. If not specified, or if set to None, the image will be saved without tiling.
- quality_mode
- Either “rates” or “dB” depending on the units you want to use to specify image quality.
- quality_layers
- A sequence of numbers, each of which represents either an approximate size reduction (if quality mode is “rates”) or a signal to noise ratio value in decibels. If not specified, defaults to a single layer of full quality.
- num_resolutions
- The number of different image resolutions to be stored (which corresponds to the number of Discrete Wavelet Transform decompositions plus one).
- codeblock_size
- The code-block size as a 2-tuple. Minimum size is 4 x 4, maximum is 1024 x 1024, with the additional restriction that no code-block may have more than 4096 coefficients (i.e. the product of the two numbers must be no greater than 4096).
- precinct_size
- The precinct size as a 2-tuple. Must be a power of two along both axes, and must be greater than the code-block size.
- irreversible
- If
True, use the lossy Irreversible Color Transformation followed by DWT 9-7. Defaults to
False, which means to use the Reversible Color Transformation with DWT 5-3.
- progression
- Controls the progression order; must be one of
"LRCP",
"RLCP",
"RPCL",
"PCRL",
"CPRL". The letters stand for Component, Position, Resolution and Layer respectively and control the order of encoding, the idea being that e.g. an image encoded using LRCP mode can have its quality layers decoded as they arrive at the decoder, while one encoded using RLCP mode will have increasing resolutions decoded as they arrive, and so on.
- cinema_mode
- Set the encoder to produce output compliant with the digital cinema specifications. The options here are
"no"(the default),
"cinema2k-24"for 24fps 2K,
"cinema2k-48"for 48fps 2K, and
"cinema4k-24"for 24fps 4K. Note that for compliant 2K files, at least one of your image dimensions must match 2048 x 1080, while for compliant 4K files, at least one of the dimensions must match 4096 x 2160.
Note
To enable JPEG 2000 support, you need to build and install the OpenJPEG library, version 2.0.0 or higher, before building the Python Imaging Library.
Windows users can install the OpenJPEG binaries available on the
OpenJPEG website, but must add them to their PATH in order to use
- Transparency color index. This key is omitted if the image is not a transparent palette image.
Open also sets
Image.text to a list of the values of the
tEXt,
zTXt, and
iTXt chunks of the PNG image. Individual
compressed chunks are limited to a decompressed size of
PngImagePlugin.MAX_TEXT_CHUNK, by default 1MB, to prevent
decompression bombs. Additionally, the total size of all of the text
chunks is limited to
PngImagePlugin.MAX_TEXT_MEMORY, defaulting to
64MB.
The
save() method supports the following options:
- optimize
- If present, instructs the PNG writer to make the output file as small as possible. This includes extra processing in order to find optimal encoder settings.
- transparency
- For
P,
L, and
RGBimages, this option controls what color image to mark as transparent.
- dpi
- A tuple of two numbers corresponding to the desired dpi in each direction.
- pnginfo
- A
PIL.PngImagePlugin.PngInfoinstance containing text tags.
- compress_level
- ZLIB compression level, a number between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all. Default is 6. When
optimizeoption is True
compress_levelhas no effect (it is set to 9 regardless of a value passed).
- bits (experimental)
- For
Pimages,.
-¶
The extension of SPIDER files may be any 3 alphanumeric characters. Therefore the output format must be specified explicitly:
im.save('newimage.spi', format='SPIDER')
For more information about the SPIDER image processing package, see the SPIDER homepage at Wadsworth Center.
TIFF.
The
open() method sets the following
info properties:
- compression
Compression mode.
New in version 2.0.0.
- dpi
Image resolution as an
(xdpi, ydpi)tuple, where applicable. You can use the
tagattribute to get more detailed information about the image resolution.
New in version 1.1.5.
- resolution
Image resolution as an
(xres, yres)tuple, where applicable. This is a measurement in whichever unit is specified by the file.
New in version 1.1.5.
The
tag_v2 attribute contains a dictionary of
TIFF metadata. The keys are numerical indexes from ~PIL.TiffTags.TAGS_V2.
Values are strings or numbers for single items, multiple values are returned
in a tuple of values. Rational numbers are returned as a single value.
New in version 3.0.0.
For compatibility with legacy code, the
tag attribute contains a dictionary of
decoded TIFF fields as returned prior to version 3.0.0. Values are
returned as either strings or tuples of numeric values. Rational
numbers are returned as a tuple of
(numerator, denominator).
Deprecated since version 3.0.0.
Saving Tiff Images¶
The
save() method can take the following keyword arguments:
- tiffinfo
A
ImageFileDirectory_v2object or dict object containing tiff tags and values. The TIFF field type is autodetected for Numeric and string values, any other types require using an
ImageFileDirectory_v2object and setting the type in
tagtypewith the appropriate numerical value from
TiffTags.TYPES.
New in version 2.3.0.
For compatibility with legacy code, a ~PIL.TiffImagePlugin.ImageFileDirectory_v1 object may be passed in this field. However, this is deprecated.
..versionadded:: 3.0.0
- compression
- A string containing the desired compression method for the
- file. (valid only with libtiff installed) Valid compression methods are:
[None, "tiff_ccitt", "group3", "group4", "tiff_jpeg", "tiff_adobe_deflate", "tiff_thunderscan", "tiff_deflate", "tiff_sgilog", "tiff_sgilog24", "tiff_raw_16"]
These arguments to set the tiff header fields are an alternative to using the general tags available through tiffinfo.
description
software
date_time
artist
- Strings
- resolution_unit
- A string of “inch”, “centimeter” or “cm”
resolution
x_resolution
y_resolution
- dpi
- Either a Float, Integer, or 2 tuple of (numerator, denominator).
- The ICC Profile to include in the saved file. Only supported if the system webp library was built with webpmux support.
- exif
- The exif data to include in the saved file. Only supported if the system webp library was built with webpmux support.
Read-only formats¶
CUR¶
CUR is used to store cursors on Windows. The CUR decoder reads the largest available cursor. Animated cursors are not supported.
DCX¶.
FLI, FLC¶
PIL reads Autodesk FLI and FLC animations.
The
open() method sets the following
info properties:
- duration
- The delay (in milliseconds) between each frame.
FPX¶
PIL reads Kodak FlashPix files. In the current version, only the highest resolution image is read from the file, and the viewing transform is not taken into account.
Note
To enable full FlashPix support, you need to build and install the IJG JPEG library before building the Python Imaging Library. See the distribution README for details.
GBR¶
The GBR decoder reads GIMP brush files.
The
open() method sets the following
info properties:
- description
- The brush name.
GD.
ICO¶
ICO is used to store icons on Windows. The largest available icon is read.
The
save() method supports the following options:
- sizes
- A list of sizes including in this ico file; these are a 2-tuple,
(width, height); Default to
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)]. Any size is bigger then the original size or 255 will be ignored.
ICNS¶
PIL reads Mac OS X
.icns files. By default, the largest available icon is
read, though you can override this by setting the
size
property before calling
load(). The
open() method sets the following
info property:
- sizes
- A list of supported sizes found in this icon file; these are a 3-tuple,
(width, height, scale), where
scaleis 2 for a retina icon and 1 for a standard icon. You are permitted to use this 3-tuple format for the
sizeproperty if you set it before calling
load(); after loading, the size will be reset to a 2-tuple containing pixel dimensions (so, e.g. if you ask for
(512, 512, 2), the final value of
sizewill be
(1024, 1024)).
MCIDAS¶
PIL identifies and reads 8-bit McIdas area files.
MIC (read only).
MIC (read only)
Pillow identifies and reads Microsoft Image Composer (MIC) files. When opened, the
first sprite in the file is loaded. You can use
seek() and
tell() to read other sprites from the file..WmfImagePlugin.register_handler() to register a WMF handler.
from PIL import Image from PIL") | https://pillow.readthedocs.io/en/3.0.x/handbook/image-file-formats.html | CC-MAIN-2019-22 | refinedweb | 2,339 | 57.47 |
WebDeveloper.com
>
Client-Side Development
>
JavaScript
> disable right click question
PDA
Click to See Complete Forum and Search -->
:
disable right click question
heavenly_blue
07-23-2004, 12:15 AM
I'm disabling right click on a personal page of mine. All the examples on the net give an Alert() when you right click. Is there any way to disable right click without an alert? I want either nothing to happen when you right click, or something else besides an Alert(). Here's the code I'm using:
function disable_right_click(e)
{
var browser = navigator.appName.substring ( 0, 9 );
var event_number = 0;
if (browser=="Microsoft")
event_number = event.button;
else if (browser=="Netscape")
event_number = e.which;
if ( event_number==2 || event_number==3 )
{
alert ("Alert!");
return (false);
}
return (true);
}
function check_mousekey ()
{
var mouse_key = 93;
var keycode = event.keyCode;
if ( keycode == mouse_key )
alert ( "Alert!" );
}
function trap_page_mouse_key_events ()
{
var browser = navigator.appName.substring ( 0, 9 );
document.onmousedown = disable_right_click;
if ( browser == "Microsoft" )
document.onkeydown = check_mousekey;
else if ( browser == "Netscape" )
document.captureEvents( Event.MOUSEDOWN );
}
window.onload = trap_page_mouse_key_events;
I want to replace alert ( "Alert!" ); with something else that will still keep right click disabled. Is there anything else that works? Refreshing the page would be kinda funny.
Jona
07-23-2004, 12:25 AM
Before answering the question, I think this member should be recognized for making a proper post with care and formatting. Because of its readability, I am willing to go to much more length in answering this member's question.
Heavenly_Blue, may I ask why you are interested in disabling right-click? Not only can more experienced web users get past it, in many, many ways (see Fredmv's post stickied to the top of this forum, "Wondering how to hide your source code?"), but it is frustrating for users who do not understand why they cannot right-click on the web page. Assuming your reasons are valid -- or at least arguable -- you can remove the alert code, and when a user right-clicks, nothing should happen, since what decides whether or not a user can right click is the return value (true or false; true means they can right-click, false means they cannot).
heavenly_blue
07-23-2004, 12:34 AM
at first i thought you said i DIDN'T make a proper post and it's readability was off - but then i read what you wrote again and understood. haha i'm soooo tired right now.
this is for a personal site of mine, and only i will be accessing it along with maybe some friends. the purpose is just to learn about the different things you can do with javascript.
i would never use this on a site where i would want users to stay and appreciate the content. thanks for the quick and informative reply.
Jona
07-23-2004, 12:41 AM
You're welcome. Has your problem been solved now?
heavenly_blue
07-23-2004, 12:56 AM
actually removing the alert(); lines makes right clicking possible again. it's the alert box that pops up that kills the right click menu. i wonder if there any other possible methods. i tried:
window.location.reload();
in place of the alerts as well but it doesnt work...
Jona
07-23-2004, 12:58 AM
That is because you are using Internet Explorer. Try replacing this part of the code.
function check_mousekey ()
{
var mouse_key = 93;
var keycode = event.keyCode;
if ( keycode == mouse_key )
return false;
}
webdeveloper.com | http://www.webdeveloper.com/forum/archive/index.php/t-40159.html | crawl-003 | refinedweb | 570 | 67.15 |
How to create namespaces in DokuWiki
What is a Namespace? A Namespace is a folder location where your page resides, much like how you can organize files on your computer using folders and subfolders, wiki pages are organized into Namespaces. For information on creating pages, please click here. Namespaces are crucial for organizing your pages within your wiki. In other words, DokuWiki can store pages in sub locations or folders to organize your pages into sub categories. This is seen in the sitemap of the site (Image is below to the right).
For example, if you want to separate the pages to topics, you can place the pages under those Namespace names like the following.
- Root (This is the root folder where all pages go)
- HTML (Namespace is HTML)
- HTML Basics (Subpage in HTML Namespace)
- HTML 5 (Subpage in HTML Namespace)
- HTML Reference (Subpage in HTML Namespace)
- wiki (Default Namespace name)
- dokuwiki (Subpage in wiki Namespace)
- syntax (Subpage in wiki Namespace)
- Page in root (This page reside in the Root Namespace)
- Another page in root (This page reside in the Root Namespace)
- start (This page reside in the Root Namespace)
You can see the Namespace and page structure where Namespaces are blue and pages are green. The root directory name is not listed in the website sitemap itself. Click the Sitemap link at the top right of the page to see the sitemap similar to the image to the right.
The Sitemap shows the Namespaces and their pages within them. The image to the right shows a basic DokuWiki sitemap with the name spaces in blue and the pages in green.
Namespaces can also be seen when creating links in the DokuWiki editor.
The Link wizard will show like the snapshot to the right. The Namespaces show as gold folder icons and the pages as blue note paper icons. For information on the Link wizard, see the article Inserting internal links in DokuWiki.
How to create a Namespace in DokuWiki
The next 2 sections will explain how to create Namespaces. Namespaces can be placed in the root directory or within other namespaces (like folders and subfolders on a computer). The following sections will explain these in detail.
Creating a Namespace in the Root directory
- Log into DokuWiki.
- Type the Namespace first and then the page name separating them with a : in the search box. The text you enter in the search should look like the following.
nameofspace:Your new page name
Note!!: Supplement nameofspace: with your new Namespace name. Namespaces have the : after them to designate it as a Namespace.
Type the name of the page you are creating after the : of the Namespace name. (In this case we entered "html:html 5 reference".) Namespaces need to have a page created with it. You can't just create a namespace. It should look like the snapshot to the right.
Click the search magnifying glass icon.
You will get a page not found. Click the pencil on the right that says "Create this page".
Insert text and save the changes.
Click the Sitemap link at the top right. The new Namespace name (In this case "html") will show in the menu like the image to the right with the page in it.
Create a Namespace within another Namespace
- Log into DokuWiki.
Type in the search box the first Namespace name and then the second subNamespace separating them with a : colon. The page name goes after the :. It should look like the following text.
nameofspace:subNamespace:Your new page name
Note!!: Supplement nameofspace: and subNamespace: and the Your new page name with your names. (Namespaces have the : after them to designate it as a Namespace.)
In this case we entered "html:html5:html 5 Videos". It should look like the image to the right.
Click the search magnifying glass icon.
Click the pencil to the right that says "Create this page" to create the page.
Add content and Save the page.
Click the sitemap link at the top right. You will see the Namespace (In this case "html:html5") within another Namespace as a subsection like the right snapshot.
Now that you created Namespaces, you may want to rename or delete a Namespace. The next article will explain how to delete and rename Namespaces. | https://www.inmotionhosting.com/support/edu/dokuwiki/writing-content-dokuwiki/create-namespace-doku | CC-MAIN-2016-30 | refinedweb | 712 | 74.69 |
I have a large sized JPanel within a JScrollPane, and in this JPanel need to render LOTS of stuff. To speed up rendering I am using the Clip Rect (specified by the graphics object method getClipBounds()) to render only the things needed. I noticed the width of the returned rectangle seems somewhat unpredictable during a scrolling drag event (eg when a user drags the scroll bar). Here's a short snippet demonstrating the behavior - run, and start a repaint by resizing the window or dragging the scroll bar and notice the difference in printed out values. A similar behavior occurs when I animate the scrolling with a Timer
import javax.swing.*; import java.awt.*; public class ScrollDemo extends JFrame{ public ScrollDemo(){ super(); ScrollPanel scPanel = new ScrollPanel(); scPanel.setPreferredSize(new Dimension(5000,200)); JScrollPane scroller = new JScrollPane(scPanel); scroller.setPreferredSize(new Dimension(500,200)); getContentPane().add(scroller); pack(); setVisible(true); } private class ScrollPanel extends JPanel{ /** * Paints the component and prints out the values of the * Clip Rect width every time it paints. */ @Override public void paintComponent(Graphics g){ super.paintComponent(g); Rectangle rect = g.getClipBounds(); System.out.println(rect.width); } } public static void main(String[] args){ new ScrollDemo(); } }
It would be ideal if the width of the clip bounds actually gave the values I expected, but its not and I'm curious as to why and if there is a workaround to the issue. | http://www.javaprogrammingforums.com/awt-java-swing/4482-clipping-while-scrolling.html | CC-MAIN-2015-35 | refinedweb | 233 | 53.92 |
How-To: Trigger your application with input bindings
Using bindings, your code can be triggered with incoming events from different resources which can be anything: a queue, messaging pipeline, cloud-service, filesystem etc.
This is ideal for event-driven processing, data pipelines or just generally reacting to events and doing further processing.
Dapr bindings allow you to:
- Receive events without including specific SDKs or libraries
- Replace bindings without changing your code
- Focus on business logic and not the event resource implementation
For more info on bindings, read this overview.
For a quickstart sample showing bindings, visit this link.
1. Create a binding
An input binding represents an event resource that Dapr uses to read events from and push to your application.
For the purpose of this HowTo, we’ll use a Kafka binding. You can find a list of the different binding specs here.
Create the following YAML file, named binding.yaml, and save this to a
components sub-folder in your application directory.
(Use the
--components-path flag with
dapr run to point to your custom components dir)
Note: When running in Kubernetes, apply this file to your cluster using
kubectl apply -f binding.yaml
apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: myevent namespace: default spec: type: bindings.kafka version: v1 metadata: - name: topics value: topic1 - name: brokers value: localhost:9092 - name: consumerGroup value: group1
Here, you create a new binding component with the name of
myevent.
Inside the
metadata section, configure the Kafka related properties such as the topics to listen on, the brokers and more.
2. Listen for incoming events
Now configure your application to receive incoming events. If using HTTP, you need to listen on a
POST endpoint with the name of the binding as specified in
metadata.name in the file. In this example, this is
myevent.
The following example shows how you would listen for the event in Node.js, but this is applicable to any programming language
const express = require('express') const bodyParser = require('body-parser') const app = express() app.use(bodyParser.json()) const port = 3000 app.post('/myevent', (req, res) => { console.log(req.body) res.status(200).send() }) app.listen(port, () => console.log(`Kafka consumer app listening on port ${port}!`))
ACK-ing an event
In order to tell Dapr that you successfully processed an event in your application, return a
200 OK response from your HTTP handler.
res.status(200).send()
Rejecting an event
In order to tell Dapr that the event wasn’t processed correctly in your application and schedule it for redelivery, return any response different from
200 OK. For example, a
500 Error.
res.status(500).send()
Specifying a custom route
By default, incoming events will be sent to an HTTP endpoint that corresponds to the name of the input binding. You can override this by setting the following metadata property:
name: mybinding spec: type: binding.rabbitmq metadata: - name: route value: /onevent
Event delivery Guarantees
Event delivery guarantees are controlled by the binding implementation. Depending on the binding implementation, the event delivery can be exactly once or at least once.
References
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve. | https://docs.dapr.io/developing-applications/building-blocks/bindings/howto-triggers/ | CC-MAIN-2021-43 | refinedweb | 540 | 56.96 |
When creating a React class, which is preferable?
export default class Foo extends React.Component {
constructor (props) {
super(props)
this.doSomething = this.doSomething.bind(this)
}
doSomething () { ... }
}
or
export default class Foo extends React.Component {
doSomething = () => { ... }
}
A coworker of mine thinks that the latter causes memory problems because babel transpiles the code to capture this inside the closure, and that reference will cause the instance to not be cleaned by GC.
this
any thoughts about this?
Binding in the render function causes new functions to be created on every render, this means the diffing algoritm thinks there are changes. When you bind in the constructor this does not happen.
Here you can see the compiled difference for binding with arrow and binding in the constructor:
The public class field syntax (so doSomething = () => {...}) is not yet part of ECMAScript but it is doing well and I am pretty confident that it will get there.
doSomething = () => {...}
So using this syntax forces you to transpile, but it brings advantages:
For me, this is a clear win. In most cases, you don't even need a constructor(props), saving you from that boilerplate super call.
constructor(props)
super
If the Babel implementation would cause memory leaks, you can be sure those would have been found and fixed quickly. You are more likely to create leaks yourself by having to write more code. | http://jakzaprogramowac.pl/pytanie/59193,when-using-react-is-it-preferable-to-use-fat-arrow-functions-or-bind-functions-in-constructor | CC-MAIN-2017-43 | refinedweb | 227 | 64.2 |
Programming FAQ¶
Contents
- Programming FAQ
- General Questions
- Is there a source code level debugger with breakpoints, single-stepping, etc.?
- Is there a tool to help find bugs or perform static analysis?
- How can I create a stand-alone binary from a Python script?
- Are there coding standards or a style guide for Python programs?
- My program is too slow. How do I speed it up?
- Core Language
-?
- Numbers and strings
-odeError: ASCII [decoding,encoding] error: ordinal not in range(128)’ mean?
- Sequences (Tuples/Lists)
- How do I convert between tuples and lists?
- What’s a negative index?
-?
- Dictionaries
- Objects
- What is a class?
- What is a method?
- What is self?
- How do I check if an object is an instance of a given class or of a subclass of it?
- What is delegation?
-?
- Modules
General Questions¶
Is there a source code level debugger with breakpoints, single-stepping, etc.?¶
Yes..
My program is too slow. How do I speed it up?¶ assembly language.-in functions. You may still use the old %
operations
string % tuple and
string % dictionary.
Be sure to use the
list.sort() built-in method:
Only use explicit relative package imports. If you’re writing code that’s in
the
package.sub.m1 module and want to import
package.sub.m2, do not just
write
import m2, even though it’s legal. Write
from package.sub import
m2 or
from . import m2 instead.)
In the unlikely case that you care about Python versions older than 2.0, use
apply():
def f(x, *args, **kwargs): ... kwargs['width'] = '14.3c' ... apply instance at 0x16D07CC> >>> print a <__main__.A instance, this feature was added in Python 2.5. The syntax would be as follows:
[on_true] if [expression] else [on_false] x, y = 50, 25 small = x if x < y else y
For versions previous to 2.5 the answer would be ‘No’.
Is it possible to write obfuscated one-liners in Python?¶
Yes. Usually this is done by nesting
lambda within
lambda..
Note
On Python 2,
a / b returns the same as
a // b if
__future__.division is not in effect. This is also known as “classic”
division. ‘0’ as octal (base 8). Format String Syntax section, e.g.
"{:04d}".format(144) yields
'0144' and
"{:.3f}".format(1/3) yields
'0.333'. You may also use
the % operator on strings. See the library reference
manual for details.
How do I modify a string in place?¶
You can’t, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:
>>> import io >>>>> a = list(s) >>> print a ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] >>> a[7:] = list("there!") >>> ''.join(a) 'Hello, there!' >>> import array >>> a = array.array('c', s) >>> print a array('c', 'Hello, world') >>> a[0] = 'y'; print a array('c', 'yello, world') >>> a.tostring()
Starting with Python 2.2,.]..
What does ‘UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)’ mean?¶
This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem.
If your programs must handle data in arbitrary character set encodings, the
environment the application runs in will generally identify the encoding of the
data it is handing you. You need to convert the input to Unicode data using
that encoding..
If you only want strings converted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails:
try: x = unicode(value, "ascii") except UnicodeError: value = unicode(value, "utf-8") else: # value was valid ASCII data pass
It’s possible to set a default encoding in a file called
sitecustomize.py
that’s part of the Python library. However, this isn’t recommended because
changing the Python-wide default encoding may cause third-party extension
modules to fail.
Note that on Windows, there is an encoding known as “mbcs”, which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. dictionary keys (i.e. they are all hashable) this is often faster
d = {} for x in mylist: d[x] = 1 mylist = list(d.keys())
In Python 2.5 and later, the following is possible instead:]).
Dictionaries¶
How can I get a dictionary to display its keys in a consistent order?¶,.
sort() function:
Isorted = L[:] Isorted.sort(key=lambda s: int(s[10:15]))
How can I sort one list by values from another list?¶, long,
If you’re using new-style classes, use the built-in
super() function: since Python 2.2:
class C: def static(arg1, arg2, arg3): # No 'self' parameter! ... static = staticmethod(static)
With Python 2.4’s decorators, this can also be written as
foo.py that imports another module
xyz.py, when you run
foo,
xyz.pyc will be created since
xyz is imported, but no
foo.pyc file
will be created since
foo.py isn’t being imported.
If you need to create
foo.pyc –, do this:> | https://docs.python.org/2/faq/programming.html | CC-MAIN-2017-43 | refinedweb | 854 | 69.89 |
I'm so confused with
global
class ProcessObject:
RR = 0
def b(self):
self.RR=5
print("valor: ", self.RR)
def c(self):
print("final: ", self.RR)
def d(self):
global RR
RR = 3
print("valor: ", RR)
print(RR)
proce = ProcessObject()
proce.b()
proce.c()
proce.d()
proce.c()
0
value: 5
final: 5
value: 3
final: 5
c
d
RR
This has nothing to do with immutability... But anyway:
class ProcessObject: # this "RR" lives in the `class` statement namespace, # it's accessible as 'RR' in this namespace. After the # `class` statement is executed, it becomes an attribute # of the `ProcessObject` class, accessible as `ProcessObject.RR`, # and thru instances as `ProcessObject().RR`. # RR = 0 def b(self): # this creates an "RR" instance attribute # on the current instance (`self`), which shadows # the "RR" class attribute self.RR=5 print("valor: ", self.RR) def c(self): print("final: ", self.RR) def d(self): # The two following lines creates a module-global # name "RR", which is distinct from the two previous # ones. global RR RR = 3 print("valor: ", RR) # this prints the value of the `RR` living in the class # statement scope - NOT the value of the yet non-existing # global RR print(RR) proce = ProcessObject() proce.b() # this creates the `proce.RR` instance attribute proce.c() proce.d() proce.c()
But I not understand why with "c" the value is 5 if the RR is an object immutable.
It prints '5' because you assigned that value to
proce.RR when calling
proce.b(). You're confusing names and values...
RR is not an object, it's a name which is bound to an object. The fact that it's at one point bound to an immutable object doesn't mean you cannot rebind it to another object (mutable or not, that's irrelevant here).
And why "d" using global no mute the value of RR
And here you are confusing binding (assignment) and mutating. binding (assignment) means "make that name points to this object", mutating means "change the state of this object". An example of mutation is adding or removing an element to/from a list, or reversing a list in place.
FWIW, the call to
proce.d DO rebind (and actually bind on the first call) the module-global "RR".
You may want to run this '"extended" version of your script to find out what really happens:
print("before : globals = {}".format(globals())) class ProcessObject: RR = 0 print "RR defined in the class namespace - not in globals: {}".format(globals()) def __init__(self): print("in init") print(" self.__dict__ : {}".format(self.__dict__)) print(" ProcessObject.__dict__ : {}".format(ProcessObject.__dict__)) def b(self): print("before calling b - self.__dict__ : {}".format(self.__dict__)) self.RR=5 print("valor: ", self.RR) print("after calling b - self.__dict__ : {}".format(self.__dict__)) def c(self): print("before calling c - self.__dict__ : {}".format(self.__dict__)) print("final: ", self.RR) def d(self): print("before calling d : globals = {}".format(globals())) global RR RR = 3 print("valor: ", RR) print("after calling d : globals = {}".format(globals())) print(RR) print("after class statement: globals : {}".format(globals())) proce = ProcessObject() proce.c() proce.b() proce.c() proce.d() proce.c() | https://codedump.io/share/DQqPUzPZWlos/1/confusion-about-global-and-immutable | CC-MAIN-2017-43 | refinedweb | 524 | 51.75 |
Hello; }
A pyramid such as that grows at a rate of (2x - 1), or one less than 2 times x.
***X 2*1 = 2 -1 = 1 **XXX 2*2 = 4 - 1 = 3 *XXXXX 2*3 = 6 - 1 = 5 XXXXXXX 2*4 = 8 - 1 = 7
A possible way to get what you're looking for is to output a blank space " " in front of each row.
And I'm guessing from looking the asterisks that you're going to want to start at one less than the height (so in the previous example, 3) then decrement it until you're left with 0 and output the last line without any spaces.
And since it is an assignment, I would recommend changing your variable names to something meaningful, (ie height, blankSpaces, etc.)
>However, this one of my attempt, please give some suggestion.
The usual pattern is a loop for the rows and two loops inside of it, one for the leading spaces and one for the triangle body:
for i = 0 to N for j = 0 to nspace print ' ' for j = 0 to nbody print 'X'
From there it's simply a matter of getting the expressions right for calculating nspace and nbody.
Or you can just turn in something that will shut your teacher up, like this:
#include <iostream> int main() { for ( int i = 0; i < 32; i++ ) { for ( int j = 0; j <= i; j++ ) std::cout.put ( ~i & j ? ' ' : '1' ); std::cout.put ( '\n' ); } }
;)
Or you can just turn in something that will shut your teacher up, like this:
#include <iostream> int main() { for ( int i = 0; i < 32; i++ ) { for ( int j = 0; j <= i; j++ ) std::cout.put ( ~i & j ? ' ' : '1' ); std::cout.put ( '\n' ); } }
;)
That's cool!
:P
hmm if about how to make the blank space i already figured it out...The one that troubled me is how to write the "x" after the blank spaces. How can I do it ?
@narue : i can't try that code of yours >.< I am using MinGw Developer Studio. Can you make the code so it can be executed in MinGw ?
>The one that troubled me is how to write the "x" after the blank spaces. How can I do it ?
That's actually the easier part. You just need a second loop that prints x's and increments by two with each row.
>Can you make the code so it can be executed in MinGw ?
Not really. The code is already conforming to the C++ standard, so unless you're doing something wrong (the most likely case) trying to execute it, tweaks would be necessary to handle implementation quirks. For example, on Dev-C++ I would have to change it to this to keep the execution window open and force cout to flush just for good measure:
#include <iostream> int main() { for ( int i = 0; i < 32; i++ ) { for ( int j = 0; j <= i; j++ ) std::cout.put ( ~i & j ? ' ' : '1' ); std::cout.put ( '\n' ); } std::cin.get(); }
get input height nunmberOfBlanks = height - 1 numberOfX = 1 level = 1 for 1 to height for 1 to numberOfBlanks print " " endfor for 1 to numberOfX print "X" endfor numberOfBlanks = numberOfBlanks - 1 level++ numberOfX = 2 * level endfor
I think that would do it
Hmm...thank you for your suggestion, i already found some way^^. But i have difficulty combine this two code
This for make the blank spaces :
for ( int b=x;b>=0;b--){ for (int z=1;z<=b;z++){ cout<<"a"; }<<endl cout } and this is for the pyramid for (int c=1;c<=height*2-1;c=c+2){ for(int d=1;d<=c;d++){ cout<<"x"; } cout<<endl; }
somehow they just don't mix together. Can you help me fix it >.< ?
for ( int b=x;b>=0;b--) { for (int z=1;z<=b;z++) { cout<<"a"; } <<endl cout } // and this is for the pyramid for (int c=1;c<=height*2-1;c=c+2) { for(int d=1;d<=c;d++) { cout<<"x"; } cout<<endl; }
Is the "a" what is meant to be your blank spaces? If so I think you're looking at it the wrong way.
The first line will have (height - 1) blank spaces, because it will be half of the bottom row (excluding the middle X), then decreases by 1 for each new row.
THIS IS UNTESTED BUT SHOULD WORK
for (int level=1;level<=height; level--) { for(int blanks= height-1; blanks > 0; blanks--) { cout << " "; } for(int d=0;d < (level*2 -1); d++) { cout<<"x"; } cout << endl; }
Example #1:
number of lines in pyramid = 3
line number 1 has 2 prefix spaces followed by 1 *
line number 2 has 1 prefix spaces followed by 3 *
line number 3 has 0 prefix spaces followed by 5 *
Example #2:
number of lines in pyramid = 4
line number 1 has 3 prefix spaces followed by 1 *
line number 2 has 2 prefix spaces followed by 3 *
line number 3 has 1 prefix spaces followed by 5 *
line number 4 has 0 prefix spaces followed by 7 *
Patterns established in examples:
1) line number increases from 1 to number of lines in pyramid
2) the number of spaces to print on each line is the number of lines in pyramid minus the line number
3) the number of * to print on each line is one less than the line number times 2
Pseudocode:
outer loop controls line number inner loop #1 prints spaces inner loop #2 prints *
Did not Nature give a wonderful explanation about making the pyramid. Did you try what Nature said?
Modify her code just a little to suit your problem.
Its as simple as
#include <iostream> int main() { using namespace std; int n; cin >> n ; for ( int i = 1; i <= n; i++ ) { for ( int j = 2*n-1; j ; j-- ) cout.put ( j>(2*i-1) ? ' ' : 'X' ); cout.put ( '\n' ); } }
or perhaps this would do
#include <iostream> int main() { int n; std::cin >> n ; for ( int j=10,i = 1; i <= n; ) std::cout.put ( j==2*n+9?j=10+(i++*0):j++>=(2*(n-i)+10) ? 'X' : ' ' ); }
#include <iostream> #include <cstdlib> #include <iomanip> using namespace std; int main (int argc, char * const argv[]) { int row = 0; int numbers[1001]; for ( int a = 1; a <= 1000; a++ ) { numbers[ a - 1 ] = a; } cout << "Enter number of pyramid\'s rows:"; cin >> row; for ( int i = 0; i < row; i++ ) { for ( int j = 0; j < i + 1; j++ ) { cout << numbers[ j ]; } cout << '\n'; } return 0; }
@pouyan_objc
Do not resurrect old/solved thread. If you want to ask question, start your own thread.
Read member rules :
Thread Closed. | http://www.daniweb.com/software-development/cpp/threads/154590/make-pyramid | CC-MAIN-2014-10 | refinedweb | 1,107 | 72.39 |
.NET as a technology has brought about great changes. Besides moving to a managed context, .NET provides developers with the tools to rapidly develop applications. However, there has been one attribute of .NET processes that has been callously overlooked by many: Memory Consumption.
Since .NET processes pull in lots of code from the framework class libraries, each process has a large footprint. When many processes are run, there will be a lot of libraries that are duplicatly loaded in separate address spaces, all taking up valuable system resources. The answer to memory conservation comes in the form of AppDomains in .NET. With AppDomains, multiple applications can run in the same process, thereby sharing the .NET runtime libraries.
Sharing the .NET runtime using AppDomains does come at a slight performance hit, though this will not be noticeable if the application is not using static methods and fields in abundance, yet the improvement in memory consumption is phenomenal. Fully homogenous .NET solutions are not common in industry as of yet, and as a result, the issue of memory has not been brought to the forefront. Yet memory consumption is always a consideration of good software design and this article shows ways to use system resources more efficiently with AppDomains in .NET.
To benchmark the memory consumption, I created two very simplistic applications. A StayinAlive.exe and a Win32StayinAlive.exe, using an executable and a .NET assembly respectively. Both programs run with a message to the console every 1 second indicating that they are alive and run until the program is shutdown by the user. To illustrate the magnitude of the problem, I ran 5 copies of the .NET version to illustrate the added memory consumption and to prove that there is no efficiency of library usage in running multiple copies of the same program. Consider the diagram below and notice that the Win32 process takes about 700KB of memory whereas its comparable counterpart in .NET takes around 4.5MB of memory. This may not be a problem for simple applications, but when running multiple .NET applications on a system, it can add up very quickly. Our 5 console applications add up to about 22.5MB of memory!
The code for the Win32 version of StayinAlive is as follows:
int _tmain(int argc, _TCHAR* argv[])
{
DWORD tid = ::GetCurrentThreadId();
while( true ){
printf( "Ah Ah Ah Ah Stayin Alive on Thread %d\n", tid );
::Sleep(1000);
}
return 0;
}
The code for the .NET managed version of StayinALive is as follows:
[STAThread]
static void Main(string[] args)
{
string myDomain = AppDomain.CurrentDomain.FriendlyName;
int myThrdId = AppDomain.GetCurrentThreadId();
int sleepTime= 1000;
if( args.Length > 0 )
sleepTime = Int32.Parse( args[args.Length-1] );
while( true ){
Console.WriteLine( "Ah Ah Ah Ah Stayin Alive on Thread {1} : {0}",
myDomain, myThrdId );
Thread.Sleep(sleepTime);
}
}
Application domains remained a mystery to me for quite a while, but after some general reading in this topic, I came to the following understanding: In .NET, the basic unit of execution is NOT the process, rather it is that of the Application Domain. The only true process is what is called a Runtime Host. The CLR is a DLL which means that, in order to run, it must be hosted in some process: The runtime host. There are basically three runtimes with the .NET framework: Internet Explorer, ASP.NET, and Windows shell. Also note that if you are running .NET 1.0 and 1.1, there will be separate runtime hosts for each of these (i.e. 6 runtime hosts). There are numerous topics regarding application domains such as threads and inter-application communication using remoting that are not in the scope of this article, but I urge you to look up Application Domains in the MSDN documentation.
The point I’m trying to make here is that everything in .NET runs within an application domain. Even though you never create an AppDomain explicitly, the runtime host creates a default domain for you before running your application runs. What makes them even more powerful, is that a single process can have multiple domains running within it. Unlike a thread, each application domain runs isolated from the others with its own address space and memory. So where’s the benefit? What do we get by running multiple applications in the same process versus running multiple processes with single (defaulted) application domains.
Quoting MSDN:
“If an assembly is used by multiple domains in a process, the assembly's code (but not its data) can be shared by all domains referencing the assembly. This reduces the amount of memory used at run time.”
“If an assembly is used by multiple domains in a process, the assembly's code (but not its data) can be shared by all domains referencing the assembly. This reduces the amount of memory used at run time.”
But….....
“The performance of a domain-neutral assembly is slower if that assembly contains static data or static methods that are accessed frequently.”
“The performance of a domain-neutral assembly is slower if that assembly contains static data or static methods that are accessed frequently.”
So, would I run multiple data processing applications that used static methods in the same process, just to save memory? Of course not, but I certainly would consider it if I had some high latency applications that, just like my dog Debug, slept around for a good part of the day.
To illustrate the power of AppDomains and the actual improvement in memory consumption, I created an ApplicationHost process. This process will load multiple .NET executables into multiple application domains, in the same process, so we can see just how much memory we save.
First, I created a class HostedApp that represents an application being hosted in my process, as follows:
HostedApp
public class HostedApp
{
internal string domainName;
internal string processName;
internal int sleepTime=1000;
internal AppDomain ad;
internal Thread appThrd;
public HostedApp( string domain, string process ){
this.domainName = domain;
this.processName = process;
ad = AppDomain.CreateDomain( domain );
}
public void Run(){
appThrd = new Thread( new ThreadStart( this.RunApp ) );
appThrd.Start();
}
private void RunApp(){
string [] args = new string[]{ sleepTime.ToString() };
ad.ExecuteAssembly( this.processName, null, args );
}
}
Each HostedApp instance will create a new AppDomain to run the hosted .NET process. The RunApp() method is privately scoped and is matched to the delegate for a ThreadStart procedure. The Run() method is called on the instance to start the hosted process in its own Thread and AppDomain.
RunApp()
ThreadStart
Run()
The executing method I implemented to test this class is as follows:
[STAThread]
static void Main(string[] args)
{
const int NUMAPPS = 5;
HostedApp[] apps = new HostedApp[NUMAPPS];
string appName = "StayinAlive.exe";
for( int i=0; i<NUMAPPS; i ++ ){
apps[i] = new HostedApp( ("Application"+(i+1)), appName );
apps[i].Run();
}
}
That’s right folks … 7.6MB for 5 processes + the hosting application. This is an approximate savings of 15MB of memory to get the same job done.
When you run the above code, you will notice one thing. Since all hosted applications are run in the same process (Windows shell), they will share the same console. Hence, if you have console applications that require user interaction from the console, this can get messy. There is hope though. When running Windows applications, such as forms, the forms are all hosted in separate threads and will run independently. In the source code provided, I have also included a simple StayinAliveForm.exe program that launches a form (instead of a console) that displays the same message in a Label control with the current time. For extra credit, you can change the hosted application from StayinAlive.exe to StayinAliveForm.exe and watch the program run with 5 independent and fully functional forms. Of course, your savings in memory will be comparatively more due to the larger footprint for Windows applications.
Label
Also, note that the .NET runtime is not dumb in the least bit. A lot of this memory will actually get paged out eventually, but the fact is that it still is committed memory and can be paged back to physical memory any time.
Application domains are very powerful, yet they can get very complex very quickly if you dive into advanced features such as moving data between domains and communicating with domains hosted on remote machines. If you have huge assemblies of your own, for example, rich user interface component libraries, that are shared by multiple processes in your product, you may want to consider using App Domains to improve memory consumption. Again, I refer you (and myself) to the MSDN documentation on this to further your (and my) knowledge about application domains. Good luck and thanks for the. | http://www.codeproject.com/Articles/6578/Use-AppDomains-To-Reduce-Memory-Consumption-in-NET?fid=36815&df=90&mpp=10&sort=Position&spc=Relaxed&tid=1876147 | CC-MAIN-2016-30 | refinedweb | 1,439 | 56.66 |
When I wanted to implement Add to home screen feature in an application I was working in flutter, I didn't found much good solutions out there and I struggled a bit coming up with a solution.
In this article, I've described my personal solution to this. Please let me know if we can do this in a great way than this. Enjoy learning!
To start learning about A2HS (Add to Home Screen), we first need to learn about PWAs. Know this already? you can skip to the main content.
PWA (Progressive Web App):
PWAs or Progressive Web Apps are the web apps that use the cutting edge web browser APIs to bring native app-like user experience.
But how do we differentiate normal and PWA web app. It's simple we just need to check if it contains the following features:
- Secure Network (HTTPS)
- Service Workers
- Manifest File
Source: MDN Web Docs
A2HS:
What's A2HS?
Add to Home screen (or A2HS for short) is a feature available in modern browsers that allows a user to "install" a web app, ie. add a shortcut to their Home screen representing their favorite web app (or site) so they can subsequently access it with a single tap.
Source & More Info: MDN Web Docs
Relation of A2HS with PWA?
As we learnt, A2HS's job is to provide you ability to install the web app on your device. Therefore, it needs the web app to have offline functionality.
Therefore, PWAs quite fit for this role.
Flutter Implementation
Well, now that we've learned, what PWA and A2HS means, let's now get to the main point, i.e. creating A2HS functionality to flutter web app or creating flutter PWA.
Let's first make the Flutter Web App, Flutter PWA.
Create a new flutter app (web enabled) and go through the steps below.
For this, we want to (click on link to navigate to the section):
- Have a manifest file
- Icons available
- Service workers
- A2HS Prompt Configuration
- Show A2HS Prompt From Flutter Web App
- HTTPS context
Manifest
Particular:
The web manifest is written in standard JSON format and should be placed somewhere inside your app directory. It contains multiple fields that define certain information about the web app and how it should behave. To know more about fields, checkout the source docs.
Implementation:
Flutter web comes with a manifest.json file already but some of the browsers don't support it. Therefore, we'll create a new file in web root directory named, "manifest.webmanifest" .
Add this code in it:
{ "name": "FlutterA2HS", "short_name": "FA2HS", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "Flutter A2HS Demo Application", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/ } ] }
Add this line in the head tag of your index.html file:
<link rel="manifest" href="manifest.webmanifest">
Run the app and navigate to Dev Tools > Application > Manifest.
You should see this:
If you see some warning, please consider resolving them.
Note: All the fields here are required for PWA to work. Please consider replacing values in it. Though you can reduce the number of images in icons list.
Source & More Info: MDN Web Docs
Icons
We can already see icons folder there, just add appropriate icons there, and make sure to add them in the manifest file.
Service Workers
Particular:.
Implementation:
Create a file named "sw.js" in root folder where manifest belongs.
Add following code there:
const cacheName = "flutter-app-cache-v1"; const assetsToCache = [ "/", "/index.html", "/icons/Icon-192.png", "/icons/Icon-512.png", ]; self.addEventListener("install", (event) => { self.skipWaiting(); // skip waiting event.waitUntil( caches.open(cacheName).then((cache) => { return cache.addAll(assetsToCache); }) ); }); self.addEventListener("fetch", function (event) { event.respondWith( caches.match(event.request).then(function (response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); }) ); });
This will cache network urls and assets.
The service worker emits an
install event at the end of registration. In the above code, a message is logged inside the
install event listener, but in a real-world app this would be a good place for caching static assets.
Now,
In in index.html before the default service worker registration of flutter (above line:
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;).
Add the following code:
var customServiceWorkerUrl = './sw.js'; navigator.serviceWorker.register(customServiceWorkerUrl, { scope: '.' }).then(function (registration) { // Registration was successful console.log('CustomServiceWorker registration successful with scope: ', registration.scope); }, function (err) { // registration failed console.log('CustomServiceWorker registration failed: ', err); });
This will register our service worker we defined in
sw.js
Source & More Info:
A2HS Prompt
Particular:
At last we're here, we now need to present the install dialog to user.
But now, an important issue here is, it will only prompt on event fire. For eg. on click event. So for eg. if you have a button in your html let's say, you'll fire a js onclickevent to call a function and show the prompt and bad part is it does not work automatically. But worry not, we'll get to this.
Implementation:
Create a
script.js file in the root directory where manifest belongs and add the following code:
let deferredPrompt; // add to homescreen window.addEventListener("beforeinstallprompt", (e) => { // Prevent Chrome 67 and earlier from automatically showing the prompt e.preventDefault(); // Stash the event so it can be triggered later. deferredPrompt = e; }); function isDeferredNotNull() { return deferredPrompt != null; } function presentAddToHome() { if (deferredPrompt != null) { // Update UI to notify the user they can add to home screen //; }); } else { console.log("deferredPrompt is null"); return null; } }
beforeinstallprompt will be called automatically when browser is ready to show prompt when A2HS conditions are fulfilled.
Now the idea is when
beforeinstallprompt fires, it will populate
defferredPrompt and we can then present the prompt.
Add this line in the head tag of
index.html file:
<script src="script.js" defer></script>
At this point, we've to check if all things are configured properly.
Run the app in browser and open developer tools (inspect) and navigate to application tab.
- Recheck manifest tab there, there should be no error or warning there.
- There should be no error or warning on the service worker tab too.
If there's no problem, then congratulations 🥳. We're all set with configurations, now we just need to call the prompt from our flutter app.
Show A2HS Prompt With Flutter
The concern here now is, how do we fire a JS callback from a button in flutter app let's say?
For this, now, we're going to use
universal_html package. We can also do it with
dart:js, but it's not recommended for using in flutter apps directly.
So go ahead and add
universal_html as dependency in your
pubspec.yaml file.
Link for package: Universal HTML
We will also require Shared Prefs, so add it too.
Link for package: Shared Preferences
We've to create a button to allow user to click and show the prompt. We'll for this eg. show a popup to user whenever it's ready to show prompt.
In
main.dart file, we've the good-old counter app.
import "package:universal_html/js.dart" as js; import 'package:flutter/foundation.dart' show kIsWeb;
Import the two packages.
And now add the following code to the
initState:
if (kIsWeb) { WidgetsBinding.instance!.addPostFrameCallback((_) async { final _prefs = await SharedPreferences.getInstance(); final>> Add to HomeScreen prompt is ready."); await showAddHomePageDialog(context); _prefs.setBool(_isWebDialogShownKey, true); } else { debugPrint(">>> Add to HomeScreen prompt is not ready yet."); } } }); }
Here, we first check if the platform is web, if yes, then call the
isDeferredNotNull function we wrote in
script.js file. This will return us, if the
defferredPrompt is not null (as we know this will only be not null when the browser is ready to show prompt.
If it's not null, then show the dialog and set the shared pref key to true to not show again.
Below is the dialog (popup) code:
Future<bool?> showAddHomePageDialog(BuildContext context) async { return showDialog<bool>( context: context, builder: (context) { return Dialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), child: Padding( padding: const EdgeInsets.all(24.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Center( child: Icon( Icons.add_circle, size: 70, color: Theme.of(context).primaryColor, )), SizedBox(height: 20.0), Text( 'Add to Homepage', style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600), ), SizedBox(height: 20.0), Text( 'Want to add this application to home screen?', style: TextStyle(fontSize: 16), ), SizedBox(height: 20.0), ElevatedButton( onPressed: () { js.context.callMethod("presentAddToHome"); Navigator.pop(context, false); }, child: Text("Yes!")) ], ), ), ); }, ); }
This will call the
presentAddToHome function in the
script.js to show the install prompt.
Final Step: HTTPS Context
For showing prompt, we need to host web app to a secure HTTPS hosting. We'll host the web app on Github Pages.
- Create a new repository, named "{username}.github.io"
- Run
flutter build web --web-renderer=html
- After successful build, navigate to
build/webdirectory.
- Initialize a new git repository and add remote to it. For
{username}.github.iothis repository.
- Push and wait for some time, check for the deployment status on the repository on GitHub.
And now, you're all done! 🥂
To check visit:
{username}.github.io
Important:
Things to keep in mind:
- Prompt will sometimes not be shown for the first time. Most probably it would be shown the next time you visit the page or reload the page. Please check it's terms. You can check the console, tab of the dev tools, if it's not ready you can see
deferredPrompt is nullprinted.
- Please see the supported browsers for
beforeinstallpromptcallback. Click here to see.
- Try in different browser if not working on one, for eg. Mozilla Firefox, Brave, etc.
- Will only work when hosted. Make sure you have no errors or warning on manifest in Applications tab in browser dev tools.
Hope you got the result you wanted!
Source Code:
That's all. This is my first article, I will love to hear suggestions to improve. Thanks! ❤️
Discussion (2)
thanks for the highly intuitive yet sophisticated walkthrough on the topic, a amusingly informative read indeed. fascinating how the web is evolving with PWAs and so is flutter web. the tutorial would be a instrumental source of documentation for anyone wanting to create a PWA, by letting others build upon this stuff, it's a boon :D
Thanks Aditya, I'll definitely try to make more stuff like this! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/iamsahilsonawane/a2hs-in-flutter-web-3cln | CC-MAIN-2021-49 | refinedweb | 1,740 | 59.7 |
ColdFusion 8: Experiment with compiling Java code from ColdFusion - Part 1
A few months back I was looking through the ColdFusion8\lib directory and noticed the tools.jar file which contained some intriguingly named classes. Needless to say I did not get around to exploring it then, but I finally did get back to it last weekend for a time.
Gold Rush
Now what caught my eye was a class named sun.tools.javac . If you have ever compiled a java class you will undoubtedly recognize the name. For those that have not, javac.exe is a small program used to compile java code from the command line and sun.tools.javac is a java class that allows you to do the same thing, only programatically. So the class definitely has some interesting potential.
Fool's Gold
At first I was very excited about the prospect of being able to compile java code from ColdFusion. But after further research and testing it did not pan out as well as I had hoped. The primary issues were:
Back to the drawing board I went.
The Real McCoy
Eventually I found the JavaCompiler class, which is an officially supported replacement for sun.tools.javac. The JavaCompiler was introduced in jdk 1.6. (Note the jdk reference. To use the JavaCompiler you must be running a jdk, not just a jre.) As with many java classes, JavaCompiler is designed to be extended so developers can easily add additional functionality. But you can still use the default implementation from ColdFusion, without having to build a custom java class. Fortunately an article on openjdk.com helped fill in some of the gaps in the main api.
Tool Time
Now to use the JavaCompiler I obviously needed some java code. So I created a rather pointless "Clock" class and saved the code to a file on disk. Note, you can use whatever directory you wish, but the file name must match the class name ie use "Clock.java".
<cfsavecontent variable="sourceCode">
import java.util.Date;
public class Clock
{
public Clock()
{
}
public String tick() {
return "tick tock it is: "+ new Date();
}
}
</cfsavecontent>
<cfset pathToSourceFile = "c:\myFiles\Clock.java" />
<cfset fileWrite(pathToSourceFile, sourceCode)>
Next, I grabbed a reference to the system compiler from the ToolProvider class. To compile the code I used the simpler JavaCompiler.run() method, which accepts several arguments. As the openJDK article describes:
The first three arguments to this method can be used to specify alternative streams to System.in, System.out, and System.err. The first two arguments are ignored by the compiler and the last one control where the output from -help and diagnostic messages will go.
So I first created output stream to capture any error messages. Next I created an array of the .java files I wanted to compile. Finally, I called the run() method to actually compile the java code. The result was a brand new .class file located in the same directory as my source file (ie c:\myFiles\ClockClass.class)
<cfset provider = createObject("java", "javax.tools.ToolProvider")>
<cfset compiler = provider.getSystemJavaCompiler()>
<cfset errStream = createObject("java", "java.io.ByteArrayOutputStream").init()>
<cfset args = [ pathToSourceFile ]>
<cfset status = compiler.run( javacast("null", ""),
javacast("null", ""),
errStream,
args
)>
<cfset message = toString(errStream.toByteArray())>
<cfset errStream.close()>
COMPILER RESULTS:<hr>
<cfoutput>
STATUS: #status# (0 == success) <br />
ERRORS: #message# <br />
</cfoutput>
(Drum Roll Please)
All that was left was to test the .class file. For this task I chose to use the JavaLoader.cfc. In its present incarnation, the JavaLoader cannot load individual class files. At least as far as I know. So I used the handy <cfzip> tag to add my new class file to a jar. Finally, I loaded my jar into the JavaLoader and voila, instant results.
Important note: The example below creates a new instance of the JavaLoader on each request for demonstration purposes only. See Using a Java URLClassLoader in CFMX Can Cause a Memory Leak for proper usage tips.
<cfzip action="zip" source="c:\myFiles\" filter="*.class" file="c:\myFiles\clock.jar">
<cfset jarPaths = [ "c:\myFiles\clock.jar" ] >
<cfset javaLoader = createObject("component", "javaLoader.JavaLoader").init(jarPaths)>
<cfset clock = javaLoader.create("Clock").init()>
COLDFUSION RESULTS:<hr>
<cfoutput>
clock.tick() = #clock.tick()# <br/ ><br />
</cfoutput>
<cfdump var="#clock#" label="My Clock class">
The World's Smallest Violin
As JavaCompiler has been around since version 1.6, I had no illusions that I was the first person to discover this tool. Java developers have probably known about it for quite some time. However, I really enjoyed learning about it and how to use it from ColdFusion. For that reason I chose to wait until the end to see if anyone else in the ColdFusion realm had blogged about it. Well, as I went to post this entry last night I was a bit crushed to discover Adrian Walker had just posted something similar two weeks ago. But as our approaches were a bit different, I decided to rise above my disappointment, and post it anyway ;) But seriously, I thought having a bit of extra background might be useful to those interested in using the tool.
So in the vein of "finish what you start" and "but ...{sputter} ... it is already written", more about compiling code with JavaCompiler.CompilationTask in Part 2 ...
- The sun.tools.javac class is internal and undocumented
- The sun.tools.javac class was deprecated around version 1.4
- When I tried using sun.tools.javac from ColdFusion 8, it did compile my source code. But it also bounced the CF Server in the process. (Granted I only ran a few cursory tests after discovering it was undocumented.)
| http://cfsearching.blogspot.com/2009/07/coldfusion-8-experiment-with-compiling.html | CC-MAIN-2018-39 | refinedweb | 937 | 59.3 |
[Java] BigDecimal Limitation
Hi all,. That's a luxury some people cannot afford if they would like to write a performant application. There should be a class just like StringBuffer for repeated manipulations of same numeric object. Your thoughts please.
JFanatic
Are you talking about garbage collection being a potential issue or the performance of BigDecimal itself? If it's garbage collection, there are lots of things you can do to tune the performance of the gc if you need to, but again, be sure that you need to before you start.You really need to be sure of your problem before you go implementating a solution to an issue that may not be there in reality.
For the interested, here are the performance test results on jdk1.5.0_11 with default VM options i.e. GC type(presumably serial collector), young generation & heap sizes. I just want to get the sum of 1 million atm transaction's amount in Java and hopefully accurate to a cent (we do care about money :)).
1) Using java primitives the result came in millisecs but not sure about accuracy.
2) With Commons mutable wrappers (thanks ryanh0) approx. same performance but accuracy is the issue.
3) And using BidDecimals i got java.lang.OutOfMemoryError: Java heap space :( just simply because of garbage involved while using BigDecimals.
All of you may agree that one of the factors that can effect the performance of an app is the performance of GC. If an app is to spent most of its execution time in GC we can imagine the impact on performance which is exactly the case here. GC is trying desperately to get some memory free so that app can work but when BigDecimal + associated String instances are taking 99% of heap what else can be done.
Can anyone please explain, the reason behind making these numerics immutable, we should forget multithreaded usage as being the reason. This should be left to app developer to ensure synchronization. Besides all the apps are not multithreaded. When folks at apache can think of a usage of mutable wrappers in real life definitely SUN can also.
public class BigDecimalTest {
public static void main(String[] args) {
final int SIZE = 1000000;
final Random r = new Random();
BigDecimal[] bdList = new BigDecimal[SIZE];
BigDecimal sum = new BigDecimal("0.00");
System.out.println("Initialization Start--->" + System.nanoTime());
for (int i = 0; i < bdList.length; i++) {
bdList[i] = new BigDecimal(Double.toString(r.nextDouble() * 100));
}
System.out.println("Initialization End--->" + System.nanoTime());
System.out.println("Start Summing--->" + System.nanoTime());
for (int i = 0; i < bdList.length; i++) {
sum = sum.add(bdList[i]);
}
System.out.println("Result--->" + System.nanoTime());
}
}
There is something wrong with the editor here, test code got corrupted. But it should not be hard to imagine what might be going on. just to avoid confusion if it may arise
1st for loop is initializing the BDs with timestamp printed before & after
2nd is just summing the list in sum variable again with timestamp printed before & after
Well, your test code is a bit extreme. You are not allowing anything (much) to be gc'd as you hold all the references to every(most) BigDecimal during the lifecycle of your main. In real life you are unlikely to be in this situation, with an array of 1000000 items held in memory (which by itself must take you close to the default limit of the jvm). I don't think there is anything special about BigDecimal that will prevent it from being gc'ed.
Message was edited by: stevegal
To stevegal & dansiviter:
Its true that in the test code all the declarations are outside the loops but these are just reference declarations and assuming my java knowledge is correct assigning a reference previously pointing to object o1 to a new object o2 makes o1 garbage collectable.
As for holding 1million objects at the same time, well MutableDoublez are performing with the same heap size. Problem is BigDecimal requires 2million to do the same job :).
Yes we can move to tuning jvm, increase heap size etc. Unfortunately that is all left to us today just because we wanted to stick to "standard options" available in java to do simple additions with reasonable performance and accuracy. Inventing homegrown solutions is not a viable option sometimes and most of us here are app developers not system developers.
Thanks
This is beginning to sound like a microbenchmark and what stevegal and dansiviter are hinting at is; microbenchmarking is notoriously difficult. If you are not careful, you will be measuring some pathology that has nothing to do with your initial question. It would be useful if you could post your code so that we can have a look at it.
Regards,
Kirk
Hi kirk
I think we are beginning to get astray from the real topic, performance test was only done because some of the posters here objected that you are saying something about BD w/o actually giving proof of its performance which all of us should know will be very slow no matter what. The question is not about how many objects we are allocating at 1 time to avoid OutOfMemory exception 1Milllion,10Million or even mere 100, BD will remain slow. The question is not about why i am not tuning my JVM to allocate more memory etc, i know this is a way to go even when i feel that memory i allocate for my app should be used to hold app specific data and not some garbage.My real question to which no one is giving any answers is why BD in java is immutable and should we have a mutable version as a standard option because BD is the only option in standard java to get accurate floating point results. I know that SUN has planned to provide some usability benefits for BD as part of SE 7.0 like operator overloading how wonderful it would be if some attention should be paid towards its performance also.
Thanks
Okay, okay, I'll bite :D
are you asking why immutable objects are a good thing? Have you thought about what might happen in a highly multithreaded app if you are passing around objects that mutate from underneath you? At least with an immutable object you can be sure that when you for example
if (myBigDecimal.compareTo(someOtherBigDecimal)>1)
{
final BigDecimal newValue = this.doSomething(myBigDecimal,someOtherBigDecimal);
}
then the values in the variable myBigDecimal and someOtherBigDecimal have not changed by the time you get to the this.doSomething method. Without immutability how can you be sure. Especially important in a finiancial app I would have though!!!
but then again I do like the keyword final :D
Do you have actual performance problems? Have you done performance test with an alternative implementation?
The results of performance tests are frequently surprising. Even when JRE doesn't optimize code. If BigDecimal were mutable it still has to allocate an array for the result. Not always, but the overhead of filtering these cases and the additional complexity of calculating in place may give worser performance. Without measurement you cannot tell whether a mutable version would be faster..
'How expensive is allocation?'
'Urban performance legend #3: Immutable objects are bad for performance'
Also in theory the JVM does not have to allocate a new object on the heap at all and could benefit from escape analysis and allocate on the stack.
>.
This is incorrect. GC will reclaim what it can when it can. Also object reuse should be avoided. References should be released as soon as possible. This allows collection in young. The young collector work by copying live objects out of Eden/Survivors. One could almost argue that this isn't garbage collection, it's live object harvesting. From this point of view you should see that short lived objects will not be harvested == very little work to reclaim the space. Longer lived objects will needed to be harvested (read copied) and that is an expensive operation which involves work to swizzle pointers and so on.
>
>
> 'Urban performance legend #3: Immutable objects are
> bad for performance'
>
> 223.html
Brian has been pushing immutability because it works better in multi-threaded applications. There is no question that immutability is a drain on performance. However, I would not thread safety for performance. The advice offered by Brian is mostly good. You're going to have to evaluate it in your particular context to see what's best.
>
> Also in theory the JVM does not have to allocate a
> new object on the heap at all and could benefit from
> escape analysis and allocate on the stack.
This isn't working just yet.
Regards,
Kirk
I think this depends on the operation mix and the size of the values involved. For multiplication with large values the limitation is the use of the classical algorithm and not gc. Adding up a series of values might benefit from a mutable version, but perhaps a better solution would be to provide a method which adds up an array of (Number) values. This could then use a mutable value internally (which already exists) and return an immutable result.
Often though you won't save much because Java's allocation of short lived memory is rather fast.
How bizarre you should point this out as I've been discussing this with a colleague today.
Unfortunately, the story is even less black and white as you've pointed out. When using the BigDecimal it's not treated as a normal class by the JVM internals. After a quick Google it turns out JVM vendors have apparently put some magical code that streamlines the usage of the class. Don't bother asking me how... but it works.
By creating some basic tests an internally written mutable decimal class [with zero internal class creation] was outperformed by BigDecimal. BigDecimal even got better when you add the '-server' flag (using JDK 1.5.0_14).
I've not had the heart to tell the guy who wrote it yet. :oP
Caveat: I've only tried this with the normal JVM and not the real-time one so cannot vouch for its behaviour in that environment, but I'd imagine it's the same.
I know jakarta commons lang has some Mutable numbers, but unfortunately no BigDecimal impl.
Maybe they have one planned or a reason for not having one...
Right, just to save face on my part, it looks like I got the wrong end of the stick with JVM optimisations [further reading suggests the BigDecimal internals were improved], but my point still stands that BigDecimal is still very quick.
Though a mutable version of BigDecimal would be nice, I feel it's still not a limitation of Java. There are a lot of clever developers out there writing financial applications in Java real-time JVM with no need for this. I agree with a number of other posters here that maybe worth looking at tuning the GC. | https://www.java.net/node/682587 | CC-MAIN-2015-27 | refinedweb | 1,834 | 63.29 |
Details
Description
When the mime type of an M4V file is detected using its name only, it returns video/x-m4v. When it is detected using the InputStream (hence utilising the MagicDetector), it incorrectly returns video/quicktime.
Using the sample M4V file from Apple's knowledge base:
public class TikaTest { public static void main(String[] args) throws Exception { String userHome = System.getProperty("user.home"); File file = new File(userHome + "/Desktop/sample_iPod.m4v"); InputStream is = TikaInputStream.get(file); Detector detector = new DefaultDetector( MimeTypes.getDefaultMimeTypes()); Metadata metadata = new Metadata(); metadata.set(Metadata.RESOURCE_NAME_KEY, file.getName()); System.out.println("File + filename: " + detector.detect(is, metadata)); System.out.println("File only: " + detector.detect(is, new Metadata())); System.out.println("Filename only: " + detector.detect(null, metadata)); } }
Renders the output:
File + filename: video/quicktime File only: video/quicktime Filename only: video/x-m4v
Moreover, if the same test is run against an M4A file, the results are even more incorrect:
File + filename: video/quicktime File only: video/quicktime Filename only: application/octet-stream
Activity
- All
- Work Log
- History
- Activity
- Transitions
I've added the m4b extension to audio/mp4 in r1237113.
Nick, although you add the ftyp for M4B (the bookmarkable format), you don't take into account its extension .m4b. Do you think you can add that?
Thanks Nick for adding the alias.
I've added the audio/x-m4a alias in r1236734.
From
"Generally speaking, atoms can be present in any order. Do not conclude that a particular atom is not present until you have parsed all the atoms in the file.
An exception is the file type atom, which typically identifies the file as a QuickTime movie. If present, this atom precedes any movie atom, movie data, preview, or free space atoms. If you encounter one of these other atom types prior to finding a file type atom, you may assume the file type atom is not present. (This atom is introduced in the QuickTime File Format Specification for 2004, and is not present in QuickTime movie files created prior to 2004)."
So, if there is a ftyp atom, it should be first, and if the first atom isn't a ftyp then there isn't one. The AtomParsely link is handy, that should help with producing a metadata extracting parser
Sorry Nick, I didn't notice you update the SVN. It looks like you need to change your mime type though from audio/x-mp4a to audio/x-m4a.
I've added a patch file that I think should fix the problem for both M4V and M4A.
According to AtomParsley, "The ftyp atom is ALWAYS first." This seems to corroborate with Apple's spec discussion on "The Movie Profile Atom".
It looks like most files (not sure if it's all of them though) have a ftyp atom at byte 4. This has "ftyp" followed by a 4 byte (space padded if needed) string of the main type. There's a list of the common ones at
I've added more specific matches for the common types in r1236700. Using the tika-app jar, I can now correctly detect mp4 video, Apple m4v video, mp4 audio and old quicktime movs (using the lower priority fallback)
I'm not sure if the ftyp atom has to be first or not, if it isn't then this detection won't work. Longer term, a proper file format aware detector would be best, ideally one that can also understand the rest of the format to report on different streams etc
I'm not sure if we're going to be able to differentiate between .mov, .mp4 and .m4v with only mime magic, as I believe they all use the same container format
We may need to look at a detector that opens the files up and checks them in a container aware manner
Thanks! | https://issues.apache.org/jira/browse/TIKA-851?focusedCommentId=13194854&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2016-07 | refinedweb | 639 | 63.29 |
Warning: sprintf(): Too few arguments in /membri/thepythoncorner/wp-content/plugins/wp-codemirror-block/includes/class-codemirror-blocks.php on line 187
On December the 8th Guido van Rossum (also known to be the BDFL or the Python project) announced on his twitter account that Python 3.6 rc1 has been officially released. That means that if no major problems will be found with this latest version, the final release is just around the corner and it’s scheduled to be released on December the 16th, carrying among other things also some improvements in the Python syntax.
Let’s have a look at this new “syntax sugar”!
Formatted string literals
The formatted string literals are one of my favorite features ever! Since today, if you wanted to create a string with some variable value inside you could do something like:
>>>>> print ("Hi " + name)
or:
or again:
>>>>> print(str.format("Hi {0}", name))
We’re not going to describe the pros and cons of these methods here, but the shiny new method to accomplish this task is
>>>>> print (f"Hi {name}")
Pretty cool, uh? And these methods works great also with other variable types like numbers. For example:
>>> number = 10/3 >>> print(f"And the number is: {number:5.3}")
Note that in this last example we have also formatted the number specifying the width (5) and the precision (3).
Underscores in Numeric Literals
This feature is better seen that explained: what’s the value of the variable “big_number” after this assignment?
>>> big_number = 1000000000
If you like me needs to count the zeroes to say that big_number is a billion, you will be probabily happy to know that from now on, this assignment can be written like this:
>>> big_number = 1_000_000_000
Syntax for variable annotations
If you need to annotate the type of a variable now you can use this special syntax:
variable: type
this means that you can write something like
>>> some_list: [int] = []
this doesn’t do anything more than before, Python is a dinamically typed language and so it will be in the future, but if you read some third party code this notation lets you know that some_list is not just a list, but it’s intended to be a list of integers. Note: I say it’s “intended to be” just because nothing prevents you from assigning some_list any other kind of value! This new variable annotation is just intended to avoid writing something like
>>> some_list = [] # this is a list of integers
Asynchronous generators
Asynchronous generators have been awaited since Python 3.5, that introduced the async / await syntax feature. In fact, one of the limitation it had was that it was impossible to use the yield and the await statements in the same body. This restriction has been lifted and in the documentation, there’s a quite interesting example that shows a function called “ticker” that generate a number from 0 to a limit passed as a parameter every X seconds (again, passed as a parameter).
import asyncio async def ticker(delay, to): """Yield numbers from 0 to *to* every *delay* seconds.""" for i in range(to): yield i await asyncio.sleep(delay) async def main(): async for x in ticker(1,10): print(x) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main())
Asynchronous comprehensions
If I asked you to modify the previous example so to create a list using the generator you would probabily modify the code this way:
import asyncio async def ticker(delay, to): """Yield numbers from 0 to *to* every *delay* seconds.""" for i in range(to): yield i await asyncio.sleep(delay) async def main(): mylist = [] async for x in ticker(1,10): mylist.append(x) print (mylist) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main())
But wouldn’t it be great if we could use list comprehensions like we do when working in “synchronous mode”? Now, we can:
import asyncio async def ticker(delay, to): """Yield numbers from 0 to *to* every *delay* seconds.""" for i in range(to): yield i await asyncio.sleep(delay) async def main(): mylist = [await x async for x in ticker(1,10)] print (mylist) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main())
That’s all for now, happy coding in Python 3.6! 🙂 | https://www.thepythoncorner.com/2016/12/syntax-sugar-in-python-3-6/ | CC-MAIN-2020-05 | refinedweb | 711 | 58.01 |
PTHREAD_SET_NAME_NP(3) BSD Programmer's Manual PTHREAD_SET_NAME_NP(3)
pthread_set_name_np - set the name of a thread
#include <pthread.h> #include <pthread_np.h> void pthread_set_name_np(pthread_t thread, char *name);
The pthread_set_name_np() function associates name with thread. This can be useful for debugging, as the name is displayed in the thread status as displayed when the process receives the SIGINFO signal. The string pointed to by name is copied, and so need not be valid for the life of the thread.
pthreads(3)
The pthread_set_name_np() function is non-portable and may not be sup- ported with the above semantics on other POSIX systems. MirOS BSD #10-current December. | http://mirbsd.mirsolutions.de/htman/sparc/man3/pthread_set_name_np.htm | crawl-003 | refinedweb | 105 | 66.03 |
In this tutorial, we introduce the quantum fourier transform (QFT), derive the circuit, and implement it using Qiskit. We show how to run QFT on a simulator and a five qubit device.
Contents
- Introduction
- Intuition
2.1 Counting in the Fourier Basis
- Example 1: 1-qubit QFT
- The Quantum Fourier transform
- The Circuit that Implements the QFT
- Example 2: 3-qubit QFT
- Some Notes About the Form of the QFT Circuit
- Qiskit Implementation
8.1 Example on 3 Qubits
8.2 General QFT Function
8.3 Running QFT on a Real Quantum Device
- Problems
- References
1. Introduction
The Fourier transform occurs in many different versions throughout classical computing, in areas ranging from signal processing to data compression to complexity theory. The quantum Fourier transform (QFT) is the quantum implementation of the discrete Fourier transform over the amplitudes of a wavefunction. It is part of many quantum algorithms, most notably Shor's factoring algorithm and quantum phase estimation.
The discrete Fourier transform acts on a vector $(x_0, ..., x_{N-1})$ and maps it to the vector $(y_0, ..., y_{N-1})$ according to the formula$$y_k = \frac{1}{\sqrt{N}}\sum_{j=0}^{N-1}x_j\omega_N^{jk}$$
where $\omega_N^{jk} = e^{2\pi i \frac{jk}{N}}$.
Similarly, the quantum Fourier transform acts on a quantum state $\sum_{i=0}^{N-1} x_i \vert i \rangle$ and maps it to the quantum state $\sum_{i=0}^{N-1} y_i \vert i \rangle$ according to the formula$$y_k = \frac{1}{\sqrt{N}}\sum_{j=0}^{N-1}x_j\omega_N^{jk}$$
with $\omega_N^{jk}$ defined as above. Note that only the amplitudes of the state were affected by this transformation.
This can also be expressed as the map:$$\vert x \rangle \mapsto \frac{1}{\sqrt{N}}\sum_{y=0}^{N-1}\omega_N^{xy} \vert y \rangle$$
Or the unitary matrix:$$ U_{QFT} = \frac{1}{\sqrt{N}} \sum_{x=0}^{N-1} \sum_{y=0}^{N-1} \omega_N^{xy} \vert y \rangle \langle x \vert$$
2. Intuition
The quantum Fourier transform (QFT) transforms between two bases, the computational (Z) basis, and the Fourier basis. The H-gate is the single-qubit QFT, and it transforms between the Z-basis states $|0\rangle$ and $|1\rangle$ to the X-basis states $|{+}\rangle$ and $|{-}\rangle$. In the same way, all multi-qubit states in the computational basis have corresponding states in the Fourier basis. The QFT is simply the function that transforms between these bases.$$ |\text{State in Computational Basis}\rangle \quad \xrightarrow[]{\text{QFT}} \quad |\text{State in Fourier Basis}\rangle $$$$ \text{QFT}|x\rangle = |\widetilde{x}\rangle $$
(We often note states in the Fourier basis using the tilde (~)).
2.1 Counting in the Fourier basis:
In the computational basis, we store numbers in binary using the states $|0\rangle$ and $|1\rangle$:
Note the frequency with which the different qubits change; the leftmost qubit flips with every increment in the number, the next with every 2 increments, the third with every 4 increments, and so on. In the Fourier basis, we store numbers using different rotations around the Z-axis:
The number we want to store dictates the angle at which each qubit is rotated around the Z-axis. In the state $|\widetilde{0}\rangle$, all qubits are in the state $|{+}\rangle$. As seen in the example above, to encode the state $|\widetilde{5}\rangle$ on 4 qubits, we rotated the leftmost qubit by $\tfrac{5}{2^n} = \tfrac{5}{16}$ full turns ($\tfrac{5}{16}\times 2\pi$ radians). The next qubit is turned double this ($\tfrac{10}{16}\times 2\pi$ radians, or $10/16$ full turns), this angle is then doubled for the qubit after, and so on.
Again, note the frequency with which each qubit changes. The leftmost qubit (
qubit 0) in this case has the lowest frequency, and the rightmost the highest.
3. Example 1: 1-qubit QFT
Consider how the QFT operator as defined above acts on a single qubit state $\vert\psi\rangle = \alpha \vert 0 \rangle + \beta \vert 1 \rangle$. In this case, $x_0 = \alpha$, $x_1 = \beta$, and $N = 2$. Then,$$y_0 = \frac{1}{\sqrt{2}}\left( \alpha \exp\left(2\pi i\frac{0\times0}{2}\right) + \beta \exp\left(2\pi i\frac{1\times0}{2}\right) \right) = \frac{1}{\sqrt{2}}\left(\alpha + \beta\right)$$
and$$y_1 = \frac{1}{\sqrt{2}}\left( \alpha \exp\left(2\pi i\frac{0\times1}{2}\right) + \beta \exp\left(2\pi i\frac{1\times1}{2}\right) \right) = \frac{1}{\sqrt{2}}\left(\alpha - \beta\right)$$
such that the final result is the state$$U_{QFT}\vert\psi\rangle = \frac{1}{\sqrt{2}}(\alpha + \beta) \vert 0 \rangle + \frac{1}{\sqrt{2}}(\alpha - \beta) \vert 1 \rangle$$
This operation is exactly the result of applying the Hadamard operator ($H$) on the qubit:$$H = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}$$
If we apply the $H$ operator to the state $\vert\psi\rangle = \alpha \vert 0 \rangle + \beta \vert 1 \rangle$, we obtain the new state:$$\frac{1}{\sqrt{2}}(\alpha + \beta) \vert 0 \rangle + \frac{1}{\sqrt{2}}(\alpha - \beta) \vert 1 \rangle \equiv \tilde{\alpha}\vert 0 \rangle + \tilde{\beta}\vert 1 \rangle$$
Notice how the Hadamard gate performs the discrete Fourier transform for $N = 2$ on the amplitudes of the state.
So what does the quantum Fourier transform look like for larger $N$? Let's derive a transformation for $N=2^n$, $QFT_N$ acting on the state $\vert x \rangle = \vert x_1\ldots x_n \rangle$ where $x_1$ is the most significant bit. This maths is here for those that find it useful, if you struggle with it then don’t worry; as long as you understand the intuition in section 2 then you can continue straight to the next section.$$ \begin{aligned} QFT_N\vert x \rangle & = \frac{1}{\sqrt{N}} \sum_{y=0}^{N-1}\omega_N^{xy} \vert y \rangle \\ & = \frac{1}{\sqrt{N}} \sum_{y=0}^{N-1} e^{2 \pi i xy / 2^n} \vert y \rangle ~\text{since}\: \omega_N^{xy} = e^{2\pi i \frac{xy}{N}} \:\text{and}\: N = 2^n \\ & = \frac{1}{\sqrt{N}} \sum_{y=0}^{N-1} e^{2 \pi i \left(\sum_{k=1}^n y_k/2^k\right) x} \vert y_1 \ldots y_n \rangle \:\text{rewriting in fractional binary notation}\: y = y_1\ldots y_n, y/2^n = \sum_{k=1}^n y_k/2^k \\ & = \frac{1}{\sqrt{N}} \sum_{y=0}^{N-1} \prod_{k=1}^n e^{2 \pi i x y_k/2^k } \vert y_1 \ldots y_n \rangle \:\text{after expanding the exponential of a sum to a product of exponentials} \\ & = \frac{1}{\sqrt{N}} \bigotimes_{k=1}^n \left(\vert0\rangle + e^{2 \pi i x /2^k } \vert1\rangle \right) \:\text{after rearranging the sum and products, and expanding} \sum_{y=0}^{N-1} = \sum_{y_1=0}^{1}\sum_{y_2=0}^{1}\ldots\sum_{y_n=0}^{1} \\ & = \frac{1}{\sqrt) \end{aligned} $$
This is a mathematical description of the animation we saw in the intuition section:
5. The Circuit that Implements the QFT
The circuit that implements QFT makes use of two gates. The first one is a single-qubit Hadamard gate, $H$, that you already know. From the discussion in Example 1 above, you have already seen that the action of $H$ on the single-qubit state $\vert x_k\rangle$ is$$H\vert x_k \rangle = \frac{1}{\sqrt{2}}\left(\vert0\rangle + \exp\left(\frac{2\pi i}{2}x_k\right)\vert1\rangle\right)$$
The second is a two-qubit controlled rotation $CROT_k$ given in block-diagonal form as$$CROT_k = \left[\begin{matrix} I&0\\ 0&UROT_k\\ \end{matrix}\right]$$
where$$UROT_k = \left[\begin{matrix} 1&0\\ 0&\exp\left(\frac{2\pi i}{2^k}\right)\\ \end{matrix}\right]$$
The action of $CROT_k$ on the two-qubit state $\vert x_jx_k\rangle$ where the first qubit is the control and the second is the target is given by$$CROT_k\vert 0x_j\rangle = \vert 0x_j\rangle$$
and$$CROT_k\vert 1x_j\rangle = \exp\left( \frac{2\pi i}{2^k}x_j \right)\vert 1x_j\rangle$$
Given these two gates, a circuit that implements an n-qubit QFT is shown below.
The circuit operates as follows. We start with an n-qubit input state $\vert x_1x_2\ldots x_n\rangle$.
- After the first Hadamard gate on qubit 1, the state is transformed from the input state to $$ H_1\vert x_1x_2\ldots x_n\rangle = \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left(\frac{2\pi i}{2}x_1\right)\vert1\rangle\right] \otimes \vert x_2x_3\ldots x_n\rangle $$
- After the $UROT_2$ gate on qubit 1 controlled by qubit 2, the state is transformed to $$ \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left(\frac{2\pi i}{2^2}x_2 + \frac{2\pi i}{2}x_1\right)\vert1\rangle\right] \otimes \vert x_2x_3\ldots x_n\rangle $$
- After the application of the last $UROT_n$ gate on qubit 1 controlled by qubit $n$, the state becomes $$ \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left( \frac{2\pi i}{2^n}x_n + \frac{2\pi i}{2^{n-1}}x_{n-1} + \ldots + \frac{2\pi i}{2^2}x_2 + \frac{2\pi i}{2}x_1 \right) \vert1\rangle\right] \otimes \vert x_2x_3\ldots x_n\rangle $$ Noting that $$ x = 2^{n-1}x_1 + 2^{n-2}x_2 + \ldots + 2^1x_{n-1} + 2^0x_n $$ we can write the above state as $$ \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left( \frac{2\pi i}{2^n}x \right) \vert1\rangle\right] \otimes \vert x_2x_3\ldots x_n\rangle $$
- After the application of a similar sequence of gates for qubits $2\ldots n$, we find the final state to be: $$ \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left( \frac{2\pi i}{2^n}x \right) \vert1\rangle\right] \otimes \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left( \frac{2\pi i}{2^{n-1}}x \right) \vert1\rangle\right] \otimes \ldots \otimes \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left( \frac{2\pi i}{2^{2}}x \right) \vert1\rangle\right] \otimes \frac{1}{\sqrt{2}} \left[\vert0\rangle + \exp\left( \frac{2\pi i}{2^{1}}x \right) \vert1\rangle\right] $$ which is exactly the QFT of the input state as derived above with the caveat that the order of the qubits is reversed in the output state.
6. Example 2: 3-qubit QFT
The steps to creating the circuit for $\vert y_3y_2y_1\rangle = QFT_8\vert x_3x_2x_1\rangle$ would be:
- Apply a Hadamard gate to $\vert x_1 \rangle$ $$ \psi_1 = \vert x_3\rangle \otimes \vert x_2\rangle \otimes \frac{1}{\sqrt{2}} \left[ \vert0\rangle + \exp\left(\frac{2\pi i}{2}x_1\right) \vert1\rangle\right] $$
- Apply a $UROT_2$ gate to $\vert x_1\rangle$ depending on $\vert x_2\rangle$ $$ \psi_2 = \vert x_3\rangle \otimes \vert x_2\rangle \otimes \frac{1}{\sqrt{2}} \left[ \vert0\rangle + \exp\left( \frac{2\pi i}{2^2}x_2 + \frac{2\pi i}{2}x_1 \right) \vert1\rangle\right] $$
- Apply a $UROT_3$ gate to $\vert x_1\rangle$ depending on $\vert x_3\rangle$ $$ \psi_3 = \vert x_3\rangle \otimes \vert x_2\rangle _2 \rangle$ $$ \psi_4 = \vert x_3\rangle \otimes \frac{1}{\sqrt{2}} \left[ \vert0\rangle + \exp\left( $UROT_2$ gate to $\vert x_2\rangle$ depending on $\vert x_3\rangle$ $$ \psi_5 = \vert x_3\rangle _3\rangle$ $$ \psi_6 = \frac{1}{\sqrt{2}} \left[ \vert0\rangle + \exp\left( \frac{2\pi i}{2}x_3 \right) \vert1\rangle\right] ] $$
- Keep in mind the reverse order of the output state relative to the desired QFT. Therefore, we must reverse the order of the qubits (in this case swap $y_1$ and $y_3$).
The example above demonstrates a very useful form of the QFT for $N=2^n$. Note that only the last qubit depends on the values of all the other input qubits and each further bit depends less and less on the input qubits. This becomes important in physical implementations of the QFT, where nearest-neighbor couplings are easier to achieve than distant couplings between qubits.
Additionally, as the QFT circuit becomes large, an increasing amount of time is spent doing increasingly slight rotations. It turns out that we can ignore rotations below a certain threshold and still get decent results, this is known as the approximate QFT. This is also important in physical implementations, as reducing the number of operations can greatly reduce decoherence and potential gate errors.
8. Qiskit Implementation
In Qiskit, the implementation of the $CROT$ gate used in the discussion above is a controlled phase rotation gate. This gate is defined in OpenQASM as$$ CU_1(\theta) = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{i\theta}\end{bmatrix} $$
Hence, the mapping from the $CROT_k$ gate in the discussion above into the $CU_1$ gate is found from the equation$$ \theta = 2\pi/2^k = \pi/2^{k-1} $$
8.1 Example on 3 Qubits
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector %config InlineBackend.figure_format = 'svg' # Makes the images look nice
It is useful to work out the relevant code for the 3-qubit case before generalizing to the $n$-qubit case. First, we must define our quantum circuit:
qc = QuantumCircuit(3)
Note: Remember that Qiskit's least significant bit has the lowest index (0), thus the circuit will be mirrored through the horizontal in relation to the image in section 5. First, we apply a H-gate to qubit 2 :
qc.h(2) qc.draw('mpl')
Next, we want to turn this an extra quarter turn if qubit 1 is in the state $|1\rangle$:
qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 qc.draw('mpl')
And another eighth turn if the least significant qubit (0) is $|1\rangle$:
qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 qc.draw('mpl')
With that qubit taken care of, we can now ignore it and repeat the process, using the same logic for qubits 0 and 1:
qc.h(1) qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.draw('mpl')
Finally we must swap the qubits 0 and 2 to complete the QFT:
qc.swap(0,2) qc.draw('mpl')
8.2 General QFT Function
We will now create a general circuit for the QFT in Qiskit. Creating large general circuits like this is really where Qiskit shines.
It is easier to build a circuit that implements the QFT with the qubits upside down, then swap them afterwards; we will start off by creating the function that rotates our qubits correctly. Let’s start as we did with the 3 qubit example, by correctly rotating the most significant qubit (the qubit with the highest index):
def qft_rotations(circuit, n): if n == 0: # Exit function if circuit is empty return circuit n -= 1 # Indexes start from 0 circuit.h(n) # Apply the H-gate to the most significant qubit for qubit in range(n): # For each less significant qubit, we need to do a # smaller-angled controlled rotation: circuit.cu1(pi/2**(n-qubit), qubit, n)
Let’s see how this looks:
qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw('mpl')
We can use the widget below to see how this circuit scales with the number of qubits in our circuit:
from qiskit_textbook.widgets import scalable_circuit scalable_circuit(qft_rotations)
Great! This is the first part of our QFT. Now we have correctly rotated the most significant qubit, we need to correctly rotate the second most significant qubit. Then we must deal with the third most significant, and so on. But why write more code? When we get to the end of our
qft_rotations() function, we can use the same code to repeat the process on the next
n-1 qubits:
def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cu1(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw('mpl')
That was easy! Using a function inside another function is called recursion. It can greatly simplify code. We can again see how this scales using the widget below:
scalable_circuit(qft_rotations)
Finally, we need to add the swaps at the end of the QFT function to match the definition of the QFT. We will combine this into the final function
qft():
def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(4) qft(qc,4) qc.draw('mpl')
This is the generalised circuit for the quantum Fourier transform. We can again see how this scales using the widget below:
scalable_circuit(qft)
We now want to demonstrate this circuit works correctly. To do this we must first encode a number in the computational basis. We can see the number 5 in binary is
101:
bin(5)
'0b101'
(The
0b just reminds us this is a binary number). Let's encode this into our qubits:
# Create the circuit qc = QuantumCircuit(3) # Encode the state 5 qc.x(0) qc.x(2) %config InlineBackend.figure_format = 'svg' # Makes the images fit qc.draw('mpl')
And let's check the qubit's states using the statevector simulator:
backend = Aer.get_backend("statevector_simulator") statevector = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(statevector)
Finally, let's use our QFT function and view the final state of our qubits:
qft(qc,3) qc.draw('mpl')
statevector = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(statevector)
We can see out QFT function has worked correctly. Compared the the state $|\widetilde{0}\rangle = |{+}{+}{+}\rangle$, Qubit 0 has been rotated by $\tfrac{5}{8}$ of a full turn, qubit 1 by $\tfrac{10}{8}$ full turns (equivalent to $\tfrac{1}{4}$ of a full turn), and qubit 2 by $\tfrac{20}{8}$ full turns (equivalent to $\tfrac{1}{2}$ of a full turn).
If we tried running the circuit at the end of section 8.2 on a real device, the results would be completely random, since all qubits are in equal superposition of $|0\rangle$ and $|1\rangle$. If we want to demonstrate and investigate the QFT working on real hardware, we can instead create the state $|\widetilde{5}\rangle$ seen at the end of section 8.2, run the QFT in reverse, and verify the output is the state $|5\rangle$ as expected.
Firstly, let’s use Qiskit to easily reverse our QFT operation:
def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates
Now let's put our qubits in the state $|\widetilde{5}\rangle$:
nqubits = 3 number = 5 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.u1(number*pi/4,0) qc.u1(number*pi/2,1) qc.u1(number*pi,2) qc.draw('mpl')
And we can see this does indeed result in the Fourier state $|\widetilde{5}\rangle$:
backend = Aer.get_backend("statevector_simulator") statevector = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(statevector) | https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html | CC-MAIN-2020-50 | refinedweb | 3,329 | 56.29 |
Details
- Type:
Improvement
- Status: Closed
- Priority:
Major
- Resolution: Won't Fix
- Affects Version/s: None
-
- Component/s: core/index
- Labels:None
- Lucene Fields:New, Patch Available
Description
Lucene makes use of infoStream to output messages in its indexing code only. For debugging purposes, when the search application is run on the customer side, getting messages from other code flows, like search, query parsing, analysis etc can be extremely useful.
There are two main problems with infoStream today:
1. It is owned by IndexWriter, so if I want to add logging capabilities to other classes I need to either expose an API or propagate infoStream to all classes (see for example DocumentsWriter, which receives its infoStream instance from IndexWriter).
2. I can either turn debugging on or off, for the entire code.
Introducing a logging framework can allow each class to control its logging independently, and more importantly, allows the application to turn on logging for only specific areas in the code (i.e., org.apache.lucene.index.*).
I've investigated SLF4J (stands for Simple Logging Facade for Java) which is, as it names states, a facade over different logging frameworks. As such, you can include the slf4j.jar in your application, and it recognizes at deploy time what is the actual logging framework you'd like to use. SLF4J comes with several adapters for Java logging, Log4j and others. If you know your application uses Java logging, simply drop slf4j.jar and slf4j-jdk14.jar in your classpath, and your logging statements will use Java logging underneath the covers.
This makes the logging code very simple. For a class A the logger will be instantiated like this:
public class A
And will later be used like this:
public class A {
private static final logger = LoggerFactory.getLogger(A.class);
public void foo() {
if (logger.isDebugEnabled())
}
}
That's all !
Checking for isDebugEnabled is very quick, at least using the JDK14 adapter (but I assume it's fast also over other logging frameworks).
The important thing is, every class controls its own logger. Not all classes have to output logging messages, and we can improve Lucene's logging gradually, w/o changing the API, by adding more logging messages to interesting classes.
I will submit a patch shortly
Activity
- All
- Work Log
- History
- Activity
- Transitions
> Should I attach the slf4j jars separately?
If we go with SLF4J, we'd want to include the -api jar in Lucene for sure, along with a single implementation. My vote would be for the -nop implementation. Then, folks who want logging can include the implementation they like.
Thanks Doug,
I've replaced the JDK14 jar with the NOP jar and deleted the logging test I added (since NOP does not log anything).
Forgot to clean up some code in tests which made use of JDK logging..
I kept safeDebugMsg because it was used by a class which extended IndexWriter and relied on that method to be called. However, I fixed the class by overriding testPoint instead. So I can now remove safeDebugMsg.
As for the output format, I agree that it should be handled by the logging system, but wanted to confirm that with other members before I change it. I'm glad that you agree to that too.
Attached is a new patch which removes the method.
Is there anything else I can do in order to help drive this issue forward?
In the mail thread, Yonik said ():
I'm leery of going down this logging road because people may add
logging statements in inappropriate places, believing that
isLoggable() is about the same as infoStream != null
They seem roughly equivalent because of the context in which they are
tested: coarse grained logging where the surrounding operations
eclipse the logging check.
isLoggable() involves volatile reads, which prevent optimizations and
instruction reordering across the read. On current x86 platforms, no
memory barrier instructions are needed for a volatile read, but that's
not true of other architectures.
Thoughts on how to address this? Have you done any performance testing of this patch versus the current system, both w/ infoStream == null and infoStream != null..
While the patch itself is likely minor, the implications of applying the patch are significant, IMO
I haven't done any performance test since after following Doug's proposal, I switched to using the NOP logger which all of its isLoggable()-like calls return false. That means that OOtB calling isDebugEnabled returns immediately w/ false, w/o doing any checks. This may even be inlined by the compiler.
If someone decides to drop the slf4j-jdk14.jar (for example), then that means that someone already uses Java logging in other places in his/her application (not necessarily the search parts only) and therefore the overhead of checking whether logging is enabled is already been taken into consideration.
However, I don't think it's the Lucene's community's responsibility to take care of these situations, because like I wrote before, someone might extend SLF4J and provide a very inefficient isDebugEnabled() implementation, and it wouldn't (and shouldn't) be the community's responsibility.
What's important is that Lucene uses the NOP adapter, which really does nothing.
If you insist, I can run some performance tests, but I really don't think it's necessary.
Grant, given what I wrote below, having Lucene use NOP adapter, are you still worried w.r.t. the performance implications?
If there is a general reluctance to add a dependency on SLF4J, can we review the other options I suggested - using infoStream as a class with static methods? That at least will allow adding more prints from other classes, w/o changing their API.
I prefer SLF4J because IMO logging is important, but having infoStream as a service class is better than what exists today (and I don't believe someone can argue that calling a static method has any significant, if at all, performance implications).
If the committers want to drop that issue, please let me know and I'll close it. I don't like to nag
It seems we should take into consideration the performance of a real logger (not the NOP logger) because real applications that already use SLF4J can't use NOP adapter. Solr just switched to SLF4J for example.
Like I wrote before, I believe that if someone will use a real logger, it's most probably because his application already uses such a logger in other places of the code, not necessarily just the search parts. Therefore, the performance implications of using a logger is not important, IMO.
For the sake of argument, what if some writes his own adapter, which performs really bad on isDebugEnabled() (for example) - is that the concern of the Lucene community?
The way I view it - this patch gives those who want to control Lucene logging, better control of it. The fact that Lucene ships with the NOP adapter means it will not be affected by the logger's isDebugEnabled() calls. If you want to always output the log messages, drop an adapter which always returns true.
I wonder if there is a general reluctance to use SLF4J at all, and that's why you continue to raise the performance implications. Because I seriously don't understand why you think that checking if debug is enabled can pose any performance hit, even when used with a real logger.
If performance measurement is what's keeping this patch from being committed, I'll run one of the indexing algoirhtms w/ and w/o the patch. I'll use the NOP adapter and the Java logger adapter so we'll have 3 measurements.
However, if performance is not what's blocking that issue, please let me know now, so I won't spend test cycles for nothing.
And ... I also proposed another alternative, which is not as good as logging IMO, but still better than what we have today - offer an InfoStream class with static methods verbose() and message(). It can be used by all Lucene classes, w/o changing their API and thus allows adding more messages gradually w/o being concerned w/ API backward compatibility.
I prefer SLF4J, but if the committers are against it, then this one should be considered also.
Shai.
Because I seriously don't understand why you think that checking if debug is enabled can pose any performance hit, even when used with a real logger.).
I think using a logger to replace the infostream stuff is probably acceptable. What I personally don't want to see happen is instrumentation creep/bloat, where debugging statements slowly make their way all throughout Lucene.{bq}
Grant wrote a few posts back:
."
IMO, adding logging messages to outer classes, like QueryParser, is unnecessary since the application can achieve the same thing by itself (logging the input query text, used Analyzer and the output Query object). But logging internal places, like merging, is very important, because you usually can't reproduce it in your dev env. (it requires the exact settings to IndexWriter, the exact stream of documents and the exact operations (add/remove)).
Like I said, logging in Lucene is mostly important when you're trying to debug an application which is out of your hands. Customers are rarely willing to share their content. Also, community-wise, being able to ask someone to drop a log of operations that has happened and caused a certain problem is valuable. Today you can ask it only on IndexWriter output, which may not be enough.).{bq}
I'm sorry, but I don't buy this (or I'm still missing something). What's the difference between logger.isDebugEnabled to indexOutput.writeInt? Both are method calls on a different object. Why is the latter acceptable and the former not?
I'm not saying that we should drop any OO design and programming, but just pointing out that Lucene's code is already filled with many method calls on different objects, inside as well as outside of loops.
The only way I think you could claim the two are different is because indexOutput.writeInt is essential for Lucene's operation, while logger.isDebugEnabled is not. But I believe logging in Lucene is as much important (and valuable) as encoding its data structures.
I'm going to go out on a limb and say this one is too contentious to make 2.9.
If you strongly disagree, please do feel free to flip it back.
I'm not even sure if this issue should be kept around, given the responses I got to it. The question is - do we think logging should be improved in Lucene or not? If YES, then let's keep the issue around and come back in 3.0. If NO, then let's cancel it. It hasn't been commented on for ~6 months, so there's no point to keep it around unless we think it should be resolved at some point
So who is in favor of this? Personally, I'm not - Shai put up the call for support months ago - one more chance I guess - without, I will close this soon.
Well ... since Mark hasn't closed it yet (thanks Mark
), I thought to try once more. Perhaps w/ the merge of Lucene/Solr this will look more reasonable now? I personally feel that just setting InfoStream on IW is not enough. I don't think we need to control logging per level either. I think it's important to introduce this in at least one of the following modes:
- We add SLF4J and allow the application to control logging per package(s), but the logging level won't matter - as long as it's not OFF, we log.
- We add a static factory LuceneLogger or something, which turns logging on/off, in which case all components/packages either log or not.
I think (1) gives us greater flexibility (us as in the apps developers), but (2) is also acceptable. As long as we can introduce logging messages from more components w/o passing infoStream around ... On
LUCENE-2339 for example, a closeSafely method was added which suppresses IOExceptions that may be caused by io.close(). You cannot print the stacktrace because that would be unacceptable w/ products that are not allowed to print anything unless logging has been enabled, but on the other hand suppressing the exception is not good either ... in this case, a LuceneLogger could have helped because you could print the stacktrace if logging was enabled.
We use SLF4J in Jackrabbit, and having logs from the embedded Lucene index available through the same mechanism would be quite useful in some situations.
BTW, using isDebugEnabled() is often not necessary with SLF4J, see
I still think that calling isDebugEnabled is better, because the message formatting stuff may do unnecessary things like casting, autoboxing etc. IMO, if logging is enabled, evaluating it twice is not a big deal ... it's a simple check.
I'm glad someone here thinks logging will be useful though
. I wish there will be quorum here to proceed w/ that.
Note that I also offered to not create any dependency on SLF4J, but rather extract infoStream to a static InfoStream class, which will avoid passing it around everywhere, and give the flexibility to output stuff from other classes which don't have an infoStream at hand.
Closing this one as we clearly don't reach a consensus about it. And it introduces a static variable to each class that is interested in logging, which is a problem if Lucene is used inside the same JVM by several instances - turning the logging on for one application will affect all the rest as well.
Anyway, it's been open for too long and I don't see that we're anywhere near a consensus (perhaps rightfully), so no point keeping it open.
This patch covers:
Few notes:
Not sure how's that align with Lucene's back-compat policy, but on the other hand I didn't think I should keep both infoStream and SLF4J logging in the code.
1. The code uses isDebugEnabled everywhere, which is at least judging by the JDK14 adapter very fast (just checks a member on the actual logger instance) and is almost equivalent to infoStream != null check.
2. It really depends on the adapter that's being used. I used JDK14, but perhaps some other adapter will perform worse on these calls, although I expect these calls to be executed quickly, if not even being inlined by the compiler. | https://issues.apache.org/jira/browse/LUCENE-1482?focusedCommentId=12654875&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2016-07 | refinedweb | 2,426 | 60.85 |
Hi all,
This is the beginning of a hopefully useful project: to create a Canvas widget for wxPython that will mimic or improve on the Tkinter Canvas widget. Those of you who have coded with both will probably know what I'm talking about. With Tkinter, you can plop items like ovals, rectangles, etc. on the canvas and then keep track of them with id #s: check for collisions, move them, etc. With wxPython, you get a blank Panel. Yea.
So, here's the beginnings of an attempt to create a wxPython Canvas widget. The Canvas keeps a list of IDS of items and draws them as needed; that list contains direct references rather than ID #s.
If there are any structural problems or whatnot, let me know. Currently, the only thing you can create are ovals. But the output was so satisfying, I had to share... :)
Jeff
import wx class CanvasItem(object): """A virtual base class. All child classes need to define self.DrawMethod and set self.type""" def __init__(self, parent, bbox, pen, brush): self.parent = parent self.bbox = bbox self.pen = pen self.brush = brush def draw(self, DC): DC.SetPen(self.pen) DC.SetBrush(self.brush) self.DrawMethod(DC, self.bbox) class Oval(CanvasItem): def __init__(self, parent, bbox, pen, brush): CanvasItem.__init__(self, parent, bbox, pen, brush) def DrawMethod(self, dc, bbox): dc.DrawEllipse(bbox.x, bbox.y, bbox.width, bbox.height) class Canvas(wx.Panel): # Store IDS in order by leftmost edge for more efficient collision detections. def __init__(self, parent=None,id=wx.ID_ANY, pos = wx.DefaultPosition, size=wx.DefaultSize,style=wx.TAB_TRAVERSAL,name="panel"): wx.Panel.__init__(self,parent,id,pos,size,style,name) self.IDS = [] self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self,event): DC = wx.PaintDC(self) for ID in self.IDS: ID.draw(DC) def create_oval(self, x0,y0,x1,y1,outline="black", fill="", stipple="", width=1,style=wx.SOLID): print "Creating oval:", x0,y0,x1,y1,outline,fill,stipple,width,style pen = wx.Pen(outline.upper(),width,style) if not fill: fill = "BLACK" style=wx.TRANSPARENT elif stipple == "": fill = outline.upper() style = wx.SOLID else: fill = outline.upper() style = wx.CROSS_HATCH # need to fix this with bitmap stippling?! brush = wx.Brush(fill,style) self.IDS.append(Oval(self, wx.Rect(x0,y0,x1,y1), pen, brush)) app = wx.PySimpleApp(0) app.frame = wx.Frame(parent=None, id=-1, size=(300,400)) app.frame.canvas = Canvas(parent=app.frame) for i in range(10,300,10): app.frame.canvas.create_oval(10,10,i,i) app.frame.Show() app.MainLoop() | https://www.daniweb.com/programming/software-development/threads/111085/wxpython-canvas-widget-rfc | CC-MAIN-2017-13 | refinedweb | 431 | 54.9 |
.
Azure Data Lake Storage (ADLS)
Azure Data Lake Storage (ADLS) is an unlimited scale, HDFS (Hadoop)-based repository with user-based security and a hierarchical data store. Recently, Azure Blob Storage was updated to (among other things) increase capabilities in both scaling and security. Although these updates reduced the differential benefit between ADLS and Blob Storage, that didn’t last long. The improvements to Blob Storage are now the basis for updates to Azure Data Lake Storage. These updates are currently in preview as ADLS Generation 2 and build directly on the new improvements in Blob Storage.
ADLS Gen2 sits directly on top of Blob Storage, meaning your files are stored in Blob Storage and simultaneously available through ADLS. This enables access to all key Blob Storage functionality, including Azure AD based permissions, encryption at rest, data tiering, and lifecycle policies. You can access data stored in ADLS Gen2 via either ADLS (HDFS) or the Blob Storage APIs without moving the data.
Key offerings for Gen2 on top of Blob Storage’s capabilities are the Hadoop-compatible file system (HDFS), hierarchical namespace (folders/metadata), and high-performance access to the large volumes of data required for data analytics. With these updates, ADLS remains the best storage interface in Azure for services running large volume analytic workloads. ADLS makes this performance available to any service that can consume HDFS, including ADLA, Databricks, HD Insight, and more.
Azure Data Lake Analytics (ADLA)
Azure Data Lake Analytics (ADLA) is an on-demand analytics job service. The ADLA service enables
execution of analytics jobs at any scale as a Software as a Service (SaaS) offering, eliminating up-front investment in infrastructure or configuration. This analysis is performed using U-SQL, a language that combines the set based syntax of SQL and the power of C#. With no up-front investment and a language that a .NET Developer can easily work with ADLA simplifies startup on the analysis of the terabytes or petabytes of data resting in your Data Lake.
What’s U-SQL?
U-SQL is a new language that combines the set-based syntax and structures of SQL with the capability and extensibility of C#. However, U-SQL is not ANSI SQL, as the intended purpose of U-SQL goes beyond reading data from a traditional RDBMS. Additional capabilities are required to support actions that are normal for data analysis of large sets both unstructured and structured data, but not for standard SQL.
One example of this is that data in a data lake is often unstructured and likely in the raw format in which it was received. Working with this unstructured data requires defining structure for the data and also often introducing some transformations and enrichment. U-SQL provides a schema-on-read capability that provides structure to data as it is being read and used vs. applying structure to the data as it is received and stored. This unstructured or semi-structured data can then be combined with data in structured data stores like SQL to find answers to questions about your business.
We’ll dive deeply into U-SQL in the future. For now, we’ll take a quick look at a sample U-SQL script. The script below reads in data from a set of CSV log files, counts the number of actions per user, and writes out a CSV file with these results. Although this is a simple example it shows the basic concepts of a U-SQL script. A pattern of read (extract), act (select and transform), and output is one that is repeated again and again in U-SQL scripts, this pattern also maps easily to a typical ETL process.
// Read the user actions data @userActionsExtract = EXTRACT userName String, action String, date DateTime, fileDate DateTime FROM "/raw/userlog/user-actions-{fileDate:yyyy}-{fileDate:MM}-{fileDate:dd}.csv" USING Extractors.Csv(); // Count the actions for each user where the date in the file name is in July @totalUserActionCounts = SELECT userName, COUNT(action) AS actionCount FROM @userActionsExtract WHERE fileDate.Month == DateTime.Now.Month GROUP BY userName; // Write the aggregations to an output file OUTPUT ( SELECT * FROM @totalUserActionCounts ) TO "/processed/userlog/user-action-counts-2018-07.csv" USING Outputters.Csv();
Related Services
The Azure Data Lake services are only part of a solution for large-scale data collection, storage, and analysis. Here are three questions you might ask about solving these problems. Answers to these questions offer a starting point for further exploration into your data analytics pipelines.
How do you get data into the data lake?
In Azure, the most prominent tool for moving data is Azure Data Factory (ADF). ADF is designed to
move large volumes of data from one location to another making it a key component in your effort to collect data into your Data Lake. V2 of Azure Data Factory was recently released. V2 provides an improved UI, trigger-based execution, and Git integration for building data movement pipelines. Another key addition is support for SSIS package execution so you can reuse existing investments in data movement and transformation.
How do you perform batch analysis of data in the data lake?
In addition to ADLS, there are other analysis services that are directly applicable to the large-scale batch analysis of unstructured data that resides in your data lake. Two of these services available on Azure are HDInsight and Databricks. Using these other services may make sense if you are already familiar with them and/or they are already part of your analytics platform in Azure. Databricks provides an Apache Spark SaaS offering that allows you to collaborate and run analytics processes on demand. HDInsight provides a greater range of analytics engines including HBase, Spark, Hive, and Kafka. However, HDInsight is provided as a PaaS offering and therefore requires more management and setup.
How do you report on data in the data lake?
Azure Data Lake and the related tools mentioned above provide the ability to analyze your data but are not the generally the right source for reports and dashboards. Once you’ve analyzed your data and identified measures and metrics you might want to see in dashboards and reports, you’ll need to do some additional work. Ideally, data for dashboards and reports will be structured and stored in a service designed to be queried regularly and update the report or dashboard data. The right place for this data will be a destination like SQL Azure, a SQL Azure Data Warehouse, Cosmos DB or your existing BI platform. This is another stage where Azure Data Factory will be key, as it can orchestrate the process to read data, schedule execution of analysis (if needed), structure data, and write the resulting data to your Reporting data store.
Contextual Overview Diagram
For More Information
- Azure Data Lake Storage (ADLS)
- Azure Data Lake Storage Generation 2 (ADLS Gen 2)
- Azure Data Lake Analytics (ADLA)
- Azure Data Factory (ADF)
- Getting Started With U-SQL | https://www.ais.com/an-introduction-to-azure-data-lake/ | CC-MAIN-2021-31 | refinedweb | 1,158 | 51.89 |
Automated Airflow Testing
Introduction to Airflow
Airflow is an Apache project for scheduling and monitoring work flows. The project has excellent documentation here, but while working in Airflow I have come across some topics that were harder to find resources on. Unit testing Airflow code was a topic where many struggle to find valuable information online. I’ll show some code basics for local automated testing!
Simple Airflow Setup
Before we can test Airflow DAGs we need a place for code to run. Most organizations will have Dev & Production environments, but it is still important to run code locally to check for errors before deploying to either of those environments. This avoids cluttering the Airflow WebUI with error messages from test code. Containers are a great way to quickly stand up a local copy of Airflow for testing purposes. This is a fantastic Github page with instructions on how to get a basic Airflow server running.
Pulling and using this image requires Docker, so start there if you are unfamiliar. Now with a local container available we can write some automated tests to make sure our DAGs in development meet some basic standards.
Local Automated Airflow Testing
The below code builds a container based on the puckel image mentioned earlier, copies all our local development dags and tests into the container, and runs the container on local port 8080. This allows us to access the web UI from the address localhost:8080.
def airflow_build(dag_path, test_path):
"""
This function runs the build for a container with airflow processes locally. Turns on webserver and scheduler.
:param dag_path: (string) the filepath where dags live locally.
:param test_path: (string) the filepath where the pytest script lives locally.
:return: returns the docker container object.
"""
client = docker.from_env()
client.images.pull("name_of_airflow_image")
running_container = client.containers.run(
"name_of_airflow_image",
detach=True,
ports={"8080/tcp": 8080}, # expose local port 8080 to container
volumes={
dag_path: {"bind": "/usr/local/airflow/dags/", "mode": "rw"},
test_path: {"bind": "/usr/local/airflow/test/", "mode": "rw"},
},
)
running_container.exec_run(
"airflow initdb", detach=True
) # docker execute command to initialize the airflow db
running_container.exec_run(
"airflow scheduler", detach=True
) # docker execute command to start airflow scheduler
return running_container
Here are some simple tests to run against DAGs:
Were there any import errors?
The webUI will not load any DAGS that contain syntax type errors and will flag them at the top of the console.
Does our DAG have a valid email provided in the `default_args`?
This could be changed if there is a specific alerting address all DAGs should send to. These tests will be included on the container as our pytest script (I named this dag_pytest.py).
Additional tests can be added based on project needs!
Shown below is the dag_pytest.py script:
def test_import_dags():
"""
Pytest to ensure there will be no import errors in dagbag. These are generally syntax problems.
"""
dags = DagBag()
assert len(dags.import_errors) == 0
def test_alert_email_present():
"""
Pytest to ensure all dags have a valid email address
"""
dags = DagBag()
r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$"
) # regex to check for valid email
for dag_id, dag in dags.dags.items():
for email in emails:
assert email_regex.match(email) is not None
The final step is to have a python script that starts a container, runs the pytests against our DAG files, and returns a status of those tests.
def test_run_dag_test_script():
"""
This function runs a docker exec command on the container and will run our airflow DAG testing script. Once the test is complete return the exit status and output messsage from the docker execute command. Then the function stops the container.
:return: the exit status and output message from the docker exec command of test script.
"""
dags = "/file/path/to/DAGS"
test_script = "/file/path/to/test/script"
running_container = airflow_build(
dag_path=dags, test_path=test_script
)
dag_test_output = running_container.exec_run(
"pytest /usr/local/airflow/test/test_dag_pytest.py"
)
ex_code = dag_test_output[0]
running_container.stop()
assert ex_code == 0
Now, the above can be run just like any other pytest script!
Conclusion
Airflow is a powerful, open source scheduling system. Basic setup is fairly straight-forward and building jobs is as easy as writing python. Local container generation for testing adds a layer of code development best practice to DAGs. There are a whole host of tests that can be instituted in this framework and should be based on project needs. Once these tests are developed, your project members can implement this system locally and standardize DAG quality across your project! | https://medium.com/slalom-technology/automated-airflow-testing-a29b6426148b?source=collection_home---2------3--------------------- | CC-MAIN-2019-22 | refinedweb | 744 | 57.06 |
Hi Readers, In this post, we are going to write a core Java Program to Print Odd Numbers within a given limit.
First of all, you should know how to find an Odd Number and it is pretty simple, divide any number by 2 if the remainder is not zero then it’s an Odd number.
So let’s see the complete Java Program here:
/** * * @author agur */ import java.util.Scanner; public class PrintOdd { public static void main(String[] args){ int limit, i; //create a scanner object to get the input Scanner in = new Scanner(System.in); //get the limit from user System.out.print("Enter the limit:"); limit = in.nextInt(); //print the odd numbers System.out.println("Odd numbers:"); //loop till the limit for(i=1; i
Read the inline comments to understand the logic.
The output of the above program:Enter the limit:10 Odd numbers: 1 3 5 7 9 BUILD SUCCESSFUL (total time: 2 seconds)
ENJOY LEARNING!
The post Java Program to print Odd Numbers! appeared first on TutorialsMade.
This post first appeared on TutorialsMade - Ultimate Tutorial, please read the originial post: here | https://www.blogarama.com/programming-blogs/290840-tutorialsmade-ultimate-tutorial-blog/29890194-java-program-print-odd-numbers | CC-MAIN-2021-04 | refinedweb | 187 | 65.62 |
i need some help how to use my email client or the webpage when opend as my desired email address login for example, gmail.coma and whn im logged in as a member, i need help sending commans just liek you would do in MIRC to teh server.exe in pure c++
these are the main commands i want. SCREEN CAPTURE OR VIDEOS OF DESKTOP of remote machine via FTP or attatchments, ways to send the beep function command. Ways to blobkuserinput. swapmousebutton and open cd rom. Keylogger aswell. so that it emails me the keylogs. I want to integrate a filter so it filters the sutes iu i want for example, ypoutube.com, gmail.com, yahoo.com, roitab.com, yahoo.com, grooveyweb.com and so on. So not just random keys pressed on the keyboard..
i tried using getakeysyncstate or whatever. But somehow my AV detecting it. THAT SUCKS SIO I WANT ANOTHER WAY PLZ...so basically i just want a server on teh victims pc. and the client as the email tool or webpage and send the commands in teh body of teh message.
for example for blockinput(true); i would send in teh body of message( BI) stands for blockinput. That will send teh server machineteh command and itr will perform that action. I just need to know what code the server will have and what libraries should i put windows.h, iostream.h winable.h , winsock.h and what elesE?
thsi is my code for now......basic:
#include <windows.h> #include <winsock.h> #include <iostream.h> #include <winable.H> using namespace std; int main() { FreeConsole(); BlockInput(true); Sleep(8000); BlockInput(false); SwapMouseButton(true); Sleep(430); SwapMouseButton(false); beep(4300,30); SendMessage(HWND_BROADCAST, WM_SYSCOMAND, SC_MONITORPOWER(lparam) 2); Sleep(4000); SendMessage(HWND_BROADCAST, WM_SYSCOMAND, SC_MONITORPOWER(lparam) -1); Sleep(2000); SendMessage(HWND_BROADCAST, WM_SYSCOMAND, SC_MONITORPOWER(lparam) 1); return(0); }-------------please help me i need to somehow reciev connection from email client and make it accept NO REVERSE CONNECTION PLZ... i also want it to inform me that ip and port iof teh computer so in teh TO box i type the ip or somehow convert it into a hostname and port binded with it so it doesnt mess anything up. See, just liek a hostname. The port is binded with the ip address or the hostname. I want to use gmail only you guys can state yahoo. tyoo....its just that i have a gmail account only so yeah i know that gmail does not use the filter etc... HOT MAIL IS CRAP SOO BNO WAY TOOO MUCH SECURITY LOL
thanks in advance Raghav Sood :_ | http://www.rohitab.com/discuss/user/30498-veer/?tab=topics | CC-MAIN-2022-21 | refinedweb | 435 | 75.4 |
Funding your startup
You're going to need some capital to get your business off the ground. Here are the top options for financing your business idea
Once you've got a great business idea and you've written out a plan, you're going to need some funds to get started. How much you need will depend on the type of business you're launching.
Fortunately, there are a lot of different funding options to help you build your empire. But first things first: let's figure out how much capital you'll need to get yourself started.
Figuring out how much capital you need
As we mentioned before, the amount of capital you need is going to depend on the type of business you're launching. Regardless of your business, though, your startup costs are going to fall into three main categories.
Business expenses
Your business expenses are your costs you'll incur to operate your business. To start your business, this could include things like marketing materials, legal fees, any fees involved in registering your business (the average cost in the US is $800–1,000 USD), website costs, salaries and office rent. The good news is these expenses are tax deductible. The bad news is you'll still need a chunk of change to get started.
Business assets
Your business assets are going to cost you money as well, but they're tangible items of value that your business owns. This could include inventory, office furniture, equipment and vehicles.
Cash reserve
Cash technically falls under business assets, but it's important to spend some time on this subject. It's crucial to figure out how much cash you'll need on hand.
Your cash on hand, or cash reserve, is money you actually have sitting in your bank account. Its purpose is to help see your business through tough times.
Figuring out your cash reserve is pretty simple. Just look at your projected monthly expenditures and multiply this by the number of months you want to have cash in reserve for. In other words, in the worst case scenario that your business goes through a period of no revenue, how many months' cushion do you want?
Most experts recommend a cash reserve of between three and six months' expenditure. It can be tempting to keep a large cash reserve, but just remember that every dollar you tie up in cash is a dollar you can't use to grow and expand your business. You need to find a figure that strikes a balance between providing security and giving you room to invest in your business.
Once you've figured out your startup expenses, startup assets and cash reserve, add these figures together and you've got the amount you'll need in startup capital. Go ahead and add 10% to this figure to give yourself a bit of a cushion in the very likely event that some costs are more than anticipated.
What you'll need to get started
Now that you have a good idea of how much capital you'll need, you're probably eager to start raising money. But before you jump into securing that sweet, sweet cash, there are a couple other details to get in order. After all, anyone investing in your business is going to want to know that you have a well thought out plan.
Business plan
Hopefully you read our previous chapter on how to write a business plan. If you didn't, though, here's a brief summary of what a business plan entails:
Value proposition: This is a summary of the solution you're providing to customers, and what makes your solution unique.
Market research: Your market research should detail demand for your solution and your ideal customer demographic. It should identify the market you'll be operating in and the opportunities in that market.
Funding: This is a summary of the funds you'll require to get started and how you plan to use those funds.
Milestones: This identifies the major milestones your business plans on hitting, and an estimate of when you'll hit them.
Resourcing: Your human resourcing should identify what roles you need to fill and profiles of the sort of staff you'll need.
This is just a synopsis, and your business plan should go into detail on each of these points. If you haven't read our chapter on writing a business plan, you should really go back and read it now.
5-year financial projections
Any investors you approach are going to want to see financial projections for at least the first three years of your business, and some may want to see up to five years. You should break your projections down month-by-month for the first year and then by quarter for the following years.
Your financial projection will take into account your expected sales minus your expenses. Be sure to be specific, showing how you're pricing your product or service, the number of sales you're projecting for each month or quarter and itemizing your expenses in detail.
Creating financial projections for a company that hasn't even launched can be tricky. This is where some in-depth research is required. You need to examine the industry you'll be working in and determine demand based on competitors. It could be a good idea to get the advice of an accountant who's worked in your industry.
Your projections shouldn't be unrealistic, but they also shouldn't be overly conservative. Remember you're trying to attract investors. You want to present them with an attractive projection.
Once you have a detailed business plan and financial projections, you can start approaching investors. But what kind of investors should you approach, and do you even need outside investment? Here are your options:
Put your own skin in the game
What it means
If you're in a position to finance your own business venture, that's fantastic. It's an uncommon position to be in (unless you keep your operation lean, which we totally recommend and will address later). But even if you can't entirely finance your startup on your own, you should still put some of your own money into it. It sends a signal to investors that you believe in your idea enough to back it yourself.
How to do it
You can use cash if you actually have enough on hand to finance your business. Once again, if you keep your operation lean it won't take much cash to get yourself up and running.
If you do require more cash, you could consider selling items you don't need, or even getting a second mortgage on your house. It's risky, we know. But starting a business requires a certain tolerance for risk.
Pros and cons
Pros
You won't be indebted to anyone
You won't need to worry about finding investors
Cons
If you need a significant amount of startup capital, you might not have enough funds on your own
Using your own funds is high risk
Get a bank loan
What it means
Banks offer a variety of loans that could help you get your business running. This could be a personal loan, which is money lent to you rather than your business. It can either be secured by some sort of asset, or unsecured. The difference is that a secured loan gives the bank recourse to take possession of the asset in the event you default on the loan.
You could also get a line of credit. This is a fixed credit amount you can draw from. You'll only be charged interest on the amount of credit you use, but a bank can require full repayment of a line of credit at any time.
If you're in the United States, many banks offer SBA loans. These are loans backed by the Small Business Administration. This makes it possible for businesses without a lot of collateral to get financing. They're easier to qualify for because they're lower risk to the bank, as the SBA guarantees up to 85% of the loan.
Finally, one of the most common types of business loans is a business term loan. These offer you a set amount of capital paid off over a fixed timeframe.
How to do it
Bank small business loans aren't easy to qualify for. It's an attractive form of financing, generally with low interest rates. As such, banks are picky about the businesses they lend to.
To put yourself in the best position, you'll need a good personal credit score. For Americans, this means a FICO of 700 or above. You'll need to demonstrate to the bank that your personal financial position is sound, and that you can meet your obligations without siphoning off of your business.
Banks will also want to see a detailed business plan and a full financial projection. You'll need to provide your personal tax returns, and you'll need to tell the bank exactly what the loan will be used for.
We're not going to sugarcoat it: startups, particularly in the United States, face an uphill battle getting bank small business loans. Some countries, such as Canada, have banks that are friendlier to startups. But most American banks want a business to have existed for at least six months and be bringing in at least $100,000 in annual revenue before approving a business loan.
An SBA loan is the best bet for a startup seeking bank funding. There are a few different types of SBA loans. The SBA 7a loan is the most common type of SBA loan. This provides funds up to $5 million USD. If you're a startup, your best bet of qualifying for an SBA 7a is to have a proven business model that the bank sees as low risk (such as a franchise).
One of the better SBA loans for startups is the SBA Express loan. This loan caters to startups needing a smaller amount of capital, with loan amounts up to $350,000 USD. This loan is typically easier to qualify for since the maximum lending amount is so much smaller.
Express loans are also quicker than SBA 7a loans. While an SBA 7a loan can take weeks or months to process, an SBA Express loan is approved or declined within 36 hours, and funds are typically available within 90 days.
If you do go for an SBA loan, you'll need to have a sizeable down payment. Lenders typically require a 25–30% down payment on SBA loans, so you'll either need to come up with that amount yourself or secure it from other investors.
Best banks for small business loans
If you're a startup, you'll definitely want to head to a bank that offers SBA loans. The Small Business Administration publishes a list of the most active SBA 7a lenders in the country, and the top five banks for SBA lending are:
Live Oak Banking Company
Wells Fargo
The Huntington National Bank
Newtek Small Business Finance
Byline Bank
Of these, Huntington National was the only one we could definitively identify as participating in the SBA Express program. However, some other lenders that offer SBA Express loans include:
Citizens Bank
TD Bank
Timberland Bank
Pros and cons
Pros
Long loan terms
Low interest rate
Low monthly repayment
Cons
Difficult to qualify for
SBA loans require a large down payment
Other loans require a business to have operated for at least six months
Get a grant
What it means
A grant is any sort of gift or subsidy bestowed upon an individual or organization for a specific purpose. Grant funds don't have to be repaid.
How to do it
There are a plethora of grants available for starting a business, but that doesn't mean there are piles of money lying around for the taking. Competition for grants is fierce, so you have to make a very good case for your business.
The first step in securing grant funds is researching the grants available and determining which ones are the best fit for your business. Grants are for specific purposes, and most have very specific focuses such as helping businesses doing research and development, funding businesses that will export goods or aiding women and minorities looking to start businesses.
If you find a grant that looks like a good match for your business, you'll need to go through the application process. Each grant will have its own application process and criteria, but you'll generally need to write a grant proposal.
Grant proposals will differ based on the submission requirements for each grant. Some organizations may require a full grant proposal, which can be around 25 pages long and detail your project, the funds you'll require and what they'll be used for. There are freelance writers who specialize in writing grant proposals, and if the grant you apply for requires a full proposal we strongly suggest utilizing this service.
Some grants may only require a Letter of Inquiry (LOI). An LOI is often the first step of the grant application process, and allows an organization to see if you're a good fit for their grant funds. This is basically your elevator pitch: a short, punchy description of what you're trying to accomplish, what you need and how you'll use the grant funds.
Some other grants may ask for a letter proposal. This is a bit longer, generally a few pages, and once again describes your project, the funds you need and how they'll be used. While you may be able to craft a winning LOI on your own, we'd also highly recommend a grant writing specialist for grants requiring a letter proposal.
Federal, state and local small business grants
The US Small Business Administration funds a few grants that can help get your startup off the ground, depending on your focus.
If you're looking to produce or sell a product and are open to targeting overseas markets, the SBA's State Trade Expansion Program (STEP) could be a good fit. The STEP grant goes directly to state agencies to support export development and increase the number of US small business exporters.
The Small Business Innovation Research (SBIR) grant helps fund startups in the tech field that are focused on research and development. If your startup is focused on R&D and tech, this grant could be a good fit.
If the tech you're developing could have nonprofit applications, look into the Small Business Technology Transfer (STTR) grant. It requires small businesses to collaborate with a research institution such as a nonprofit, a university or a federal R&D department.
In addition to federal grants, many individual states and even local governments also offer grants to small business. Do some research into the grants offered in your state and city to see if your business idea qualifies.
Small business grants for women
The Amber Grant awards a different female entrepreneur $2,000 USD each month, with an annual prize of an additional $25,000 USD for one of the year's 12 winners. There's a $15 application fee, but the application process is quick and straightforward. Both US and Canadian businesses are eligible.
The Girlboss Foundation awards a bi-annual grant of $15,000 USD to female entrepreneurs. Not only do winners get funds, they also get great exposure for their businesses on the Girlboss platform.
Small business grants for minorities
The Minority Business Development Agency posts regular updates on grant opportunities for minority business owners. You can find open grant competitions on the MBDA website.
Small business grants from corporates
Here's a bit of inspiration for you: every Fortune 500 company was once a startup, just like you. Fortunately, a few of them remember this and look to give a leg up to entrepreneurs.
There are a number of different corporates offering small business grants, but a couple are particularly good fits for startups.
The Visa Everywhere Initiative focuses on entrepreneurs working on payment platform solutions. It awards $50,000 to the top three submissions each year.
The FedEx Small Business Grant Contest divides $25,000 between 10 winners each year. The application requires a brief description of your entrepreneurial story and business idea, as well as a one-minute video pitching your business.
Small business grant for veterans
The StreetShares Foundation offers an annual grant of $25,000 split between four winners. Applicants must be a veteran, reserve or active duty transitioning military member or spouse. Entry is simple, and requires filling out an online form and creating a two-minute pitch video.
Pros and cons
Pros
Funds don't have to be repaid
Cons
Competition for grants is fierce
Application process can be time consuming
Approval timeframes can be long
Get a P2P loan
What it means
Peer-to-peer (P2P) lenders match borrowers with individuals or groups of individuals with money to lend. It's a similar concept to crowdfunding, but with more sophisticated mechanisms in place to appropriately price for risk and return. Investors in P2P lenders can choose to invest small or large amounts, pick their risk appetite and then their money will be pooled with similar investors and matched with people seeking loans that fit their profile.
How to do it
P2P finance is much easier to qualify for than traditional bank financing, because P2P lenders can match your business to investors with a higher risk appetite. However, most P2P small business loans require you to have been in business for at least a year.
This doesn't mean you can't get a P2P loan as a startup. It just means you'll have to qualify on your personal finances rather than the strength of your business plan. P2P lenders will typically consider borrowers with lower credit scores, though most will want a FICO of at least 600.
The application process for most P2P lenders is straightforward, and can be done online. Because a lot of P2P lenders have positioned themselves as fintechs (financial technology companies), they have fast approval processes that rely on algorithms rather than humans with a calculator and a rubber stamp.
To get a P2P loan for your business, you'll need to pull together your personal financial information, including your tax returns, pay stubs and bank statements. Just be aware that the amount of funds you'll be able to access with a personal loan will be lower than a business loan (typically up to $50,000 USD).
Best P2P lenders for small business
While there are plenty of great P2P lenders offering personal loans, Upstart stands out to us. They take a more holistic view of their borrowers, looking not just at financial history but at education, work history and area of study. You'll need a minimum FICO of 620, but you can borrow up to $50,000 USD for a three- to five-year loan term.
Pros and cons
Pros
Easier to qualify for than bank loans
Low interest rates
Simple application process
Fast approval and funding times
Cons
Lower maximum loan amounts than bank loans
Business loans only available to established businesses
Approval will depend on your personal finances rather than the strength of your business plan
Use a credit card
What it means
If you don't have cash on hand and don't want to worry about raising money from investors, you can use a personal credit card to finance your startup costs.
How to do it
This one is a bit of a no-brainer. You just put any startup costs on your personal credit card. Be sure to go through your statements carefully and itemize any business expenses so you can deduct them on your taxes. You should also think about choosing a credit card with a 0% introductory APR so you don't accrue interest during your first year of operation. Rewards points can also be helpful for your business, as you could use them for future expenses like business travel.
Depending on your personal credit, you could also qualify for a business credit card even if you're still in startup phase and haven't earned any revenue. Business cards are a better option for most startups than a personal card, as they make it easier to separate business and personal expenses. Plus, missed payments on some small business cards won't affect your personal credit score.
Best credit cards for small business
The best card for your small business will depend on your personal financial circumstances and credit history, but we think the American Express Blue Business Plus is worth a look. AMEX will consider your application even if you haven't earned any revenue yet, and the card has no annual fee. You'll also earn double rewards points for every $1 spent up to $50,000 per year, and one point for every dollar thereafter.
Pros and cons
Pros
Don't have to seek funding
Don't have to have large amounts of cash on hand
Keep equity in your business
Potentially earn rewards points
Cons
High interest rate (after introductory period)
Low maximum amount versus some other sources of capital
Missed payments could ruin your personal credit
Seek out angel investors
What it means
Angel investors are high net worth individuals who invest money in business ventures. They can invest on their own or pool their money with other angel investors. They invest in return for equity in the business or convertible debt, which is debt that can be converted into shares in the company.
Angel investors are a popular source of financing for startups, since they focus on the strength of the individual entrepreneur and business plan rather than personal credit history. Angel investments on average range from $25,000 USD to $100,000 USD.
How to do it
Angel investors are taking a high risk investing in your business, so they need to be ensured that it's a good risk to take. That means they'll want to see drive, motivation, persistence and intelligence from you as an individual, and a solid plan for your business.
While your business plan will be crucial in securing angel investors, they're also busy people, which means you need to work on your elevator pitch. Work on condensing your business plan to a brief presentation that communicates your value proposition, the demand for your product or service and your growth strategy. You should also consider making a slide deck to go along with your elevator pitch.
Because they're taking a big risk, angel investors also expect a big return (in the neighborhood of 20–30%), so demonstrate how their investment will generate that return. You also need to present a sound exit strategy.
Pros and cons
Pros
Potential for large amounts of capital
Focus on character of entrepreneur and solidity of business plan rather than credit history
Cons
You'll be giving up equity in your business
Competition for angel investment funds is fierce
Angel investors expect a high rate of return
Pitch to venture capitalists
What it means
Venture capitalists represent groups of investors who pool their money to purchase equity in new business ventures. They differ from angel investors in that angel investors are investing their own personal funds, whereas venture capital firms represent investors.
Venture capitalists also typically invest larger amounts than angel investors. As we mentioned before, an individual angel investor may invest $25,000 USD to $100,000 USD, while the average venture capital investment is $7 million USD.
Venture capitalists are also generally more involved than angel investors. An angel investor may offer help and support to an entrepreneur, but this depends on the entrepreneur's and angel investor's own preferences. Venture capitalists, however, are actively involved in providing guidance, advice and support to the startups they fund.
How to do it
It's tough to get the attention of a venture capital firm. VCs are flooded with funding requests from startups, so they have to be picky about the ones they pursue.
VCs tend to focus on tech-based startups, and particularly startups developing software as a service (SaaS) products. They're also attracted to past success, so they lean towards successful serial entrepreneurs.
One of the most difficult parts of securing venture capital is to get on a VC's radar to begin with. The best way to do this is through a personal introduction by a trusted mutual associate.
If you're lucky enough to get the attention of a VC, you'll need a good elevator pitch and a well-crafted business plan. If they like what they see, you'll work with them (and lawyers) to craft a term sheet. This sets out the terms of the VC's investment. It basically entails what they expect to receive in return for their money.
A term sheet will likely include details like the way the VC's equity stake will be structured, their rights to control of the company via seats on the board of directors, their rights to participating in future funding rounds, the valuation of the company and what happens upon sale or liquidation of the company.
Pros and cons
Pros
Large amounts of capital
Guidance and support for growing your business
Cons
Gives up equity in your business
Relinquishes control of some parts of your business
Very difficult to secure
Crowdfund your idea
What it means
Crowdfunding is raising funds from a large group of people, usually using an online platform. It relies on securing small amounts from a large number of individuals.
There are a couple different types of crowdfunding, and each comes with its own challenges. First, there's donation and reward crowdfunding. This practice lays out your entrepreneurial vision and asks people to donate to help you achieve it. At certain levels of donation, rewards are offered. This could be the product you're developing or access to the service you're selling.
The second type of crowdfunding is investment crowdfunding. In this method, you're offering people an equity stake in your business proportionate to their investment, or a share of the revenue.
How to do it
There are a number of online platforms for crowdfunding. It's important, though, to be clear about the challenges involved.
Donation and reward crowdfunding is usually a make or break scenario. Your crowdfunding campaign has a certain goal, and if you don't hit it you don't end up with any funds. It's a risky venture.
Another challenge presented by donation and reward crowdfunding is fulfilling all the orders if you do hit your goal. If you're using the funds to develop a product and offering that product as a reward, you need to be certain you can deliver the product to participants in a reasonable timeframe, and that the product delivers on what you promised.
Investment crowdfunding presents its own legal challenges. Because you're offering people equity in your business, you'll have to fill out some paperwork. You'll file what's known as a Form C, which is required of any company raising capital through equity crowdfunding. Depending on the platform you choose, investment crowdfunding can also be a binary outcome. Either you hit your goal and receive funding, or you miss your goal and receive nothing.
Crowdfunding platform comparison
Kickstarter
Kickstarter focuses specifically on creative projects. That could be an artistic project, a fashion product, a new piece of technology or any other creative pursuit. It's an all-or-nothing model, meaning you have to hit your goal to see any funds. The platform doesn't allow offers of equity or revenue sharing.
Indiegogo
Indiegogo offers a more flexible model than Kickstarter, with the ability to raise funds through either a donation and rewards model or an equity model. The platform also offers prototyping, manufacturing and fulfillment support.
Crowdfunder
Crowdfunder is an equity crowdfunding platform linking VCs with entrepreneurs. To participate, your idea should already have gotten some early traction with customers, other investors or entrepreneurship programs like startup incubators. You'll also need a term sheet, an executive summary and an investor pitch deck. Only Accredited Investors are allowed to invest via Crowdfunder, so the platform is only suited to startups that are beyond the inception phase.
SeedInvest
SeedInvest is a platform linking crowd investors with startups. Depending on the model you choose, you can raise anywhere from $250,000 to $50 million USD. SeedInvest requires entrepreneurs to apply to be included on the platform. It will pay certain upfront costs, and only makes money if your equity raising campaign is successful.
Pros and cons
Pros
Provides easy access to willing investors
Some platforms help manage payments from investors
Some platforms help with marketing, manufacturing and fulfillment
Cons
Some platforms are an all-or-nothing funding model
Some platforms are geared towards more mature startups
Turn to friends and family
What it means
Pitch your vision to people you already know to raise capital for your business. You can offer them an equity stake in return for their investment.
How to do it
They're your friends and family. You'd know better than us.
In all seriousness, though, you should focus on having a professional pitch. Don't just count on drawing investment from your friends and family based on your relationship alone. Show them that your business is a sound investment that can generate a return for them. You're not looking for a handout. You're offering an opportunity.
A well-crafted business plan is just as important when raising funds from friends and family as it is when raising capital from banks or venture capitalists. It demonstrates that you have a solid strategy and have properly crunched the numbers on the return you expect your business to generate. Asking friends and family to open their wallets can be an awkward endeavor. A quality business plan serves as a shield to that awkwardness.
Only you can gauge whether or not it's wise to pursue funding from your social circle. A lot of this decision will come down to your history with them and their individual temperaments. If you've inundated your social circle with requests for money in the past, you may already have burned those bridges, regardless of the strength of your business plan. But if you've built a reputation of trustworthiness and responsibility, your friends and family may be eager to invest in your future, regardless of the return it generates for them.
Pros and cons
Pros
Friends and family already know you
Cons
Friends and family already know you (gulp!)
Draw on your retirement
What it means
If you're in the US, you can actually use your 401(k) to start a business. There are several ways to do this, but the best fit for startups is known as ROBS, or Rollover for Business Startups. This allows you to draw out your 401(k) or IRA funds to finance your business venture. Unlike other 401(k) options, there are no penalties or taxes on the withdrawal, and you don't have to repay the funds.
How to do it
You'll need at least $50,000 in a 401(k) or IRA to use this option (Roth IRAs aren't eligible). You'll have to set your business up as a C-corp, which we'll discuss further in our chapter on structuring your business. To qualify you'll also need to be employed full-time in your business. You'll also need to find a provider who offers ROBS. One further stipulation is that your business will have to offer retirement plans to eligible employees.
If you're short of the $50,000 USD required, you can use your 401(k) or IRA as a savings account to save up funds for starting your business. It might mean delaying your startup for a few years, but it means your savings will be tax deductible.
Pros and cons
Pros
No repayment required
Not based on credit history
Not based on strength of business plan
Cons
Need at least $50,000 USD in a retirement fund
Limits your options for structuring your business
PayPal
What it means
PayPal Working Capital is a program that allows PayPal merchants to get a cash advance based on their total sales. It's interest-free, but does come with a one-time fee. You make minimum repayments every 90 days, and you can repay the entire cash advance at any time.
How to do it
This one only applies if you've got a history of accepting payments through PayPal, so it might not help get your business off the ground. It can help you launch a new product or a new business venture, but only if you have previous sales through PayPal.
PayPal Working Capital provides a cash advance of up to 35% of your annual PayPal sales. It's based on these sales rather than your credit history. There's no interest on the cash advance. Instead you pay a percentage of each PayPal sale until the cash advance is repaid. There's also a fee based on your sales history, the repayment percentage you choose and the cash advance amount.
You can apply online through PayPal. The application takes about five minutes and you can receive your cash advance immediately. The maximum cash advance amount is around $187,000 USD.
Pros and cons
Pros
No interest charges
Easy application
Doesn't rely on credit history
Fast funding
Cons
Requires previous PayPal sales history
Maximum borrowing amount is 35% of annual PayPal sales
Microloans
What it means
Microloans are small amount loans specifically for small businesses. While microloans started as a way to encourage entrepreneurship in impoverished countries, they're now available to a wide range of entrepreneurs who need smaller amounts of capital.
Microloans typically have low interest rates and long loan terms of up to six years. The maximum amount you can borrow is usually around $50,000 USD, but the average microloan is more in the neighborhood of $10,000 USD, and you can borrow as little as $500 USD.
How to do it
Microloans are a great option for startup businesses because they're easier to qualify for than other forms of finance. If you keep your startup costs low, which we recommend, a microloan should cover your expenses.
Every microlender will have different criteria, so compare a few. Regardless of the lender you choose, however, you'll need a detailed business plan and financial projections. The good news is that these loans focus less on your personal credit and finances, and more on the strength of your business plan.
Microlenders are nonprofits, and particularly focus on providing startup capital to women, minorities or people launching businesses in impoverished areas. They take an active interest in helping borrowers, and provide pro-bono counseling and support to help develop your business plan.
Pros and cons
Pros
Long loan terms
Low interest rates
Support for developing your business plan
Cons
Lower loan amounts
As nonprofits, microlenders are typically limited in the number of loans they can fund per year
Microlenders are mission-oriented, so if your business model doesn't fit their mission you might not be eligible
Inventory and invoice finance
What it means
This is a type of finance, also called asset finance, that uses sales or stock to secure funding.
Inventory financing uses physical inventory as collateral to establish a revolving line of credit. You can draw on this line of credit as needed, and you're only charged interest on the amount you use.
Invoice financing, also called receivables financing or factoring, sells your outstanding invoices to a third party at a discounted rate. The finance company then takes on the responsibility and risk for collecting on your outstanding invoices.
How to do it
Your eligibility for either of these forms of finance will depend on your type of business. To apply for inventory financing, you'll need to be selling tangible products and have a decent sized inventory of them.
Invoice financing works well for businesses selling a service rather than a product. For invoice financing, you'll need to already have customers, and those customers will need to have outstanding debts.
There are finance companies that specialize in inventory and invoice financing. If you decide to go with this form of financing, make sure you compare their terms.
Pros and cons
Pros
Inventory financing provides working capital if your money is tied up in large amounts of inventory
Invoice financing offloads your risk and responsibility for collecting on debt
Cons
Inventory financing comes with high costs as it requires an appraisal of inventory
Inventory is often appraised at a lower price than you paid suppliers
Invoice financing means you'll forfeit some of the value of your accounts receivable
Pre-sell a proof of concept
What it means
If you're offering a product, particularly a software product, you can raise money through pre-sales. Then you can use this money to develop the product for wide release. This differs from crowdfunding because you're offering a one-to-one exchange of goods instead of allowing people to contribute the amount they want, and you're not required to hit a specific funding goal before receiving funds.
How to do it
Take this route with extreme trepidation. If you're going to pre-sell a product that doesn't exist yet, you better over-deliver and you better over-deliver on schedule. Otherwise you will have torched your business' reputation from its very start.
If you are going to pre-sell, you'll need to develop some kind of proof of concept. If you're selling a physical product, that could be a working prototype. If it's a software product, it could be a wireframe.
Next you'll need a website that details the benefits of your product and allows customers to pre-buy. You'll need some digital marketing to drive traffic to your site. We'll go into detail on marketing in a later chapter, but marketing will play a crucial role in driving pre-sales for your business.
You'll also need to know how many pre-sales you'll require to develop your product, and in what timeframe. Like we said, you'll have to commit to a timeframe to deliver your product to buyers, so you'll have a limited time to secure those funds. If you miss this deadline, you will have created unsatisfied customers before you even launch.
Pros and cons
Pros
Generates demand for your business before it launches
Builds a customer base
Cons
Potential to burn bridges if you don't deliver on your promises
Limits your product development timeframe
Keep it low cost
What it means
OK, we're admittedly a bit biased, but this is our favorite option. You can keep your startup costs to an absolute minimum by identifying needs that you can fulfill using freelancers. And by absolute minimum, we mean less than $1,000 USD.
How to do it
Think about what your business actually needs to get started. If you're not a bricks and mortar retailer (and we unabashedly prefer e-commerce as a business model over bricks and mortar), you don't need office space. Instead, you can build out a virtual office using freelancers.
Here are a few things you will need as an online business:
Website design (average of $244.88 on Freelancer)
Web hosting and domain name (about $14.99 per year for domain name and $8.99 per month for web hosting via GoDaddy)
Branding (average of $151.48 on Freelancer)
A logo (average of $88.83 on Freelancer)
Marketing (average of $173.40 on Freelancer)
In addition to this, you might need inventory if you're an e-commerce retailer. If you're launching a new product, you might also need product design (average of $329.33 on Freelancer).
Let's go into a bit more detail about why you need these and how to get them done.
Whether you're an online business or a traditional business, you need a website. In fact, 30% of consumers won't even consider a business that doesn't have a website.
The services you'll need to build your website will depend on the type of business you're starting. If you're starting a business that requires a sophisticated website with custom functionality, you'll need a web developer. For most businesses, though, a website built using Wix, Squarespace or Wordpress will work just fine.
However, even if you choose one of the platforms mentioned above, you'll want your website to have its own look and feel that reflects your brand. To pull this off, you'll need a web designer.
Your website will need to be hosted. Web hosting provides the server storage space for your website and makes it accessible on the internet. If your website is sophisticated and has to store a lot of data, you might need a heavy duty cloud server platform like Amazon Web Services. But for most businesses, an inexpensive web hosting platform like GoDaddy or Bluehost should work.
You're also going to need to find a consistent look and feel for your brand. Fortunately, you can find a graphic designer who specializes in creating brand identity. This service could include logo design, but if it doesn't you can also hire a graphic designer specifically to create your business' logo.
Marketing is another essential component. Once you have your business up and running, you need to make people aware of it.
In a later chapter we'll go into more detail about how and why to build out a virtual office using freelancers. But even at a glance, you can see that using freelancers to keep your startup costs lean means you can start pursuing your business without a massive amount of capital. And if you do pursue other forms of funding in the future, demonstrating low operating costs will put you in a great position to secure investors.
Pros and cons
Pros
Can fund your startup yourself
Keeps costs low to make your business more attractive to future investors
Allows you to staff for specific projects without a long-term hiring commitment
Cons
Some business models may require more startup capital
Conclusion
Once you've got your funding, it's time to launch your business in earnest. In the next chapter, we'll offer some practical tips on the logistics of putting your business together.
READ CHAPTER 4 OF THE ULTIMATE BUSINESS GUIDE | https://www.freelancer.hu/articles/starting-your-business/funding-your-startup | CC-MAIN-2021-25 | refinedweb | 7,162 | 59.94 |
So here is something that came up in a discussion I was having. It revolved around delegates and their parameter types because we were trying to find an easier way to solve an issue without having to write more code than we really wanted to. If you program entirely in VB or are not using .Net framework 2.0 with C#, then you are missing out on 2 features of delegates that are very useful: covariance and contravariance. Now I have personally spent, until very recently, the vast majority of my time in VB and Framework 1.1, so even though I knew about the features, I never fully understood what I could do with them and I was never able to make use of them until now when it came up as part of a way to solve a problem in a program that I am helping a friend with. He knew nothing of these new features, so maybe there are more of you out there that benefit from this, as it doesn’t seem to be well documented in easy to find places. Just for fun I tried to google "covariance" and a few other things with no success, so maybe putting this out there will make it easier for others to find. These are fine examples of how the languages continue to evolve and allow us to create more flexible, maintainable and efficient code.
Covariance basically means that the return value of a method that is referenced by your delegate can have a different return type than that specified by the delegate itself, so long as the return type of the method is a subclass of the return type of the delegate. In the example below, you can see that MyMethod returns Car, but xyz is calling FunctionTwo, which returns type Toyota. Because Toyota is derived from Car, this works.
public class Car
{
}
public class Toyota : Car
{
}
class Demo
{
static void Main()
{
MyMethod abc = FunctionOne;
MyMethod xyz = FunctionTwo;
}
public delegate Car MyMethod();
public static Car FunctionOne()
{
return new Car();
}
public static Toyota FunctionTwo()
{
return new Toyota();
}
}
Contravariance is kind of the same thing, but deals with the parameters rather than return types. Contravariance allows you to use delegate parameters who’s types are those that inherit from the parameter types used in the method the delegate references. In the following example, you can see that FunctionOne specifies the Car type as the parameter, while the delegate has the signature that specifies Toyota. Contravariance allows this to happen.
class Demo
{
public delegate void MyMethod(Toyota value);
static void Main(string[] args)
{
MyMethod abc = FunctionOne;
MyMethod xyz = FunctionTwo;
}
public static void FunctionOne(Car value)
{
}
public static void FunctionTwo(Toyota value)
{
}
}
Last week I decided its time to get a new phone. I’ve always had just a “phone”. You couldn’t do anything more with it than dial numbers and talk to people (although my last phone, the Motorola V300 did have a camera). This time I went all out. I didn’t get just a phone. I got a miniature laptop that fits on my hip.
I now have a Blackberry Pearl smartphone, the latest and greatest in mobile handheld technology. I have to tell you, after having this phone for a few days, I am absolutely loving it. The only thing this phone doesn’t do is record video, unless it does and I just haven’t figured it out yet. Having just stepped into the boundries of Blackberry, I’m awed and impressed.
The Pearl has seemless integration with GMail, which was important to me. The email features are outstanding. This doesn’t have a full 1 key per letter keyboard, but typing is just as fast (most of the keys are doubled up i.e. A/S are on one key), because of the QWERTY keyboard layout. It has built in support for Yahoo, AIM, MSN, ICQ and Blackberry instant messenging.
The trackball navigation is pretty slick. You can pretty much do everything you need to with your thumb just by moving and pressing the trackball. Voice activated dialing is also built in.
The address book is nice and take me back to the days of an old phone I had many years ago. My V300, I had to store HOME and WIFE CELL seperately, as did for DAD HOME, DAD OFFICE, DAD CELL etc. Now, I just have an entry for DAD, and in that entry I have all his phone numbers, email, addresses etc.
The address book synchronizes with the Contact list from my Microsoft Outlook. Same with the calendar, tasks and memos, so I can keep them all synched up just like a regular Palm thingy. Right now I do the synchronizations via USB, but hoping that a new laptop soon with also have Bluetooth installed and then I can go all wireless.
Browsing the internet is just as fast on my phone as it is at my house it seems (I have 1.5 Mbps down at home). Now, I know that my phone doesn’t process the backgrounds, styles etc (I have them turned off) but going to CodeBetter came up in a flash.
The picture quality of photos I take is much better with the Pearl than it was with my V300. Its 1.3 megapixels with 5x zoom and built-in flash.
Blackberry Maps is very cool. I just punch in an address and it brings up the map, or I can get driving directions as well. It doesn’t have a GPS receiver in it, so this is the next best thing.
This thing knows when you have it holstered or not. You can set it up so that if you have it holstered, it will only vibrate when an email comes in, or ring and vibrate when you get a phone call, or play a tune when somebody IMs you. When you take it out, it knows it and plays different tunes, doesn’t vibrate, or however you set it up. Cool stuff.
Tons of applications available for this phone at Handango. 547 for the Pearl. Many other devices are listed there as well.
I also bought a 1 GB memory chip for the Pearl. I can load tons of MP3s and play them right on my phone, just like an IPod.
So in short, I have a phone, Palm, IPod, camera, email etc all in one device. Sounds just like a laptop, eh?
I would like to wish my wonderful wife of 10 years a Happy Anniversary today. This year has been the most trying year of our lives. To quote a line from the new Rocky Balboa movie I watched last night regarding life, “… its about how hard you can get it, and keep moving forward.” We took our punches, and we’re still standing.
Also some exciting news is that I will begin a new job on January 15th for one of the best consulting firms there is: Geniant. I’m really looking forward to moving back to the private/commercial sector after having spent the last 9 years working entirely in the public sector. Geniant has some awesome individuals on staff, including Chip Wilson, who is 1 of about 50 people world-wide to hold the Microsoft Certified Architect honor, as well as certifications from IBM and Sun. Exciting opportunity indeed.
April 16th, 1 year to the day when our son died, we shall have a new son arrive. For those of you who know the story from earlier this year, this baby looks completely healthy and everything is great at this point.
I did a lot of presentations around the Midwest this year, and have 5 setup for this coming winter and spring, so I’ll see some of you around early this coming year. I really enjoy doing this and am looking forward to the tour before my son arrives.
I’m looking forward to blogging more again. My new job and all the industries and technologies it shall touch is going to be exciting and I’ll have plenty of things to share with you as I learn new tricks, new tools and new people.
Stay tuned, its going to be a great | http://codebetter.com/blogs/raymond.lewallen/archive/2006/12.aspx | crawl-001 | refinedweb | 1,374 | 69.92 |
Running Windows 7 64bit
I did a project last month and used both a USBTiny and my Atmel-ICE without any problems. Now I can't access my ATMega328P with USBTiny or the Atmel-ICE. I'm thinking maybe a uSoft update messed something up.
I'm using a stable 5V power supply on the Evil Mad Scientist board where the ATMega328P is installed in a ZIF socket...I've used this board a bunch in the past so I know it's not a problem.
Also I've used 2 chips and 2 different boards with same results.
So here's the deal;
When I plug the USBTiny into USB plug then apply power to the board the system recognizes it but it I plug it in and power is already applied I get an unknown device error.
And in Device Manager it's listed under libusb-WIN32 as usbtiny!
using AVRDUDE; avrdude -c usbtiny -p atmega328p -v
and get
Now in Atmel Studio 6.2, I uninstalled 6.2, 7.0 and all drivers and reinstalled 6.2 last night with no change.
When I plug the Atmel-ICE in the system recognizes it as Atmel-ICE CMSIS-DAP
but when I go to program device it gives error;
The ISP Clock is set all the way down on 45kHz
I know the chip is not bricked, DWEN not set.
So I'm absolutely stumped! Any help would be much appreciated! | https://www.avrfreaks.net/forum/driver-problem-or-what | CC-MAIN-2021-17 | refinedweb | 243 | 81.73 |
With the release of ASP.NET 2.0 comes a powerful new diagnostics framework located under the System.Web.Management namespace. The intention of this new framework is to eliminate the need to use external logging libraries such as log4net. This article is not meant to be an overview of the new features available in ASP.NET but as a means to use the events provided by this system in combination with log4net. However, for a great overview of the System.Web.Management namespace, I would urge you to read the Diagnostics chapter in Essential ASP.NET 2.0 by Fritz Onion and Keith Brown.
System.Web.Management
Because the System.Web.Management system is intertwined within the core ASP.NET framework, there are some pretty important events provided that used to require jumping through hoops to obtain in the past. For instance, logging when and why an application shutdown used to mean you had to hook into the Global.asax and use Reflection to pull the correct properties (see this overview on Scott Gu’s blog for more information). However, with the new ASP.NET infrastructure, these messages are provided automatically, and it only takes setting up the right provider to begin receiving them.
This is all great, but the question that I encountered was what if you had an existing application that already has a large log4net infrastructure in place? Or, what if you wanted to use some of the appenders that comes with the log4net framework (such as the RollingFileAppender) which are not provided with the new ASP.NET infrastructure? These questions lead me to the point of this article: how to send messages from the ASP.NET Management framework to log4net without having to write any code.
RollingFileAppender
Like most of the new features in ASP.NET 2.0, the health monitoring framework relies on the extensible Provider model. By utilizing this, we are able to essentially forward messages from ASP.NET to log4net. In other words, capturing all the internal ASP.NET web events in log4net is as simple as adding a reference to the provider included in the download.
An example configuration is shown below:
<healthMonitoring enabled="true">
<providers>
<add name="Log4NetProvider"
type="HealthMonitoring.Log4NetBufferedWebEventProvider"
bufferMode="Critical Notification"
loggerName="MyLog"
level="Debug"
/>
</providers>
<rules>
<add name="MyCustomRule"
eventName="All Events"
provider="Log4NetProvider"
minInterval="00:00:01" minInstances="1"
maxLimit="Infinite"
/>
</rules>
</healthMonitoring>
As you can see, we are simply adding a new health monitoring provider and creating a new rule to apply to that provider. With this in place, the ASP.NET web events automatically begin logging to whatever log you specify. One thing to keep in mind is, the provider assumes log4net has already been been configured and does not explicitly perform the configuration.
Below is an example message that is now logged to my log4net log when the application shuts down:
12/20/2006 11:45:49,154 DEBUG MyLog [%user name%,beyg2355kdautd55lcwkmb45] - Event code: 1002
Event message: Application is shutting down. Reason: Configuration changed.
Event time: 12/20/2006 11:45:49 AM
Event time (UTC): 12/20/2006 5:45:49 PM
Event ID: 6b81587fc7ee4a4bb78d719402456438
Event sequence: 9
Event occurrence: 1
Event detail code: 50004%
Besides simply using the included provider to capture all the built-in ASP.NET web events, this provider will also allow you to create your own web events and even customize how they are logged in log4net. This is done by using the provided ILoggerEvent interface shown below:
ILoggerEvent
interface ILoggerEvent
{
Level Level
{
get;
set;
}
string LogName
{
get;
set;
}
}
By creating your event and implementing the above interface, you can specify at what level and which log the event is to be logged. An example implementation is provided in the code download called LoggerWebRequestEvent. As shown below, this event can specify a different log and level than what was specified in the provider configuration settings.
LoggerWebRequestEvent
12/20/2006 11:45:14,575 ERROR DifferntLog
[%user name%,beyg2355kdautd55lcwkmb45] - Event code: 150000
Event message: i cannot be less than zero and is currently -1
Event time: 12/20/2006 11:45:13 AM
Event time (UTC): 12/20/2006 5:45:13 PM
Event ID: 213c7c5f04084c8898324f9bff7b9808
Event sequence: 8
Event occurrence: 1
Event detail code: 0%
Request information:
Request URL: %request url%
Request path: /Default.aspx
User host address: 127.0.0.1
User: %user name%
Is authenticated: True
Authentication Type: NTLM
Thread account name: %user name%
Custom event details:
By creating custom web events, you can begin moving in the direction of using the provided logging infrastructure without having to make the change overnight.
As more and more providers are created for the ASP.NET Management framework, I think the need to utilize third party frameworks will decrease. However, with existing applications and libraries, this provider bridges the gap, allowing log4net users to get the messages that are already provided internal to the ASP.NET 2.0 framework with minimal. | http://www.codeproject.com/Articles/16832/How-to-Capture-Web-Events-in-log4net?fid=369170&df=90&mpp=10&sort=Position&spc=None&tid=1813147 | CC-MAIN-2015-27 | refinedweb | 825 | 54.22 |
Have you come across a situation where you need to store a dictionary with a huge number of strings and realized that keeping it in memory is a nightmare? If so, this might be one of the best solutions for your problem. In this article I'll describe an implementation where everything in the dictionary is kept in the disk. The advantages of using this in your code are:
I am doing a research in natural language processing for Sinhala which is my native language. For this, I needed to keep several big dictionaries (phrase, word and sound dictionaries) in memory at the same time. However, I realized that the dictionaries eat a lot of memory (hundreds of megabytes) causing the program performance to degrade vastly. I was forced to go for an implementation where the dictionary can be kept in and accessed directly from the disk.
Say, we are to store a dictionary with 100,000 words. If the average length of a word is 6 characters and we store the relative frequency (likelihood of appearance) of the word as an integer. We'll need 10 bytes for a word and only 1MB for the whole dictionary!! It's quite a small amount and why do we need to go for a disk approach? Well, this will be the case only if we store the words sequentially. This will require a linear search to find a word which is totally impractical (in terms of performance) for a big dictionary. Therefore we definitely need a structured way to store the dictionary. Trie, being a tree based data structure, is the most popular answer for this. In a trie, the search for a word will require only as few steps as the word's depth in the tree.
Now the question is how much memory do we need to store the trie. Will it be significantly higher than that needed for the sequential approach? Let's see. There are leaf nodes in the trie equal in number to the words in the dictionary i. e. 100,000. In addition, there are internal (non-leaf) nodes. In my work, I found this number is nearly two times the number of leaf nodes when words are stored. So, the total node count will be approximately 300,000. How much memory for a node? A node will require : (i) ID : 4 bytes (ii) A flag to indicate whether it is a leaf node : 1 byte (iii) map of transitions from the node if the node is internal - a transition is an association of a string (note that the unit is string) and an integer. Let's say the average number of transitions per node is 5 (5 bytes * 5 = 25 bytes). The map data structure itself will take some memory. If we assume it to be 10 bytes the memory taken by the map is 35 bytes. So, the memory taken by a node will be 40 bytes and the whole dictionary will need 40 * 300,000 = 12MB. This is much more than that we predicted for sequential approach. Things get worse when the strings stored are longer (e.g. phrases). The node count will be much higher and the memory requirement will grow into even hundreds of MBs.
You do not need to understand or even read this section to use the code. This section is for people who are interested in the inside story. I used the B-Tree approach when storing the dictionary in the disk which is very common in database implementations. You better read a good tutorial (there are many) on B-Trees before reading this section if you are not familiar with them.
In this implementation there are three structures that constitute the disk file.
Our disk file consists of sequentially arranged instances of these structures. Lets peep into the node structure.
Note that a node contains its first TMP within itself. Then it has the offset to its next TMP if any; otherwise it is set to invalid offset. Transition Page structure looks exactly like the part enclosed by the red borders whereas in a TMP there is an additional integer field at the beginning which indicates the offset to the next TMP if any.
The disk file has a header which contains some attributes and statistics of the dictionary.
First two bytes of the header is the two characters "DL" which stands for "Dictionary Lite". If you open the dictionary file in a text editor you'll see these two characters in the beginning. What immediately follows the header is the root node of the trie.
Using the code is very simple. First include "Dictionary.h" in your project. You can create a CDictionaryLite object and manipulate it with the functions described in the following guidelines.
CDictionaryLite
CDictionaryLite(CString sFilename);
CDictionaryLite(CString sFilename, bool bKeepFile,
int iStrLen = DICTIONARY_LITE_DEFAULT_STR_LEN,
int iNoOfStrInNode = DICTIONARY_LITE_DEFAULT_NO_OF_STR_IN_NODE,
int iNoOfStrInTransition = DICTIONARY_LITE_DEFAULT_NO_OF_STR_IN_TRANSITION);
Use the second constructor when creating the dictionary for the first time. The second argument indicates whether or not to keep the dictionary file after being destroyed. If you create a large number of dictionaries throughout the program and do not need them after the program termination, keep this argument false. There are other dictionary related arguments (optional) that you can specify according to the requirement. For an example, if you are going to use character as the unit of string, you may set iStrLen = 2 (remember to keep one byte for the null terminator). iNoOfStrInNode is the number of strings in a node or in a TMP. iNoOfStrInTransition is the number of strings in a transition page. If not specified these parameters will be assigned with default values. However, it's always a good practice to enter these values to minimize the space and time complexities of your dictionary.
iStrLen
iNoOfStrInNode
iNoOfStrInTransition
The first constructor should be used when creating a dictionary object using an already existing dictionary file. Only the filename has to be given because the dictionary file contains all other parameters in its header.
void AddString(CStrList& oStrList, int iCount = 1);
Note that you enter a string list rather than a single string as the word. This is because the unit of the string used in the dictionary is also a string. This is done to make it more generic. CStrList is a class derived from std::list<CString> so all you have to do is push unit strings to it. If this is not clear, refer to the example below. Optionally the count of the string can be given. If the word is already in the dictionary, its count will be incremented by this number.
CStrList
std::list<CString>
int GetStringCount(CStrList& oStrList);
If the word is in the dictionary the output will be its count, zero otherwise.
bool GetFirstWord(CStrList& oStrList, int& iCount);
bool GetNextWord(CStrList& oStrList, int& iCount);
Function names are self-explanatory. Words in the dictionary are traversed in a depth-first-left-recursive fashion. i.e. if A and are two sibling nodes (with same parent node) with A is in left to B in the tree, B is not visited until A and all its descendents are visited.
After using the dictionary object just delete it. It's that simple! The dictionary file will remain in the disk (unless you entered bKeepFile parameter as false in the constructor) and you can use it again.
bKeepFile
The following code snippet illustrates these basic operations:
// create dictionary
CDictionaryLite* pDicLite = new CDictionaryLite
("MyDic.ldic", true, 3, 5, 6);
// add three words to the dictionary
CStrList oStr1, oStr2, oStr3;
oStr1.push_back("a");
oStr1.push_back("pp");
oStr1.push_back("le");
// "apple"
oStr2.push_back("m");
oStr2.push_back("a");
oStr2.push_back("n");
// "man"
oStr3.push_back("ca");
oStr3.push_back("t");
// "cat"
pDicLite->AddString(oStr1); // count = 1
pDicLite->AddString(oStr2, 4); // count = 4
pDicLite->AddString(oStr3, 2); // count = 2
//check whether "cat" is in the dictionary
bool bIsInDictionary = (pDicLite->GetStringCount(oStr3) > 0);
// result : true
oStr3.push_back("s");
//check whether "cats" is in the dictionary
bIsInDictionary = (pDicLite->GetStringCount(oStr3) > 0);
// result : false
//retrieve first two words in the dictionary
CStrList oWord;
int iCount;
pDicLite->GetFirstWord(oWord, iCount);
// oWord = "apple" iCount = 1
pDicLite->GetNextWord(oWord, iCount);
// oWord = "cat" iCount = 2
// destroy the dictionary object
delete pDicLite;
Memory required for a dictionary object is in bytes - not even in kilobytes! This does not depend on the actual dictionary size. It takes less than 1ms to access one word (to find the count of a word) in my 2.8 GHz machine. This can be definitely made even more faster by adding in-memory cache. Can somebody try this?
The space that the dictionary acquires from disk can be reduced by implementing variable size pages because in this implementation the page size (number of strings in a page) is fixed and not necessary all the entries in a page (transition page or TMP) are used. In this case the page size can be stored somewhere in the page itself. Appreciate if someone can try this as well.
10-March-2007: Initial Release2065: 'greater' : undeclared identifier c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 2 error C2062: type 'int' unexpected c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 4 error C2143: syntax error : missing ';' before '>' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 5 error C2059: syntax error : '>' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 8 error C2065: 'greater' : undeclared identifier c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 9 error C2062: type 'int' unexpected c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 11 error C2143: syntax error : missing ';' before '>' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 12 error C2059: syntax error : '>' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 13 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.h 22
Error 21 error C2146: syntax error : missing ';' before identifier 'mmapWords' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 987
Error 22 error C2065: 'mmapWords' : undeclared identifier c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 987
Error 23 error C2065: 'mmapWords' : undeclared identifier c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 991
Error 24 error C2228: left of '.insert' must have class/struct/union c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 991
Error 25 error C2065: 'mmapWords' : undeclared identifier c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 994
Error 26 error C2228: left of '.size' must have class/struct/union c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 994
Error 27 error C2825: 'MMAP_REVERSE_INT_STR': must be a class or namespace when followed by '::' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 996
Error 28 error C2143: syntax error : missing ';' before 'std::iterator' c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 996
Error 29 error C2955: 'std::iterator' : use of class template requires template argument list c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 996
Error 30 error C1903: unable to recover from previous error(s); stopping compilation c:\users\marcin\desktop\b-tree\cdictionarylite_demo\dictionary.cpp 996
31 IntelliSense: greater is not a template c:\Users\Marcin\Desktop\B-Tree\CDictionaryLite_demo\Dictionary.h 22
32 IntelliSense: this declaration has no storage class or type specifier c:\Users\Marcin\Desktop\B-Tree\CDictionaryLite_demo\Dictionary.h 22
typedef multimap < int, CString, greater<int> > MMAP_REVERSE_INT_STR;
MMAP_REVERSE_INT_STR::iterator ite1 = mmapWords.begin();
Priyank Bolia wrote:Hunspell is used by Mozilla and Open office and is extremely fast and can read write standard dictionaries used by other softwares.
"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
Priyank Bolia wrote:Yes, its open source and extremely fast and use standard dictionaries available for Mozilla or Open Office and just doesn't matches char by char, but works on phonetic and the science of words.
Priyank Bolia wrote:
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/17974/A-Lite-Memory-Dictionary | CC-MAIN-2016-22 | refinedweb | 2,062 | 56.45 |
Install and access data files (conf, json, sqlite3, ...) in an easy way.
Project Description beta software!
First, let’s make life easier and use some ‘configuration by convention’.
I assume that (1) you have layout your project like:
MANIFEST.in README.rst setup.py mypkg │ ├── __init__.py ├── mypkg.conf ├── mypkg.db └── ...:
$ pip install -U datafolder
Then, type:
$ datafolder
It will make a file called bootdf.py that you must put inside your mypkg directory and a new file called setup_TPL.py that you must put in the root of your project.
setup_TPL.py,'other_packg1','other_packg2'], # <-- ADAPT THIS data_files=data_files, ... # <-- ADAPT THIS ) # but we are NOT READY, in some cases the data files # don't have the appropriate permissions, # let us fix that... installer.pos_setup(MYDATAFILES)
- Now, rename the file to setup.py.
- Write your MANIFEST.in file (missing this step is the cause of many problems!). Should look like this:
include *.txt include *.md include *.rst include mypkg/*.conf include mypkg/*.rst include mypkg/*.db
And that is all!
But with version 0.2.1 it is even better!
Just go to the root of you project and in a terminal type:
$ datafolder mypkg
Now, you will see that MANIFEST.in and setup.py were fill in for you and bootdf.py is already inside the mypkg folder. You only need to complete setup.py as need (the fields author, email, url and trove classifiers …).
“But, I have the reverse problem, how can I access these files in my code?” I heard you say.
Very easy, in your code (for a file in the same folder as bootdf.py):
from .bootdf import DataFolder data = DataFolder('mypkg') # now you can get the full path of each data file, e.g. conf_fp = data.files['mypkg.conf'] # do your thing... (read, write, ...)
For your convinience, the DataFolder class discovers the location of the data folder for you and provides attributes and methods, that make it easy to handle the files presente in the data folder.
REMARK: as you can see above, this only works if the install method uses setup.py. Is not the case of python wheels however!
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/datafolder/ | CC-MAIN-2018-17 | refinedweb | 381 | 78.85 |
A Python library to interact with Hulu's "hidden" 2.0 API.
Project description
hulu attempts to make it easy for developers to interact with the Hulu “hidden” 2.0 API
The Story
A friend of mine, (@adammagana) created a PHP library (found here) to interact with the Hulu “hidden” 1.0 API. The 1.0 API only returns XML, but someone opened up an issue revealing some 2.0 endpoints that return JSON.
Since JSON is easier to work with in Python than XML is, I took it upon myself to try an open up their API to other developers.
Features
- List companies that have shows/videos on Hulu
- List videos from a specific show
- List trailers available on Hulu
- Find the position of a given video within the shows video list
- (Kind of) Much more!
Installation
$ pip install hulu
Example Usage
from hulu import Hulu h = HuluAPI() try: h.get_companies() except HuluError as e: print e try: h.get_video_info(441295) except HuluError as e: print e
Contribute
If anyone has additional information (such as; paramters taken to given API methods, extra API methods not yet found, etc.) please feel free to open a Pull Request! :)
TODO
- Figure out authentication!
Some API methods require authentication, yet I haven’t been able to figure out how to authenticate to make those API calls, these API calls include:
api/2.0/plus_upsell.json api/2.0/favorited_show_ids api/2.0/queued_video_ids
Project details
Release history Release notifications | RSS feed
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/hulu/ | CC-MAIN-2021-21 | refinedweb | 269 | 63.19 |
Exchange 2010 CAS certificates
hi, i am not certificate expert, so please bear with me. i am trying to get certificates for our CAS array, OWA etc. the domains are: -mail.ourExternaldomain.com -legacy.ourExernaldomain.com -autodiscover.ourExternaldomain.com -casArray.ourInternaldomain.com -casServer.ourInternaldomain.com the problem is, ourInternaldomain.com eventually exists and owned by another company. what should I do? should I just use internal CA/certs for those namespace? do i really need cert for casArray.ourInternaldomain.com and casServer.ourInternaldomain.com, anyway? please shed some light. thanks.
July 15th, 2010 10:03am
Hi, By default Exchange 2010 comes with a built-in certificate which is not trusted. You need to obtain a third party trusted certificate for wider use. You can have different domain name on the certificate other than the internal domain. For complete understanding you may read the below article. Also watch this video to request and implement certificate from local CA. Regards, Tariq
July 15th, 2010 12:23pm
You don't have to use the internaldomain in the cert. You will need to create a DNS zone internal for your external domain namespace (split brain DNS). Update all CAS internal and external URLs to the externaldomain names. Then point the internal DNS zone for external namespace to the internal IPs of the Exchange server. Point the CASArray URL and DNS to one of the external domain names (probably mail.ourexternaldomain.com). And you only need legacy if you are supporting coexistence with Exch 2003. Tim Harrington - Catapult Systems -
July 15th, 2010 4:19pm
hi tim, are you suggesting the CAS array FQDN to be resolvable externally? is this a good practice? the reason i come into this issue is because i'm trying to keep CAS array FQDN to local. maybe my only option is to use my own PKI/CA for the internal namespace and 3rd party CA for the external? do i make any sense? :(
July 15th, 2010 4:57pm
The CAS Array FQDN can be the externdomain name (mail.). There is no issues with this. You are not going to be able to split up the certs as there is just one website to bind the cert to. If you do not have the option to add the internaldomain to the cert SAN, and you only have the option to use the externaldomain in the cert, then you are going to have to go this route. When you use split brain DNS, the CAS Array will resolve to the internal IP. The only thing that is referenced from the outside is the mail. and autodiscover. records. You just happen to be using the same name for the FQDN of the CAS array. It is actually much less complex to do it this way. Here is a good reference article: Tim Harrington - Catapult Systems -
July 15th, 2010 10:10pm
if cas array name = external domain (mail.), won't you run into this issue mentioned by Brian Day on this thread? () thanks for the link to the article. i have read the article and it uses different name outlook.contoso.com as the CAS array, in oppose to mail.contoso.com. so back to one of my original questions, do we actually need a certificate for outlook.contoso.com, do we need to include it in the SAN names? thanks again.
July 16th, 2010 1:55am
I guess I will let someone else chime in. I have done a 3 node DAG with a HLB for the CAS array. Pointed the CAS Array to mail.extdomain and only had mail.extdomain, autodiscover.extdomain and legacy.extdomain in my cert. Changed all InternalURLs and ExternalURLs to point to mail.extdomain and autodiscover.domain (depending on which URLs are being configured). Internal clients point to internal VIP of HLB. External DNS points to public IP that NATs to VIP of HLB. Everything works just fine. Anyone else want to chime in? Tim Harrington - Catapult Systems -
July 16th, 2010 5:23am
hmm..anyone?
July 19th, 2010 3:57am
Tim’s design is one option for you, although Brian’s concern is possible if we publish the CAS array FQDN to the internet. If you also concern about it, then casArray.ourInternaldomain.com is required to be added, but casServer.ourInternaldomain.com doesn’t have to be addedJames Luo TechNet Subscriber Support () If you have any feedback on our support, please contact [email protected]
July 21st, 2010 12:59pm
thanks guys. i ended up using casArray.ourExternaldomain.com for array FQDN and place it on internal (split) DNS.
July 26th, 2010 7:15am | http://www.networksteve.com/exchange/topic.php/Exchange_2010_CAS_certificates/?TopicId=4844&Posts=9 | CC-MAIN-2019-13 | refinedweb | 767 | 68.47 |
Pylint NEWS¶
What’s new in Pylint 1.6.4?¶
Release date: 2016-07-19
-
Recurse into all the ancestors when checking if an object is an exception
Since we were going only into the first level, we weren’t inferring when a class used a metaclass which defined a base Exception class for the aforementioned class.
What’s new in Pylint 1.6.3?¶
Release date: 2016-07-18
-
Do not crash when inferring uninferable exception types for docparams extension
Close #998
What’s new in Pylint 1.6.2?¶
Release date: 2016-07-15
-
Do not crash when printing the help of options with default regular expressions
Close #990
-
More granular versions for deprecated modules.
Close #991
-
Do not crash in docparams when we can’t infer the exception types.
What’s new in Pylint 1.6.1?¶
Release date: 2016-07-07
- Use environment markers for supporting conditional dependencies.
What’s New in Pylint 1.6.0?¶
Release date: 2016-07-07
-, ‘trailing-newlines’, which is emitted when a file has trailing new lines.
Closes issue #682.
-
Add a new option, ‘redefining-builtins-modules’, for controlling the modules which can redefine builtins, such as six.moves and future.builtins.
Close #464.
-
‘reimported’ is emitted when the same name is imported from different module.
Close #162.
-
Add a new recommendation checker, ‘consider, ‘invalid.6?¶
Release date: 2016-06-06
-
config files with BOM markers can now be read.
Close #864.
-
epylint.py_run does not crash on big files, using .communicate() instead of .wait()
Close #599 ‘un
-
Don’t emit unsubscriptable-object if the node is found inside an abstract class. Closes issue #685.
-. ‘wrong-import-order’ is emitted when PEP 8 recommendations regarding imports are not respected (that is, standard imports should be followed by third-party imports and then by local imports). ‘ungrouped-imports’ is emitted when imports from the same package or module are not placed together, but scattered around in the code. ‘wrong-import-position’ is emitted when code is mixed with imports, being recommended for the latter to be at the top of the file, in order to figure out easier by a human reader what dependencies a module has. Closes issue #692.
-
Added a new refactoring warning, ‘unneeded-not’, emitted when an expression with the not operator could be simplified. Closes issue #670.
-
Added a new refactoring warning, ‘simplifiable-if-statement’, used when an if statement could be reduced to a boolean evaluation of its test. Closes issue #698.
-
Added a new refactoring warning, ‘too-many-boolean-expressions’, used when a if statement contains too many boolean expressions, which makes the code less maintainable and harder to understand. Closes issue #677.
-
Property methods are shown as attributes instead of functions in pyreverse class diagrams. Closes Issue #284
-
Add a new refactoring error, ‘too-many-nested-blocks’, which is emitted when a function or a method has too many nested blocks, which makes the code less readable and harder to understand. Closes issue #668.
-
Add a new error, ‘unsub, ‘unsupported-membership-test’, emitted when value to the right of the ‘in’ operator doesn’t support membership test protocol (i.e. doesn’t define __contains__/__iter__/__getitem__)
-
Add new errors, ‘not-an-iterable’, emitted when non-iterable value is used in an iterating context (starargs, for-statement, comprehensions, etc), and ‘not-a-mapping’, emitted when non-mapping value is used in a mapping context. Closes issue #563.
-
Make ‘no-self-use’ checker not emit a warning if there is a ‘super()’, ‘not-context-manager’, emitted when something that doesn’t implement __enter__ and __exit__ is used in a with statement.
-
Add a new warning, ‘confusing-with-statement’, emitted by the base checker, when an ambiguous looking with statement is used. For example with open() as first, second which looks like a tuple assignment but is actually 2 context managers.
-
Add a new warning, ‘duplicate ‘extensions’ for optional checkers with the test directory ‘test/extensions’ and documentation file ‘doc/extensions.rst’.
-
Added new checker ‘extensions, ‘unexpected-special-method-signature’, which is emitted when a special method (dunder method) doesn’t have the expected signature, which can lead to actual errors in the application code. Closes issue #253.
-
Remove ‘bad-context-manager’ due to the inclusion of ‘unexpected, ‘using-constant-test’, which is emitted when a conditional statement (If, IfExp) uses a test which is always constant, such as numbers, classes, functions etc. This is most likely an error from the user’s part. Closes issue #524.
-
Don’t emit ‘raising, ‘invalid, ‘too-many-star-expressions’, emitted when there are more than one starred expression (*x) in an assignment. The warning is emitted only on Python 3.
-
Add a new error, ‘invalid, ‘star-needs-assignment-target’, emitted on Python 3 when a Starred expression (*x) is not used in an assignment target. This is not caught when parsing the AST on Python 3, so it needs to be a separate check.
-
Add a new error, ‘unsupported, ‘non, ‘continue, ‘misplaced, ‘nonlocal-without-binding’
The error is emitted on Python 3 when a nonlocal name is not bound to any variable in the parents scopes. Closes issue #582.
-
- ‘deprecated, ‘yield-inside-async-function’, emitted on Python 3.5 and upwards when the yield statement is found inside a new coroutine function (PEP 492).
-
Add a new error, ‘not-async-context-manager’, emitted when an async context manager block is used with an object which doesn’t support this protocol (PEP 492).
-
Add a new convention warning, ‘singleton-comparison’, emitted when comparison to True, False or None is found.
-
Don’t emit ‘assigning-non-slot’ for descriptors. Closes issue #652.
-
Add a new error, ‘repeated-keyword’, when a keyword argument is passed multiple times into a function call.
This is similar with redundant-keyword-arg, but it’s mildly different that it needs to be a separate error.
-
–enable=all can now be used. Closes issue #142.
-
Add a new convention message, ‘misplaced-comparison-constant’, emitted when a constant is placed in the left hand side of a comparison, as in ‘5 == func()’. This is also called Yoda condition, since the flow of code reminds of the Star Wars green character, conditions usually encountered in languages with variabile assignments in conditional statements.
-
Add a new convention message, ‘consider-using-enumerate’, which is emitted when code that uses range and len for iterating is encountered. Closes issue #684.
-
Added two new refactoring messages, ‘no-classmethod-decorator’ and ‘no (‘{0}’), mixed with a positional argument which did an attribute access (‘{0.__class__}’). Closes issue #463.
- Take in account all the methods from the ancestors when checking for too-few-public-methods. Closes issue #471.
- Catch enchant errors and emit ‘invalid-characters-in-docstring’ when checking for spelling errors. Closes issue #469.
- Use all the inferred statements for the super-init-not-called check. Closes issue #389.
- Add a new warning, ‘unichr-builtin’, emitted by the Python 3 porting checker, when the unichr builtin is found. Closes issue #472.
- Add a new warning, ‘intern-builtin’, emitted by the Python 3 porting checker, when the intern builtin is found. Closes issue #473.
- Add support for editable installations.
- The HTML output accepts the –msg-template option. Patch by Dan Goldsmith.
- Add ‘map-builtin-not-iterating’ (replacing ‘implicit-map-evaluation’), ‘zip-builtin-not-iterating’, ‘range-builtin-not-iterating’, and ‘filter-builtin-not-iterating’ which are emitted by –py3k when the appropriate built-in is not used in an iterating context (semantics taken from 2to3).
- Add a new warning, ‘un, ‘using ‘raise (ZeroDivisionError, None)’.
- Fix a false positive with invalid-slots-objects, where the slot entry was an unicode string on Python 2. Closes issue #421.
- Add a new warning, ‘redundant-unittest-assert’, emitted when using unittest’s methods assertTrue and assertFalse with constant value as argument. Patch by Vlad Temian.
- Add a new JSON reporter, usable through -f flag.
- Add the method names for the ‘signature-differs’ and ‘argument ‘-j’ option for running checks in sub-processes.
- Added new checks for line endings if they are mixed (LF vs CRLF) or if they are not as expected. New messages: mixed-line-endings, unexpected-line-ending-format. New option: expected-line-ending-format.
- ‘dangerous ‘too-few-format-args’ or ‘too-many-format-args’ for format strings with both named and positional fields. Closes issue #286.
- Analyze only strings by the string format checker. Closes issue #287.
- Properly handle nested format string fields. Closes issue #294.
- Don’t emit ‘attribute-defined-outside-init’ if the attribute was set by a function call in a defining method. Closes issue #192.
- Properly handle unicode format strings for Python 2. Closes issue #296.
- Don’t emit ‘import-error’ if an import was protected by a try-except, which excepted ImportError.
- Fix an ‘unused-import’ false positive, when the error was emitted for all the members imported with ‘from import’ form. Closes issue #304.
- Don’t emit ‘invalid-name’ when assigning a name in an ImportError handler. Closes issue #302.
- Don’t count branches from nested functions.
- Fix a false positive with ‘too-few-format-args’, when the format strings contains duplicate manual position arguments. Closes issue #310.
- fixme regex handles comments without spaces after the hash. Closes issue #311.
- Don’t emit ‘unused-import’ when a special object is imported (__all__, __doc__ etc.). Closes issue #309.
- Look in the metaclass, if defined, for members not found in the current class. Closes issue #306.
- Don’t emit ‘protected-access’ if the attribute is accessed using a property defined at the class level.
- Detect calls of the parent’s __init__, through a binded super() call.
- Check that a class has an explicitly defined metaclass before emitting ‘old-style-class’ for Python 2.
- Emit ‘catching-non-exception’ for non-class nodes. Closes issue #303.
- Order of reporting is consistent.
- Add a new warning, ‘boolean-datetime’, emitted when an instance of ‘datetime.time’ is used in a boolean context. Closes issue #239.
- Fix a crash which ocurred while checking for ‘method-hidden’, when the parent frame was something different than a function.
- Generate html output for missing files. Closes issue #320.
- Fix a false positive with ‘too-many-format-args’, when the format string contains mixed attribute access arguments and manual fields. Closes issue #322.
- Extend the cases where ‘undefined-variable’ and ‘used-before-assignment’ can be detected. Closes issue #291.
- Add support for customising callback identifiers, by adding a new ‘–callbacks’ command line option. Closes issue #326.
- Add a new warning, ‘logging-format-interpolation’, emitted when .format() string interpolation is used within logging function calls.
- Don’t emit ‘unbalanced-tuple-unpacking’ when the rhs of the assignment is a variable length argument. Closes issue #329.
- Add a new warning, ‘inherit-non-class’, emitted when a class inherits from something which is not a class. Closes issue #331.
- Fix another false positives with ‘undefined ‘assigning-non-slot’ when the assignment is for a property. Closes issue #359.
- Fix for regression: ‘{path}’ was no longer accepted in ‘–msg-template’.
- Report the percentage of all messages, not just for errors and warnings. Closes issue #319.
- ‘too-many-public-methods’ is reported only for methods defined in a class, not in its ancestors. Closes issue #248.
- ‘too, ‘exclude ‘class’ statement.
- Warn when performing parameter tuple unpacking; it is not supported in Python 3.
- ‘abstract-class-instantiated’ is also emitted for Python 2. It was previously disabled.
- Add ‘long-suffix’ error, emitted when encountering the long suffix on numbers.
- Add support for disabling a checker, by specifying an ‘enabled’ attribute on the checker class.
- Add a new CLI option, –py3k, for enabling Python 3 porting mode. This mode will disable all other checkers and will emit warnings and errors for constructs which are invalid or removed in Python 3.
- Add ‘old-octal-literal’ to Python 3 porting checker, emitted when encountering octals with the old syntax.
- Add ‘implicit ‘undefined-variable’ for undefined names when using the Python 3 metaclass= argument.
- Checkers respect priority now. Close issue #229.
- Fix a false positive regarding W0511. Closes issue #149.
- Fix unused-import false positive with Python 3 metaclasses (#143).
- Don’t warn with ‘bad-format-character’ when encountering the ‘a’ format on Python 3.
- Add multiple checks for PEP 3101 advanced string formatting: ‘bad-format-string’, ‘missing-format-argument-key’, ‘unused-format-string-argument’, ‘format-combined-specification’, ‘missing-format-attribute’ and ‘invalid-format-index’.
- Issue broad-except and bare-except even if the number of except handlers is different than 1. Fixes issue #113.
- Issue attribute-defined-outside-init for all cases, not just for the last assignment. Closes issue #262.
- Emit ‘not-callable’ when calling properties. Closes issue #268.
- Fix a false positive with unbalanced iterable unpacking, when encountering starred nodes. Closes issue #273.
- Add new checks, ‘invalid-slice-index’ and ‘invalid-sequence-index’ for invalid sequence and slice indices.
- Add ‘assigning-non-slot’ warning, which detects assignments to attributes not defined in slots.
- Don’t emit ‘no-name-in-module’ for ignored modules. Closes issue #223.
- Fix an ‘unused-variable’ false positive, where the variable is assigned through an import. Closes issue #196.
- Definition order is considered for classes, function arguments and annotations. Closes issue #257.
- Don’t emit ‘unused-variable’ when assigning to a nonlocal. Closes issue #275.
- Do not let ImportError propagate from the import checker, leading to crash in some namespace package related cases. Closes issue #203.
- Don’t emit ‘pointless ‘unnecessary-lambda’ if the body of the lambda call contains call chaining. Closes issue #243.
- Don’t emit ‘missing ‘index ‘eval ‘logging, ‘bad-reversed-sequence’, for checking that the reversed() builtin receive a sequence (implements __getitem__ and __len__, without being a dict or a dict subclass) or an instance which implements __reversed__.
- Mark file as a bad function when using python2 (closes #8).
- Add new warning ‘bad-exception-context’, checking that raise … from … uses a proper exception context (None or an exception).
- Enhance the check for ‘used-before-assignment’ to look for ‘nonlocal’ uses.
- Emit ‘undefined-all-variable’ if a package’s __all__ variable contains a missing submodule (closes #126).
- Add a new warning ‘abstract-class-instantiated’ for checking that abstract classes created with abc module and with abstract methods are instantied.
- Do not warn about ‘return-arg-in-generator’ in Python 3.3+.
- Do not warn about ‘abstract emmited as a regular warn().
- Avoid false used-before-assignment for except handler defined identifier used on the same line (#111).
- Combine ‘no-space-after-operator’, ‘no-space-after-comma’ and ‘no-space-before-operator’ into a new warning ‘bad-whitespace’.
- Add a new warning ‘superfluous-parens’ for unnecessary parentheses after certain keywords.
- Fix a potential crash in the redefine-in-handler warning if the redefined name is a nested getattr node.
- Add a new option for the multi-statement warning to allow single-line if statements.
- Add ‘bad-context-manager’ error, checking that ‘__exit__’ special method accepts the right number of arguments.
- Run pylint as a python module ‘python , ‘non-iterator-returned’, for non-iterators returned by ‘__iter__’.
- Add new checks for unpacking non-sequences in assignments (unpacking-non-sequence) as well as unbalanced tuple unpacking (unbalanced-tuple-unpacking).
- useless-else-on-loop not emited ‘exec’ function
- New –msg-template option to control output, deprecating “msvc” and “parseable” output formats as well as killing –include-ids and –symbols options
- Do not emit [fixme] for every line if the config value ‘notes’ ‘class ‘old ‘disable-all’ inline directive in favour of ‘skip preceeded ‘sym ‘l’ emited: ‘ ‘Expression “ ‘no’
-: ‘NoneType’ object has no attribute ‘name’, ‘W ‘load ‘–parseable’, path are written relative to the current working directory if in a sub-directory of it (#9789)
- ‘p | https://pylint.pycqa.org/en/1.6.0/whatsnew/changelog.html | CC-MAIN-2021-49 | refinedweb | 2,608 | 51.44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.