text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Hello everyone,
This is a mix between discussion and a post, if you don't agree with me, I hope you write a comment and hopefully change my mind as long the point changes my views. I have recently done project, and I need a UI, I don't need UI to be fancy or production ready, I want it to be simple, and when I do decide to change I should still be able to make it production ready.
Fetching from API
To fetch a data from API, I don't expect people to write
fetch calls, they shouldn't be going to documentation and trying to find out how to make the call, what is the url, what parameter is going to be used etc. That's just a implementation detail which no one cares for, I want developers to invest time in actually building a product rather than stare at a API documentation, in the interest of saving developer's time, I always prepare/generate a API client.
I generally use swagger to document my API, and I generate clients for most of the language, however for typescript, I use
@crazyfactory/tinka, this supports middleware, mocking, testing, caching etc, I haven't found anything which makes api calls better than this.
When I do need to make an API call, here's what I do:
const api = Sdk.getInstance(baseUrl); const response = api.profile.getById(userId); if (isError(response)) { // do something return; } // use the actual response
And because everything is in typescript, I get full typescript features everywhere.
Now consumer of Sdk, never has to look at API documentation, just use your IDE, which shows what you need.
Normally for a large project where I want to ensure it's a very solid project, I create a separate package and use
semantic-release to create releases automatically with proper semantic versioning, if you don't know what this is, have a look at semantic-release project.
But in my case, I just created a directory called Sdk and wrote everything there. Here's a PR which introduced it:
If you follow that PR you'll notice that I'm using the tinka package, and adding Sdk methods, and because everything's typed, consumer of this Sdk, (which is this project itself), will never have to worry about what method it's using, what URL it's hitting etc. Now obviously I could generate a client using autorest, but I couldn't find a generator which supported middlewares (I'll need middleware support).
Storing data (React is a View layer, don't fetch / store data in a view layer)
Now that fetching data is out of the way, let's talk about storing data.
I treat React as a view library, even though they're planning on introducing API calls with suspense soon.
One thing I really hate when I review someone's code, they simply go to
componentDidMount (or
useEffect), and make a api call, or they have hooks which makes the API call and put it on state.
IMO, this is a NO-NO, why would you access data from your view layer, have you ever queried a database from your view layer in any other MVC frameworks? Should you?
For that reason I've a different layer, I call it side effect layer, I use redux-saga for managing side effects this let's me keep my view and logic completely separate, in theory, if someone decided that I needed to ditch react for something else, in this situation I technically can, because again, React is just a view layer.
I keep data on redux and if say some day I happen to say I don't want to redux for data storage and want to move to mobx, I still can. They're not glued together.
Here's how I do this:
I've a page which needs data from API call, on it's componentDidMount (or useEffect, I'll come to this later), I check if I already have data available on store, if I do, then I don't do anything.
But if I don't have any data on store, then my componentDidMount will dispatch a action
SOME_DOMAIN/FETCH_DATA (or something similar), it dispatches this, and my side effect layer notices this (redux saga has ability to listen to actions and call a method when it happens) on that call, I call API using the Sdk I mentioned before, and set the data on redux.
There's a side effect to this, how many times have you tried to do setState on a unmounted component? Say user goes to a page and immediately navigates away from that component, then you get a warning from react saying that's wrong, also you now can't re-use that data anymore, when user comes to the component, you make the api call again.
Because redux and redux-saga are different layers, that problem is not there anymore (and you can test your redux, redux-saga and your component separately, and writing tests are easier).
If you had done a fetch call inside a component, you'll end up with one messy component, and a very dreadful set of tests (worst if you decide to test after the code is done)
So I don't think you should keep data on your view layer, I also don't think you should make any calls from your view layer and I certainly don't think you should mix all of them on same layer.
The PRs I linked to, and the project I've linked to, neither of them is a gold standard, I know that, had I enough time, and had this project needed to be that way, I certainly would have spent a bit more time to separate Sdk into whole another npm package, same thing with components, I could have used a higher order component to give the color values and made the whole thing themeable, but that's not for today.
Let's talk about redux hooks
I've seen people jumping on this hooks' train left and right, let's talk about redux hooks first.
When you
useSelector on your component, you basically glue your component to redux, view layer and data layer is very tightly coupled, and that's not what you want in a production ready app, I personally don't even want it on a throw away app, is calling connect function really that difficult?
And I've heard this argument before, "How about we create a Wrapper component which calls the useSelector and passes them down to components which needs them", to that I say you just implemented
connect component, it's basically the same, except you'll want to do it for every component, if not, it's just another
connect.
And with redux hooks, now you have to mock your redux store, which is a whole other story.
Remember, you really don't want to glue your view and data layer. I keep the concerns separate, and when you do use redux hooks your component violates a lot of SOLID principles.
It certainly violates single responsibility principle, because it's now communicating with your redux layer,
It also violates open for extension and closed for modification principle, Now that you've used redux hooks, you can't extend it in anyway, you're actually tied to redux layer, and that's it. Take these two component for example:
const Component: React.FC<IThemeProp> = (props) => { return ( <div style={{padding: 10, background: props.theme.background, color: props.theme.color}}>{props.children}</div> ); }; export const Alert = withTheme(Component);
export const AlertWithHook: React.FC = (props) => { const theme = useTheme(); return ( <div style={{padding: 10, background: theme.background, color: theme.color}}>{props.children}</div> ); };
The above examples are just simple react hooks, but let's take them as an example,
The first component which doesn't use hooks, can be extended easily, you can just use the component without the theme, and personalize it.
The second component however, is already tied with a certain context, and there's nothing you can do to change the second component with hook.
Another thing, the first component is a pure component (without the higher order component), for same input, it always returns same output, but the second one with hooks, isn't a pure component, it actually depends on what hook returns, which is a side effect, I generally tend not to go that way.
Performance and functional vs classes
First off, I always prefer functional components for smaller components, if a component is getting big, probably time to break them down to smaller components.
Facebook also says, don't go and change your existing class components and change to functional, there's no need for that, (but people being people, have started rewriting libraries), I'm not doing that.
Another thing is people say with hooks, you get performance boost. I don't think that's the case, let me tell you why.
I think the hooks create another side effect which is all your components are functional, and functions are faster than classes, the performance boost isn't coming from hooks, but the fact that you have functional components.
What I prefer is to have smaller functional components, and when it comes to larger components which might have logic, or needs multiple handlers, I tend to have them as a separate method, after all, I can actually do OOO.
Discussions welcome
I'm sure I might have missed some points, and there are so many things I wanted to communicate, but don't have the time to write about and don't want to extend the post too long.
Please raise your concerns in a way we can talk about, and if you don't agree, let me know why you don't agree, if you do, can you elaborate why you feel that way? I feel like there are some things my instincts tell me are dirty, but I can't actually explain them.
Discussion (6)
I already worked with class and redux free react application, and seems quite useful. If we find the right balance of our state, then useReducer is enough. Without any useContext. For complex side effect handling, I was use saga: npmjs.com/package/use-saga-reducer that is also fit for hook works. My another favourite js library is github.com/callbag/callbag great in side effect handling too.
what I meant is, as soon as you mix ui and data (if you use useSagaReducer), you're doing just that, but again, if that works for you then good for you :)
In my mindset react as view layer means view component don't handle any data, just represent props, and call actions for interaction. One or many useReducer / useReduceSaga organise business logic, and works with state. So I have few controll component / program.
well, IMO, as soon as you use any of the hooks from redux, like useSelector, (honestly, we've banned them in our linting rules, so I don't even know what hooks are available from redux), but as soon as you do that, your components gets glued together with data, sure, logic is in different file, doesn't mean it's still separate, you used it in a way that I can't re-use your component without using that hook.
But again, let me reiterate, if that works for you, it's good, for me, I don't like that even one bit, when you mix your view with data, that's a problem,
when you use component, the original component is still not really glued with redux, because your connect hoc does the glueing part, which means say you don't want to use redux anymore, you can.
But as soon as you useSelector from redux, then you're stuck with redux forever, (unless you change so many places)
Also btw, I don't use redux-saga the way it's shown in example, the reason is that there's handling of dependency correctly, say you want an API client, you don't want to have to create a client in every saga file, they have recommended to use what pattern works, use just that one, I use the OOP way, here's an example:
github.com/crazyfactory/ts-react-b... (registers all sagas)
github.com/crazyfactory/ts-react-b... (base class which all sagas implement, and it makes sure we get the dependency we need)
github.com/crazyfactory/ts-react-b... (example of a saga which fetches an API call)
On that boilerplate, we're not doing Sdk, so dummyApi is being called directly, BUT, when you do have api, you define that as dependency on your BaseSaga, and a instance of sdk will be passed (I'm finishing up a project where I'll be doing this, I'll give you that link once I have it. :)
You can use saga capability with useSagaReducer without redux ( I don't use redux ). In that way you can use saga same simply way as use useReducer. And you right if you put hook in any component, you can't use without that. But I think if you write your components without any outer dependency, and all date and action come from props, then your components can be reused, don't mother if you use state, or saga driven side effects inside of them.
I agree that we need to separate two layers of side-effects (rendering & dynamic data), however, functional programming paradigm is very different from MVC and OOP. SOLID principles do not make too much sense in functional world, so it is difficult to criticize redux hooks based on SOLID. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/cyberhck/let-s-talk-about-how-react-is-only-a-view-layer-5gg1 | CC-MAIN-2022-27 | refinedweb | 2,301 | 58.96 |
Questions:
1..
Explanation:
Below mention code is compiled in Visual Studio 2015 and Code Blocks 13.12,output snap is attached.. If any problem you feel and you want some explanation feel free to contact us.
Code:
/**************************************************|
/*************C++ Programs And Projects************|
***************************************************/
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "What is your first name? ";
string firstName;
getline(cin, firstName);
cout << "What is your last name? ";
string lastName;
getline(cin, lastName);
char grad;
cout << "What letter grade do you deserve? ";
cin >> grad;
grad = grad + 1;
cout << "What is your age? ";
int age;
cin >> age;
cout << "Name: " << lastName << ", " << firstName << endl
<< "Grade: " << grad << endl
<< "Age: " << age << endl;
return(0);
}
Output:
Related Articles:
0 Questions: | http://www.cppexamples.xyz/2016/04/write-c-program-that-requests-and.html | CC-MAIN-2018-30 | refinedweb | 113 | 74.69 |
The problem
Given an array of strings
arr. String
s is a concatenation of a sub-sequence of
arr which have unique characters.
Return the maximum possible length of
s.
Example test-cases
Constraints
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i]contains only lower case English letters.
How to write the code
def maxLength(arr: List[str]) -> int: result = [float('-inf')] unique_char("", arr, 0, result) if not result[0] == float('-inf'): return result[0] return 0 def unique_char(cur, arr, index, result): # End of the array if index == len(arr): return # Iterating from the current word to the end of the array for index in range(index,len(arr)): # If current word + next word have all unique characters if len(set(cur + arr[index])) == len(list(cur + arr[index])): # Compare the actual lenth with the previous max result[0] = max(result[0],len(cur + arr[index])) # Make a new call with concatenate words unique_char(cur + arr[index], arr, index + 1,result)
doesn’t work
Hi Jeremy,
What about the solution doesn’t work?
Depending on your Python version, you may need to change :
to: | https://ao.gl/get-the-maximum-length-of-a-concatenated-string-with-unique-characters-in-python/ | CC-MAIN-2020-45 | refinedweb | 188 | 60.55 |
>>>>> On Sat, 11 Mar 2006 14:09:22 +0200, Eli Zaretskii <address@hidden> said: > Yes, and then all the callers of mac_draw_rectangle except > x_draw_hollow_cursor need to subtract 1 from width and height. > Funny. > I modified mac_draw_rectangle to not add 1 to these two dimensions, > and then removed the decrements from its callers. Hmm, I'd rather prefer to keep the arguments compatible with the X11 version so as to make synchronization easy. >>. Not installed yet. I was planning to make the change like this: /* Mac replacement for XDrawRectangle: dest is a window. */ static void mac_draw_rectangle (f, gc, x, y, width, height) struct frame *f; GC gc; int x, y; unsigned int width, height; { #if USE_CG_DRAWING CGContextRef context; context = mac_begin_cg_clip (f, gc); CG_SET_STROKE_COLOR (context, gc->xgcv.foreground); CGContextStrokeRect (context, CGRectMake (x + 0.5f, y + 0.5f, width, height)); mac_end_cg_clip (f); #else Rect r; SetPortWindowPort (FRAME_MAC_WINDOW (f)); RGBForeColor (GC_FORE_COLOR (gc)); SetRect (&r, x, y, x + width + 1, y + height + 1); mac_begin_clip (gc); FrameRect (&r); /* using foreground color of gc */ mac_end_clip (gc); #endif } So, if the callers does not subtract 1 from width and height, then the callee need to do so when USE_CG_DRAWING == 1. That's another reason why I'd prefer to keep the meaning of the arguments. YAMAMOTO Mitsuharu address@hidden | http://lists.gnu.org/archive/html/emacs-devel/2006-03/msg00431.html | CC-MAIN-2016-40 | refinedweb | 211 | 61.46 |
Run One Program at any Scale with Legate
Python is one of the most used languages today, particularly in machine learning. Python itself doesn’t have a numerically focused data type, so NumPy was created to fill that void, adding support for large, multidimensional arrays and matrices, as well as contributing a good collection of math functions for these arrays and matrices.
NumPy
Most people who code in Python have seen or written NumPy code, but just in case you have not, this quick example creates an “empty” 2D array of size nx by ny:
import numpy as np nx = 10 ny = 10 a = np.empty((nx,ny)) type(a)
Array a is of data type numpy.ndarray, with which you can do all sorts of things, including adding, subtracting, multiplying, and performing other mathematical operations. Another example is to solve the linear equation, Ax = b:
import numpy as np nx = 100 ny = 100 a = np.random.rand(nx,ny) b = np.random.rand(ny) x = np.linalg.solve(a, b)
Array a and the second part of the tuple, b, are created by a random number generator with random samples from a uniform distribution over [0,1). The equation is then solved by the solve routine.
NumPy on GPUs
NumPy functions are all single threaded unless the underlying NumPy code is multithreaded. GPUs are monsters for matrix computations, but NumPy itself does not run on GPUs. CuPy was created as an almost complete NumPy-compatible library that runs on GPUs. Most routines use a single GPU for running code, although porting functions to use multiple GPUs requires work. CuPy is even adding functions from SciPy to its codebase. As with NumPy, CuPy is open source.
CuPy code looks virtually identical to NumPy code:
import cupy as cp nx = 10 ny = 10 a = cp.empty(nx,ny) type(a)
Notice that the CuPy data type is different from NumPy because it is specific to the GPU. However, commands can move data back and forth to the GPU, converting data types for you.
As mentioned previously, you can run almost any NumPy code with CuPy. The second NumPy example is written as CuPy:
import cupy as cp nx = 100 ny = 100 a = cp.random.rand(nx,ny) b = cp.random.rand(ny) x = cp.linalg.solve(a, b)
To run NumPy code on GPUs with CuPy, you need to change your code. Generally, it is not difficult to port most NumPy code to CuPy. Mixing NumPy and CuPy requires extra coding to move data back and forth while paying attention to data types and data location, which increases the amount of code and adds complexity. Moreover, without careful coding, the code would no longer be portable because it needs a CPU and a GPU. | https://www.admin-magazine.com/HPC/Articles/Run-One-Program-at-any-Scale-with-Legate/(tagID)/665 | CC-MAIN-2022-21 | refinedweb | 463 | 63.7 |
IOS XR run multiple policies
Hi,
on IOS 15.1 with eem version 3.2 the default setting for the number of parallel tcl policies that can run is one.
There is the command "event manager scheduler script thread class <name> number <#>" to change the number of scripts that can be executed in parallel.
I could not find a similar command on IOS XR, does somebody know the default value there and maybe a command to change it? In addition there is also no "show event manager version" command, which version of eem is available on IOS XR? The IOS XR version I used is 4.1.2
Thanks for any advice
There is no equivalent in IOS-XR. Last time I did a big IOS-XR project, I found that one policy would run at a time. However, you could test that. Register this script, then run it multiple times in parallel from different VTYs.
::cisco::eem::event_register_none
namespace import ::cisco::eem::*
namespace import ::cisco::lib::*
action_syslog msg "I'm here"
after 10000
action_syslog msg "After a good sleep, still here"
If they are running in parallel, you should see multiple "I'm here's" before you see the second message.
IOS-XR doesn't support a version of EEM equivalent to IOS. However, if I had to give you a version, I would say, it's like EEM 2.1. | https://supportforums.cisco.com/discussion/11588931/ios-xr-run-multiple-policies?tstart=0 | CC-MAIN-2014-15 | refinedweb | 232 | 72.76 |
ClassyPrelude: The good, the bad, and the ugly
August 3, 2012
Michael Snoyman
First a message from our sponsors: Yesod 1.1 is fully tested and ready for release. I'm holding off until the beginning of next week, since I hate making major releases on a Friday (if there are any bugs, I won't be around on Saturday to fix them). If you're really eager to check it out, you can get the latest and greatest from Github.
I promised to write this blog post a week or two ago, but never got around to it. Dan Burton reminded me about it yesterday... so here's paying off my debt :).
So far, most of the discussion around classy-prelude has focused around the "classy" bits. As Felipe mentioned a few weeks ago, there's a lot more going on than just the classy parts. So I'd like to break open the discussion more and explain what exactly is going on.
Before we start, I think I need to give a bit of an explanation of my development strategy, as I think some people don't understand my approach. When attacking a problem for the first time, I throw in the kitchen sink. Many people prefer to take a more iterative approach, adding features one step at a time after a lot of careful testing. And in many cases, I think that's the only valid approach.
But for a project like
classy-prelude, I'm interested in being much more
experimental. That means I'm happy to throw in some half-baked ideas to see if
they work. Don't mistake that as me saying I fully endorse and recommend this
approach. On the contrary, as I hope this post makes clear, I'm highly
skeptical of some the choices I made. But I'm also a firm believer that we
won't know if the choices were bad unless we try them out.
So without further ado, let's break down the
classy-prelude, starting with
the "obvious good" category and moving further into the unknown. (And I think
it goes without saying that statements like "obviously good" are subjective.)
Win: Full compatibility with standard libraries
I saw the contrary claim made many times in various discussions, so let's put
it to rest. Unlike other prelude replacements,
classy-prelude does not try
to fix flaws in the base package.
Functor is not a superclass of
Monad,
fail still exists, and
Num is unchanged. That's not to say that I think
that the base package did everything correctly (I don't), but rather, by
sticking to the standard typeclasses,
classy-prelude code should work with
any existing library without a hitch.
From a user perspective: you should be able to use
classy-prelude in one
module, ditch it in another, depend on some packages that use it and others
that don't, without any problem. In fact, I've done exactly that in some of my
code. If you use
classy-prelude in your library, your library users should
not be affected beyond the fact that they have to install
classy-prelude.
As an aside, I'd like to see some of those bigger changes make it into base
ultimately, and I think an alternate prelude is a great way to play around with
the ideas. But such an alternate prelude wouldn't be much use for real-world
use, which is why I haven't taken that route with
classy-prelude.
Win: Don't export partial functions
I really wish
Prelude didn't export
head,
tail, and a bunch of other
partial functions. So
classy-prelude doesn't. More generally, I've been
taking a whitelist approach to which
Prelude functions are exported. If I've
left out one of your favorite functions, it's likely because I just didn't get
around to it yet, not due to any hatred of it. If there's some total function
in
Prelude that you'd like added, just send a pull request.
Win: Export commonly used functions from other modules
I prefer using
<$> to
fmap in most circumstances. I like to use
first and
&&&, and a huge number of my modules import
mapMaybe. All of these
functions/operators have names that are well recognized in the community, I
believe are unambiguous, and are very generally useful. Since the main purpose
of
classy-prelude is to save you from extra keystrokes, let's just export
them all by default.
The selection here is clearly going to be pretty opinionated. And the list isn't really that exhaustive right now (again, pull requests welcome). But while we can argue over exactly which functions should be exported, I think this is a pretty solid advantage.
Win: Export datatypes
How many modules have you written with lines looking like:
import Data.ByteString (ByteString)
And how many times do you just import
Data.ByteString qualified and use
S.ByteString? How often is
ByteString imported from
Data.ByteString.Lazy
instead? And do you make the alias for the module
S or
B?
These are all thoroughly uninteresting questions. Typing out the code is
boring. And trying to remember which convention is used in the particular
module you're working on is just a pain. So in
classy-prelude, we have a
simple convention: export the datatype. If there's a lazy variant, prefix it
with
L. So we end up with
ByteString,
LByteString,
Text,
LText,
Map,
HashMap, and so on.
There's nothing earth-shattering here. It just removes an annoyance.
Probably a win: Generalize using existing typeclasses
I like
Monoid a lot. I think it's a great typeclass. And I think it's a shame
that in
Prelude,
concat only works for lists and not arbitrary
Monoids.
Similarly, I wish that
++ was just
mappend. So in
classy-prelude, I've
done just that.
This is a bit controversial, because it can make error messages a bit more
confusing. But let me reinforce something that I probably didn't clarify
enough:
classy-prelude is not intended for beginners. I don't think that a
Haskell tutorial should be using it for examples.
classy-prelude is intended
for Haskellers who are already battle-tested with GHC's error messages, and
won't shy away from some more general types.
One change I didn't make, but was considering, was using
. and
id from
Control.Category. I'm not sure how much of a practical benefit that would
provide people, while making error messages likely much more complex. But if
people want that change, let's discuss it.
More debatable win: recommend better datatypes
I've gone on record many times saying that I dislike
type FilePath = [Char].
system-filepath is
(yet another) wonderful package by John Millikin, and I use it extensively in my
personal code. (It's also making its way more solidly into the Yesod ecosystem,
though we frankly don't do that much filesystem access in Yesod.)
In
classy-prelude, I export
system-filepath's
FilePath type. This is
likely the most "breaking change" we have, though it doesn't really prevent you
from continuing to use
[Char] for all your filepaths.
classy-prelude also
exports a bunch of the functions and operators for manipulating filepaths, like
basename and
</>.
Again, this is an opinionated decision. But I think moving over to
system-filepath could be a huge win for the Haskell community in general, and
regardless of
classy-prelude's future, I hope it catches on.
More controversial: create a bunch of new typeclasses
Now we get to the fun stuff.
classy-prelude defines a bunch of new
typeclasses for functions which are commonly imported qualified. I mentioned it
previously, but I don't think my point got across, so I'll say it again. The
purpose here has nothing to do with equational reasoning. This is purely a
technique for name overloading, nothing more.
Let's expand on that a bit. One of the nice things about typeclasses is that
they are usually associated with a set of laws that define their behavior. This
lets us write code against a typeclass and know, based on the laws, how it will
behave. We don't need to know if we're dealing with a list of a
Set, we know
that
mappend empty foo is the same as
foo.
That's not my purpose here. The purpose is purely about name overloading. I
haven't stated a semantics for what
lookup needs to do, because the answer is
it depends on the container. This means that
classy-prelude is not
decreasing the cognitive load of the programmer in any meaningful way. If there
are semantic differences between the
insert functions for a
HashMap and a
Map, you still need to know about them. (To my knowledge, no such difference
exists.)
So let's say it again: the only purpose for this technique is to allow name overloading.
Based on this, I think it's fair to claim that
classy-prelude doesn't make
code more buggy due to its lack of associated laws. The libraries you're using
already don't conform to a set of laws.
classy-prelude is just making it
easier to use them. If you write type-generic code and try to use it for
multiple container types (not a practice I recommend), it's possible that
you'll get buggy code due to semantic differences. But the same applies if you
write a function using
Data.Set, copy-paste it, and then replace
Data.Set
with
Data.HashSet.
All that said, I'm not saying that a set of associated laws isn't a good thing.
I'd love to add them. And if
classy-prelude continues, I'm sure we will add
them. But for the initial proof-of-concept experimental release, I don't think
it was worth the investment of time.
One final idea here is to leverage some existing collections of typeclasses (Edward Kmett's reducers package in particular) instead of defining our own typeclasses. Again, for the proof-of-concept, that idea was premature, but going forward I'm hoping to look into it. There are obstacles we'd have to overcome (like ensuring good performance), but I don't think anything is insurmountable.
Very controversial: make those typeclasses work with
conduit
I was surprised not to see as much of a discussion about this point as the
previous one. In my mind, this was by far the most controversial choice in
classy-prelude. It's fair to say that I put it in more out of curiosity if it
would work than anything else.
Let's take
filter as an example. A relatively simple typeclass to model it
would look like:
class CanFilter container element | container -> element where filter :: (element -> bool) -> container -> container
This would work for lists,
ByteString,
Set, and so on. However, here's the
(simplified) signature of
filter from
Data.Conduit.List:
filter :: (i -> Bool) -> Conduit i m i
This doesn't fit in with our
CanFilter class above.
CanFilter has a
function that takes two arguments, whereas in
conduit
filter has just one
argument.
So here's the trick. We recognize that the first argument is the same (a
predicate), and just leverage currying. Recognizing that
CanFilter's
filter
can be viewed as a function of one argument returning a function, we split it
up into two typeclasses:
class CanFilter result element where filter :: (element -> bool) -> result class CanFilterFunc container element | container -> element where filterFunc :: (element -> bool) -> container -> container
And then we define a single instance of
CanFilter that uses
CanFilterFunc
for all cases where we return a function:
instance (container ~ container', CanFilterFunc container element) => CanFilter (container -> container') element where filter = filterFunc
(If you're curious about the equality constraint, see this excellent Stack Overflow answer.)
We can then separately define an instance for
conduit, which does not overlap
at all, and allows us to reuse the name
filter in significantly different use
cases. Frankly, I think it's pretty cool that we have this kind of flexibility
in the type class system. But from a practical standpoint, I'm not sure it's
really a great trade-off:
Since the two
filterconcepts work fairly differently, it may be more confusing than anything else to lump them together.
Error messages get significantly more confusing.
I don't think that
conduitusage in this sense is prevalent enough to warrant the costs.
In other words, if there's something I'd want to cut out first from
classy-prelude, it's the gymnastics which it pulls to accomodate
conduit
instances. It was definitely a fun part of the experiment, and I'm glad to have
tested it. If anyone has an opinion either way on this, let me know.
Moving forward
There are a number of minor bugs in the typeclass definitions in
classy-prelude, requiring more explicit type signatures than should be
necessary in some cases. Those kinds of things are easily fixed. If people find
specific examples, please bring them to my attention.
Dan Burton started a project called
ModularPrelude
which takes a different approach to the namespace issue, replicating first
class modules via the record system. I think it's definitely an interesting
approach, and think it can coexist very well with
classy-prelude. But it's
not enough for my taste: I prefer the relative terseness of typeclass-based
code.
However, putting that project together with my points in this post, I think
it's important to note that there is a very large part of
classy-prelude
which has nothing to do with typeclasses. Dan called this
BasicPrelude.hs,
and I think it makes a lot of sense to provide that separately (though at least
for now, I'll keep it in the same package for convenience).
The idea is simple: I think a lot of people agree with me that some major
aspects of this prelude are no-brainers, and would like to use them. People are
understably more wary of the experimental bits. (As I've said before, so am I:
I won't allow
classy-prelude to be used in
yesod in its current state.) So
let's create a stable basis, and encourage experimentation. As I mentioned at
the beginning, since we have full compatibility with
base, there's no real
concern of fragmentation.
Once I remove the
conduit aspects of the library, I think it will open it up
for much better analysis of typeclass laws. It might be possible to completely
drop a number of typeclasses and use the
reducers versions instead. For
others, more experimentation might be necessary.
And as usual: feedback is welcome, especially the constructive kind :). | http://www.yesodweb.com/blog/2012/08/classy-prelude-good-bad-ugly | CC-MAIN-2015-22 | refinedweb | 2,466 | 63.59 |
C Tutorial
Control statement
C Loops
C Arrays
C String
C Functions
C Structure
C Pointer
C File
C Header Files
C Preprocessors
C Misc
Using #include preprocessor directive
The #include preprocessor directive tells the compiler to include the code inside given file before compiling rest of the program. So, we can tell that this #include preprocessor includes the code of given file to the current file in which we are working.
For easily understand the function of #include preprocessor let’s take an example. Suppose we have a file named myfile.h in the same directory in which we are working now. And inside the file we have written the following code.
myfile.h
int sum(int a, int b){ int total = a + b; return total; }
Now, if our current file with .c extension in which we are working contains the following code.
#include <stdio.h> #include "myfile.h" int main(){ int x, y, result; x = 20; y = 30; result = sum(x, y); printf("%d\n", result); return 0; }
Then the compiler will include the code inside myfile.h before the main program and the file will be as like as following.
#include <stdio.h> int sum(int a, int b){ // code from myfile.h int total = a + b; return total; } int main(){ // main program int x, y, result; x = 20; y = 30; result = sum(x, y); printf("%d\n", result); return 0; }
Although we can write any code inside our created header file but it is not recommended as this practice is very confusing as well as error prone.
A header file can contains any portion of our C program although they are typically contain variable and function declarations as well as macro definitions in our program.
Method of using #include preprocessor directive in C
We can use #include preprocessor directive in two ways as like as following;
// two way of using #include preprocessor directive #include <file_name> #include "file_name"
#inculude : It tells the compiler to include the file from where the system header files are located.
#inculude “file_name” : It tells the compiler to include the file from the current directory in where we are working now. | https://worldtechjournal.com/c-tutorial/has-include-preprocessor-directive/ | CC-MAIN-2022-40 | refinedweb | 358 | 58.21 |
c++ standard and file extenstions (.hpp, .H, .hxx)
Discussion in 'C++' started by whit, Mar 19, 2009.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
Abstract Class Extenstions Not exactly working as I would expect.Michael Boocher via JavaKB.com, May 26, 2005, in forum: Java
- Replies:
- 8
- Views:
- 576
- John McGrath
- May 30, 2005
#include <boost/shared_ptr.hpp> or #include "boost/shared_ptr.hpp"?Colin Caughie, Aug 29, 2006, in forum: C++
- Replies:
- 1
- Views:
- 939
- Shooting
- Aug 29, 2006
Difference between *.hxx and *.h header files?Mark Sullivan, May 17, 2008, in forum: C++
- Replies:
- 27
- Views:
- 5,744
- James Kanze
- May 21, 2008
What is the difference between .cpp + .h vs .cxx and .hxx ?Patrick Brehmer, Nov 27, 2008, in forum: C++
- Replies:
- 9
- Views:
- 8,444
- $B3Y?.L@(B
- Dec 5, 2008
REGEX (Not allowing file extenstions) or the dotGuest, Oct 4, 2003, in forum: Perl Misc
- Replies:
- 8
- Views:
- 230
- sts
- Oct 5, 2003 | http://www.thecodingforums.com/threads/c-standard-and-file-extenstions-hpp-h-hxx.676353/ | CC-MAIN-2016-07 | refinedweb | 196 | 83.66 |
Created on 2010-09-04 00:01 by kevinpt, last changed 2017-03-31 16:36 by dstufft. This issue is now closed.
The isblank() function defined in curses.ascii is incorrect and doesn't match the output from C's isblank() from ctype.h
Incorrect definition:
def isblank(c): return _ctoi(c) in (8,32)
Should be:
def isblank(c): return _ctoi(c) in (9,32)
This most likely affects all versions of Python, not just 2.7.
The problem and fix are simple but who is best placed to take a look at this?
I've fixed isblank to accept tab instead of backspace and added tests
for character classification functions from curses.ascii module that
have corresponding analogs in ctype.h. They've uncovered issues in
isblank, iscntrl, and ispunct functions.
Open questions:
- is it a security bug (backspace is treated as tab in isblank())?
If it is then 3.1, 3.2, 3.3 branches should also be updated
[devguide]. If not then only 2.7, 3.4, and default branches should
be changed.
[devguide]:
- iscntrl() mistakenly returns false for 0x7f but c11 defines it as
a control character. Should iscntrl behavior (and its docs) be
changed to confirm? Should another issue be opened?
- ispunct() mistakenly returns true for control characters such as
'\n'. The documentation says (paraphrasing) 'any printable except
space and alnum'. string.printable includes '\n' but 'printing
character' in C11 does not include the newline. Moreover
curses.ascii.isprint follows C behavior and excludes control
characters. Should another issue be opened to return false from
ispunct() for control characters such as '\n'?
- ispunct() mistakenly returns true for non-ascii characters such as
0xff
- negative integer values: C functions are defined for EOF macros
(some negative value) and the behavior is undefined for any other
negative integer value. What should be curses.ascii.is* predicates
behavior? Should Python guarantee that False is returned?
- curses.ascii.isspace/.isblank doesn't raise TypeError for bytes,
None on Python 3
- should constants from string module be used? What is more
fundamental: string.digits or curses.ascii.isdigit?
- no tests for: isascii, isctrl, ismeta (they are not defined in
ctype.h). It is unclear what the behaviour should be e.g., isascii
mistakenly returns True for negative ints, ismeta returns True for
any non-ascii character including Unicode letters. It is not clear
how isctrl is different from iscntrl.
I've made the title more explicit: "curses.isblank function doesn't match
ctype.h" -> "curses.ascii.isblank() function is broken. It confuses
backspace (BS 0x08) with tab (0x09)"
If a core developer could review the open questions from the
previous message msg221008 then I could prepare a proper patch for the
issue.
Most issues was fixed in issue27079. Except handling negative integers. Following patch fixes the latter issue.
New changeset cba619a7bf6a by Serhiy Storchaka in branch '3.5':
Issue #9770: curses.ascii predicates now work correctly with negative integers.
New changeset 84ca252ac346 by Serhiy Storchaka in branch '2.7':
Issue #9770: curses.ascii predicates now work correctly with negative integers.
New changeset eb81f2d2a42b by Serhiy Storchaka in branch '3.6':
Issue #9770: curses.ascii predicates now work correctly with negative integers.
New changeset 1c0b72996e60 by Serhiy Storchaka in branch 'default':
Issue #9770: curses.ascii predicates now work correctly with negative integers. | https://bugs.python.org/issue9770 | CC-MAIN-2019-43 | refinedweb | 553 | 61.53 |
Status Update Yii 2
#1
Posted 10 September 2012 - 06:47 PM
#2
Posted 11 September 2012 - 04:32 AM
#3
Posted 11 September 2012 - 05:24 PM
#4
Posted 12 September 2012 - 07:31 AM
#5
Posted 10 October 2012 - 03:08.
#6
Posted 10 October 2012 - 03:36 AM
#7
Posted 10 October 2012 - 03:47 AM
#8
Posted 10 October 2012 - 04:07 AM
"Soon!"
But to be serious: Just because a project exceeds a "sort of planned/guessed date" doesn't mean it will fail, although, that's what a lot of people feel and because of that companies tend to publish software that's not ready yet (see Microsofts Win 2000, Vista etc.) just to please their customers. I am glad to see that the opposite is true for Yii. Qiang is focused on quality, not on due dates and that is important (and he's too experienced to be infected by "featuritis" I guess).
So don't stress the team, give them the time they need to do their job
>
#9
Posted 10 October 2012 - 05:45 AM
ekerazha, on 10 October 2012 - 03:08 AM,.
I've got to disagree, software goes through planning phase where enhancements are planned and implemented. Really the only thing they are guilty of is communication. What needs to happen is the entire planning process needs to be logged somewhere (preferable a wiki/tracking type system) so people can see what is planned and maybe even offer suggestions, forum is getting a little cluttered.
Then at some point the 2.0 release needs to be locked (so all confirmed changes will be done) and no more can be suggested. This usually will be the alpha for suggestions, beta for bug fixing with minor improvements, rc bug fixes only, final. This is a typical software development process, i would said Yii's still in the alpha stage.
Quote
#10
Posted 10 October 2012 - 06:56 PM
Some items were listed as 'to be done' at that time. Which ones are done? Is the bulk of the development done yet, or are there some time consuming topics to be started later on? Have you started testing with the goal to release the framework (alpha version) or are you still developing additional functionality? Do you already have a release date/month for the alpha version in mind?
Don't take me wrong, I don't want to stress the team (as Haensel suggested). Instead I'm looking for information.
#11
Posted 10 October 2012 - 10:10 PM
ekerazha, on 10 October 2012 - 03:08 AM, said:
I agree with Haensel and Jaggi. The core team never suffered from feature creep, they won't start doing it now. I'm sure that they're taking care of good design and quality.
The time they're taking to get Yii 2.0 to the first development release is the time that is needed to be taken.
#12
Posted 10 October 2012 - 10:49 PM
POPULAR
As I have explained before, Yii 2 is not a simple translation of Yii 1 with namespaced classes. We are trying to make Yii 2 something that you feel right about in nearly every detail. We are not adding many new features. Instead we are mainly redesigning existing classes so that they are easier to use and more flexible to customize. It often takes us a lot of time in thinking and discussion before we set to write code. Another factor affecting the progress of Yii 2 is our availability. Every core developer has his own business to take care of, and none of us is working full time on Yii (even though sometimes we do so as a matter of fact.)
#13
Posted 16 October 2012 - 09:54 AM
I hope only it will be retro-compatible with 1.1.12 because we'are working on a 3-year project .. and we'll want to keep updated all of our tools, Yii included.
Ricordalo quando fai il debug
#14
Posted 16 October 2012 - 10:13 AM
realtebo, on 16 October 2012 - 09:54 AM, said:
I hope only it will be retro-compatible with 1.1.12 because we'are working on a 3-year project .. and we'll want to keep updated all of our tools, Yii included.
It's already been stated there will be compatibility issues with 1.x and 2.x. So either way you will have to do some code migration to move from 1.x to 2.x. Hopefully there should be some good documentation to make that an easier process.
Quote
#15
Posted 17 October 2012 - 03:47 AM
#16
Posted 17 October 2012 - 04:00 AM
realtebo, on 16 October 2012 - 09:54 AM, said:
I hope only it will be retro-compatible with 1.1.12 because we'are working on a 3-year project .. and we'll want to keep updated all of our tools, Yii included.
My opinion is that a codebase change from V1 to V2 is so great, that its asking for troubles if you want to migrate. You'll probably need extensive testing to make sure your app works the same as before.
I recommend that you start to create Unit Tests (PHPUnit) and Functional Tests(Silenium) if you haven't already. That will help ease any migration process significantly.
#17
Posted 17 October 2012 - 06:01 AM
For function test,
silenium is actually studied from someone 'over' me. So it's not my decision.
But, please, go on documenting. I'm 100% sure we'll migrate 1.x to 2.0.
Ricordalo quando fai il debug
#18
Posted 05 March 2013 - 05:15 AM
#19
Posted 16 March 2013 - 09:20 AM
We've been planning a rewrite of one of our applications. Seeing as the rewrite would start within the next couple of months and would last around 4-6 months I had been thinking that we could wait for Yii2 alpha and then progress with our developments along side that of Yii2 (helping in the process with whatever issues there may be). And finally release our app after Yii2 final release.
Our dates aren't fixed as our current Yii 1.1.x based webapp does what it should (mostly). We can easily push our dates back a bit if that can prevent us from having to rewrite in Yii 1.1.x and then migrate to Yii 2 which would be painful (and probably take longer anyways)
So I was wondering if any of the Yii team could let me know if this planning of mine is doable or if I'm being delusional with the time frames. Obviously I'm not asking for any commitment to a date. I'm aware you want to do it right no matter the time, and that your availability is limited to get there. All I need to know is if I'm completely bonkers if I try and do it this way or if there is -some- likely hood it's doable.
#20
Posted 16 March 2013 - 09:28 AM
I would not hold off any new projects in anticipation of the alpha/beta release of Yii2 because I know that it's not going to be the final, bug-free version.
I also know that I can branch off my existing projects easily and perform the necessary Yii2 re-factoring in parallel to maintaining those projects.
So I would just start my new projects using Yii 1.x, and worry about Yii2 when it's relevant to do so. | http://www.yiiframework.com/forum/index.php/topic/35443-status-update-yii-2/page__p__175350?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024 | CC-MAIN-2015-27 | refinedweb | 1,269 | 71.34 |
Building the Lino Book¶
This page explains how to build the Lino Book, i.e. how to generate the html pages you are reading right now.
The Lino Book is static html which is visible at different places, e.g. at, at lino.readthedocs.io or (when you've built it) locally on your computer.
Theoretically it's easy¶
When your development environment is correctly installed as explained
in Installing getlino, then --theoretically-- it's easy to build the Lino
Book: you just run
inv bd in the root directory of your
book repository:
$ go book $ inv bd
This will tell Sphinx to read the .rst source files and to generate
.html files into the
docs/.build directory. Voilà.
If you get some error message, then you need to read the Troubleshooting section. Otherwise you can now start your browser on the generated files:
$ firefox docs/.build/html/index.html
Or jump directly to your local copy of this page:
$ firefox docs/.build/html/team/builddocs.html
Troubleshooting¶
.../docs/api/xxx.yyy.foo.rst:21:failed to import Bar¶
This can occur when you have an earlier build of the book on your
computer, then pulled a new version of some Lino repository (or made
some local code changes) and then run
inv bd again.
The error should disappear either if you manually remove the specified
file
docs/api/xxx.yyy.foo.rst. Or, most fool-proof solution,
you use the
inv clean command to automatically remove cached
and generated files:
$ inv clean -b
[autosummary] failed to import u'lino_book.projects.team.tests.test_notify'¶
This means that autosummary (which
in turn needs autodoc) has a
problem to import the module
lino_book.projects.team.tests.test_notify.
Indeed you can verify that importing this module in a normal Python session will fail:
>>> import lino_book.projects.team.tests.test_notify Traceback (most recent call last): ... ImproperlyConfigured: Requested setting SITE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
As the error message tries to explain, the module refuses to import
because
DJANGO_SETTINGS_MODULE is not set. That's related
to an oddness of Django (one of its well-known and widely accepted
oddnesses): you cannot simply import a module that imports
django when that environment variable is not set.
Note that the
docs/conf.py contains (among others) the
following lines:
from lino.sphinxcontrib import configure configure(globals(), 'lino_book.projects.max.settings.doctests')
This calls the
lino.sphinxcontrib.configure() function which
basically does exactly what we need here: it sets the
DJANGO_SETTINGS_MODULE to
lino_book.projects.max.settings.doctests.
So Sphinx uses the
lino_book.projects.max project when
generating the docs.
But your message says that something went wrong during all this.
Let's try this:
$ # cd to ~/projects/book/lino_book/projects/max: $ go max $ python manage.py shell
And in that Python shell you try to import the module which Sphinx was not able to import:
import lino_book.projects.team.tests.test_notify
What happens now?
Introducing Sphinx¶
Lino makes heavy usage of Sphinx, the dominant documentation system in the Python world. Sphinx is a tool that "makes it easy to create intelligent and beautiful documentation" and that "actually makes programmers want to write documentation!" ().
For example, the "source code" of the page your are reading right now is in a file docs/dev/builddocs.rst.
Read more about the markup used by Sphinx in reStructuredText Primer. Also The build configuration file.
Let's play¶
Let's play a bit:
Open the source file of this page:
$ nano docs/team/builddocs.rst
Edit something in that file and save your changes. Then build the book again:
$ inv bd
Then hit Ctrl-R in your browser and check whether the HTML output changes as expected.
You can undo all your local changes using:
$ git checkout docs/team/builddocs.rst
Or, if you agree to contribute your changes to the Lino project, you can submit a pull request as you would do with code changes. | https://lino-framework.org/dev/builddocs.html | CC-MAIN-2020-05 | refinedweb | 668 | 57.67 |
25 November 2011 16:08 [Source: ICIS news]
LONDON (ICIS)--Suppliers have agreed to substantial discounts on the price of Indian fertilizer imports which were requested after a sharp devaluation of the rupee, buyers in India said on Friday.
The Indian Farmers Fertiliser Co-operative Ltd (IFFCO) had called for diammonium phosphate (DAP) import prices to be dropped by $50/tonne, nitrogen-phosphate-potassium (NPKs) by $45/tonne and muriate of potash (MOP) by $36/tonne.
Importers said that Russian fertilizer producer PhosAgro had negotiated a 5% discount on cargoes of DAP due to be shipped until March 2012 under contract agreements.
This reduction would lower the established contract price of $677/tonne (€508/tonne) CFR (cost and freight) for DAP by $35/tonne to $642/tonne CFR.
PhosAgro was not available to confirm any agreement on the proposed discounts.
The depreciation of the rupee – which fell to a low of Rs52.1 against the US dollar – was increasing the cost of imports, which was then being passed to end users.
The higher retail price of DAP had pushed farmers to source cheaper alternatives and increasingly expensive imports threatened further maximum retail price hikes.
The call for discounts at the same time as the US Gulf export price dropped by $20/tonne to $600/tonne FOB (free on board) ?xml:namespace>
Responses from suppliers have been cool.
“I would be flabbergasted if they do it,” said one source. “It is not the dollar value, it is the precedent it sets if it did happen.”
Others have acknowledged the role that
“A discount to $50/tonne is a big step. But
The spot market has dropped below the $677/tonne CFR contract price in recent weeks and the $25-30/tonne premium usually achieved is considered no longer possible.
($1 = €0.75) | http://www.icis.com/Articles/2011/11/25/9511853/suppliers-agree-india-fertilizer-import-discounts-on-falling-rupee.html | CC-MAIN-2014-10 | refinedweb | 301 | 59.64 |
I’ve been experimenting with the UI tools Unity just released in version 4.6. I am very happy so far, so for this post, I am going to use it to create the interface for our Text based RPG game.
Our Interface will consist of an input text field, where the user can type commands like “Attack Ogre” or “Hide”, a button which accepts the input, and a scrollable text area where the user can see a history of the commands he has entered as well as events occurring in the game such as “Spider hit Wolf for 10 damage”.
- Create a new scene.
- From the menu bar, choose “GameObject-> UI-> Panel”. Unity will automatically create a Canvas and EventSystem and parent the Panel to the Canvas for us and everything should already be configured as we want.
- Name the panel object “Root Panel” so it will be easy to refer to later.
- We won’t be needing an Image component on the Root Panel, I’ll just use the camera’s background color, so feel free to remove it.
- Make sure the Root Panel is selected and then from the menu bar, choose “Component-> Layout-> Vertical Layout Group” to add that component to the object. This will be used to separate the input section from the output section in a nice looking and organized way. Configure the new component by setting each of the values of Padding to 20 (Left, Right, Top and Bottom) as well as 20 on the Spacing. Finally uncheck the “Height” toggle next to “Child Force Expand”.
- Create two more Panel’s like you did in step 2, and parent them to the root panel. I called the first panel (which appears at the top) the “Output Panel” and the second panel the “Input Panel”. We won’t need the Image components on these either, so remove them.
- Add the component “Horizontal Layout Group” to the “Output Panel”. This will be used to layout a Scrollable Text Field and the Scroll Bar. Disable the toggle for “Width” next to “Child Force Expand” but leave “Height” enabled.
- Create another panel. I named this object “Text Area” and parented it to the Output panel. This time do not remove the Image component.
- Make sure the Text Area is selected and then from the menu bar, choose “Component-> UI-> Mask” to add that component to the object. Without this component, the text we will add soon would be able to render beyond the borders of the container. The mask requires the Image component to work and is why we did not remove it.
- Add the component “Layout Element” to the Text Area and enable the “Flexible Width” with a value of 1.
- From the menu bar, choose “GameObject-> UI-> Text”. Parent this object to the Text Area.
- On the Rect Transform for the Text object, set the min anchor and pivot fields to 0. Set a max X anchor of 1 and a max Y anchor of 0. Then set all of the Pos fields to 0 as well. Finally set the Right to 0 so that the width is the same width as the parent panel.
- On the Text component, I added a bunch of junk text, and I set the Alignment to Left and Top, and made the Font size pretty big at 80, but mostly so I could see the effects of the scrolling more quickly. Later I will reduce the font size and remove the starting text.
- Add the component “Content Size Fitter” to the Text object. Set the “Vertical Fit” to “Preferred Size”. This will automatically resize the Rect Transform’s height based on the amount of text and newlines, etc. so that the Scroll Rect we are about to configure will know how much room it has to move.
- From the menu bar, choose “GameObject-> UI-> Scrollbar”. Parent this object to the Output Panel.
- Set the “Direction” of the Scrollbar to “Bottom To Top”.
- Add the component “Layout Element” to the Scrollbar and enable the “Min Width” toggle with a value of 20.
- Add the component “Scroll Rect” to the “Text Area” panel and assign its child Text object as the “Content”, and the sibling object “Scrollbar” as the “Vertical Scrollbar”.
- If you set everything up correctly so far, and added enough lines of junk text that the Text content is taller than the scroll rects area, you could press play now and see that scrolling the scroll bar works and the text can be scrolled exactly from the top to the bottom without us needing to program a single line of code. Before you continue, make sure to exit play mode or your changes will be lost.
- Add the component “Horizontal Layout Group” to the Input Panel. This will handle the layout of the Input Field and Enter button. Set a value of 20 for the “Spacing” and uncheck “Width” and “Height” for “Child Force Expand”.
- From the menu bar, choose “GameObject-> UI-> InputField”. Parent it to the “Input Panel”.
- Add the component “Layout Element” to the Input Field and set a value of 160 for “Min Width”, a value of 30 for “Min Height” and “Preferred Height”, and a value of 1 for “Flexible Width”.
- From the menu bar, choose “GameObject-> UI-> Button”. Parent the button to the “Input Panel”.
- I named my button the “Enter Button”. And specified the button’s label to have the text, “Enter”.
- Add the component “Layout Element” to the Enter Button and set a value of 160 for “Min Width”, a value of 30 for “Min Height” and “Preferred Height”.
We’re almost complete, but in order to finish giving functionality to the Enter Button we will need to add a script. I created new script called “GameViewController.cs”. Which I added to the Canvas object at the root of the hierarchy. The contents of the script are below:
using UnityEngine; using UnityEngine.UI; using System.Collections; public class GameViewController : MonoBehaviour { public InputField input; public Text output; public void OnEnterButtonPressed () { output.text = string.Format("{0}\n{1}", output.text, input.text); input.text = ""; } }
Connect the “InputField”child object on the “Input Panel” to the “input” property of the script. Connect the “Text” child object on the “Text Area” panel in the “Output Panel” hierarchy to the “output” property of the script.
Select the “Enter Button” and then click the “+” button at the bottom of its “On Click ()” event handler list. Drag the Canvas object containing the “GameViewController” script into the Object field, and then choose the “GameViewController-> OnEnterButtonPressed” method.
Everything is now configured. Press play and type some text into the InputField, then press the Enter button. The input field will revert to the placeholder text and the text you entered will appear inside the scrollable text area.
17 thoughts on “Unity’s new GUI”
Hi, the whole thing is going well here and ofcourse every one is sharing facts, that’s
truly good, keep up writing..
Hey, sorry to hear you are having that kind of experience. Is your content intended to be commercialized? I am guessing so, since you have outsourced some of it.
I am not doing anything special to stop copyright infringement for my own materials. I haven’t noticed if anyone has plagiorized me or not – I haven’t even looked. Since all of my content is free, including the full source code, it may just be the case that there is little benefit to anyone trying or wanting to steal it anyway. I wish we could always rely on the honor system, but at the very least the honor system seems to be “more” followed for free content in my own experiences.
I have read some excellent stuff here. Certainly worth bookmarking
for revisiting. I wonder how so much effort you place to create the sort of great informative web site.
I’ve read several just right stuff here. Definitely price bookmarking for revisiting.
I surprise how a lot effort you set to create one of these wonderful informative site.
I am аctualkly plеаsed to reaad this website
posts hich carries lots of սseful information, thanks
for providing theѕe kinds of information.
Asking questions are in fact good thing if you are not understanding anything fully, except this post offers good understanding yet.
Hi friends, nice piece of writing and pleasant urging commented at this place, I
am genuinely enjoying by these.
Thanks, and welcome!!
I started with a free wordpress blog. It was nice because it was very easy to use and learn on – everything is already setup so you pretty much can simply start writing. If your blog becomes successful (by whatever definition that is to you), you can upgrade within the wordpress domain, or can always move to your own server and pay for wordpress to forward any existing traffic to the new host. I don’t think it matters too much how you start, because there are tons of options at every step of the way. Good luck!
Pretty element of content. I simply stumbled upon your
website and in accession capital to say that I acquire actually enjoyed account
your blog posts. Any way I’ll be subscribing to your augment and even I fulfillment you get entry to consistently fast.
Hi there to every one, the contents existing at this website are
really remarkable for people experience, well, keep up the good work fellows.
That is a good tip especially to those fresh to the blogosphere.
Brief but very precise info? Appreciate your sharing this one.
A must read article!
Helpful info. Fortunate me I found your site accidentally, and I am stunned why this coincidence didn’t took place earlier!
I bookmarked it.
We web log!
I’m open to guest written content, assuming the content is non-offensive and that it is made available with an unrestricted license. | http://theliquidfire.com/2014/12/04/unitys-new-gui/?replytocom=13208 | CC-MAIN-2020-45 | refinedweb | 1,649 | 72.26 |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-10-08 06:55:43
From: "Douglas Gregor" <gregod_at_[hidden]>
> Thanks to some insight from Brad King, I've introduced additional syntax
into
> Boost.Function that makes function<..> instances act more like function
> pointers. Assignment to and comparison with zero is now supported, e.g.:
>
> function<int (int x, int y)> f;
> f = std::plus<int>();
> assert(f != 0); // same as assert(!f.empty())
> f = 0; // same as f.clear()
> assert(0 == f); // same as assert(f.empty());
What is the rationale for the change?
> This change is source-compatible but not necessarily binary-compatible
with
> older versions on Boost.Function. Nonetheless, it was only made on the CVS
> trunk (not the branch), and will appear in 1.30.0.
Actually I have a regression to report. Since function::operator= takes a
non-const operand, this code now fails:
#include <boost/function.hpp>
typedef boost::function< void * (void * reader) > reader_type;
typedef std::pair<int, reader_type> mapped_type;
int main()
{
mapped_type m;
m = mapped_type();
}
as std::pair's implicit assignment operator takes a non-const reference,
too.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2002/10/37233.php | CC-MAIN-2019-09 | refinedweb | 204 | 53.78 |
Pods. A Pod's contents are always co-located and co-scheduled, and run in a shared context. A Pod models an application-specific "logical host": it contains one or more application containers which are relatively tightly coupled. In non-cloud contexts, applications executed on the same physical or virtual machine are analogous to cloud applications executed on the same logical host.
As well as application containers, a Pod can contain init containers that run during Pod startup. You can also inject ephemeral containers for debugging if your cluster offers this.
What is a Pod?
The shared context of a Pod is a set of Linux namespaces, cgroups, and potentially other facets of isolation - the same things that isolate a Docker container. Within a Pod's context, the individual applications may have further sub-isolations applied.
In terms of Docker concepts, a Pod is similar to a group of Docker containers with shared namespaces and shared filesystem volumes.
Using Pods
The following is an example of a Pod which consists of a container running the image
nginx:1.14.2.
apiVersion: v1 kind: Pod metadata: name: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80
To create the Pod shown above, run the following command:
kubectl apply -f
Pods are generally not created directly and are created using workload resources. See Working with Pods for more information on how Pods are used with workload resources.
Workload resources for managing pods
Usually you don't need to create Pods directly, even singleton Pods. Instead, create them using workload resources such as Deployment or Job. If your Pods need to track state, consider the StatefulSet resource.
Pods in a Kubernetes cluster are used in two main ways:
Pods that run a single container. The "one-container-per-Pod" model is the most common Kubernetes use case; in this case, you can think of a Pod as a wrapper around a single container; Kubernetes manages Pods rather than managing the containers directly.
Pods that run multiple containers that need to work together. A Pod can encapsulate an application composed of multiple co-located containers that are tightly coupled and need to share resources. These co-located containers form a single cohesive unit of service—for example, one container serving data stored in a shared volume to the public, while a separate sidecar container refreshes or updates those files. The Pod wraps these containers, storage resources, and an ephemeral network identity together as a single unit.Note: Grouping multiple co-located and co-managed containers in a single Pod is a relatively advanced use case. You should use this pattern only in specific instances in which your containers are tightly coupled.
Each Pod is meant to run a single instance of a given application. If you want to scale your application horizontally (to provide more overall resources by running more instances), you should use multiple Pods, one for each instance. In Kubernetes, this is typically referred to as replication. Replicated Pods are usually created and managed as a group by a workload resource and its controller.
See Pods and controllers for more information on how Kubernetes uses workload resources, and their controllers, to implement application scaling and auto-healing.
How Pods manage multiple containers.
For example, you might have a container that acts as a web server for files in a shared volume, and a separate "sidecar" container that updates those files from a remote source, as in the following diagram:
Some Pods have init containers as well as app containers. Init containers run and complete before the app containers are started.
Pods natively provide two kinds of shared resources for their constituent containers: networking and storage.
Working with Pods
You'll rarely create individual Pods directly in Kubernetes—even singleton Pods. This is because Pods are designed as relatively ephemeral, disposable entities. When a Pod gets created (directly by you, or indirectly by a controller), the new Pod is scheduled to run on a Node in your cluster. The Pod remains on that node until the Pod finishes execution, the Pod object is deleted, the Pod is evicted for lack of resources, or the node fails.
When you create the manifest for a Pod object, make sure the name specified is a valid DNS subdomain name.
Pods and controllers
You can use workload resources to create and manage multiple Pods for you. A controller for the resource handles replication and rollout and automatic healing in case of Pod failure. For example, if a Node fails, a controller notices that Pods on that Node have stopped working and creates a replacement Pod. The scheduler places the replacement Pod onto a healthy Node.
Here are some examples of workload resources that manage one or more Pods:
Pod templates
Controllers for workload resources create Pods from a pod template and manage those Pods on your behalf.
PodTemplates are specifications for creating Pods, and are included in workload resources such as Deployments, Jobs, and DaemonSets.
Each controller for a workload resource uses the
PodTemplate inside the workload
object to make actual Pods. The
PodTemplate is part of the desired state of whatever
workload resource you used to run your app.
The sample below is a manifest for a simple Job with a
template that starts one
container. The container in that Pod prints a message then pauses.
apiVersion: batch/v1 kind: Job metadata: name: hello spec: template: # This is the pod template spec: containers: - name: hello image: busybox command: ['sh', '-c', 'echo "Hello, Kubernetes!" && sleep 3600'] restartPolicy: OnFailure # The pod template ends here
Modifying the pod template or switching to a new pod template has no direct effect on the Pods that already exist. If you change the pod template for a workload resource, that resource needs to create replacement Pods that use the updated template.
For example, the StatefulSet controller ensures that the running Pods match the current pod template for each StatefulSet object. If you edit the StatefulSet to change its pod template, the StatefulSet starts to create new Pods based on the updated template. Eventually, all of the old Pods are replaced with new Pods, and the update is complete.
Each workload resource implements its own rules for handling changes to the Pod template. If you want to read more about StatefulSet specifically, read Update strategy in the StatefulSet Basics tutorial.
On Nodes, the kubelet does not directly observe or manage any of the details around pod templates and updates; those details are abstracted away. That abstraction and separation of concerns simplifies system semantics, and makes it feasible to extend the cluster's behavior without changing existing code.
Pod update and replacement
As mentioned in the previous section, when the Pod template for a workload resource is changed, the controller creates new Pods based on the updated template instead of updating or patching the existing Pods.
Kubernetes doesn't prevent you from managing Pods directly. It is possible to
update some fields of a running Pod, in place. However, Pod update operations
like
patch, and
replace
have some limitations:
Most of the metadata about a Pod is immutable. For example, you cannot change the
namespace,
name,
uid, or
creationTimestampfields; the
generationfield is unique. It only accepts updates that increment the field's current value.
If the
metadata.deletionTimestampis set, no new entry can be added to the
metadata.finalizerslist.
Pod updates may not change fields other than
spec.containers[*].image,
spec.initContainers[*].image,
spec.activeDeadlineSecondsor
spec.tolerations. For
spec.tolerations, you can only add new entries.
When updating the
spec.activeDeadlineSecondsfield, two types of updates are allowed:
- setting the unassigned field to a positive number;
- updating the field from a positive number to a smaller, non-negative number.
Resource sharing and communication
Pods enable data sharing and communication among their constituent containers.
Storage in Pods
A Pod can specify a set of shared storage volumes. All containers in the Pod can access the shared volumes, allowing those containers to share data. Volumes also allow persistent data in a Pod to survive in case one of the containers within needs to be restarted. See Storage for more information on how Kubernetes implements shared storage and makes it available to Pods.
Pod networking
Each Pod is assigned a unique IP address for each address family. Every
container in a Pod shares the network namespace, including the IP address and
network ports. Inside a Pod (and only then), the containers that belong to the Pod
can communicate with one another using
localhost. When containers in a Pod communicate
with entities outside the Pod,
they must coordinate how they use the shared network resources (such as ports).
Within a Pod, containers share an IP address and port space, and
can find each other via
localhost. The containers in a Pod can also communicate
with each other using standard inter-process communications like SystemV semaphores
or POSIX shared memory. Containers in different Pods have distinct IP addresses
and can not communicate by IPC without
special configuration.
Containers that want to interact with a container running in a different Pod can
use IP networking to communicate.
Containers within the Pod see the system hostname as being the same as the configured
name for the Pod. There's more about this in the networking
section.
Privileged mode for containers
In Linux, any container in a Pod can enable privileged mode using the
privileged (Linux) flag on the security context of the container spec. This is useful for containers that want to use operating system administrative capabilities such as manipulating the network stack or accessing hardware devices.
If your cluster has the
WindowsHostProcessContainers feature enabled, you can create a Windows HostProcess pod by setting the
windowsOptions.hostProcess flag on the security context of the pod spec. All containers in these pods must run as Windows HostProcess containers. HostProcess pods run directly on the host and can also be used to perform administrative tasks as is done with Linux privileged containers.
Static Pods
Static Pods are managed directly by the kubelet daemon on a specific node, without the API server observing them. Whereas most Pods are managed by the control plane (for example, a Deployment), for static Pods, the kubelet directly supervises each static Pod (and restarts it if it fails).
Static Pods are always bound to one Kubelet on a specific node. The main use for static Pods is to run a self-hosted control plane: in other words, using the kubelet to supervise the individual control plane components.
The kubelet automatically tries to create a mirror Pod on the Kubernetes API server for each static Pod. This means that the Pods running on a node are visible on the API server, but cannot be controlled from there.
specof a static Pod cannot refer to other API objects (e.g., ServiceAccount, ConfigMap, Secret, etc).
Container probes
A probe is a diagnostic performed periodically by the kubelet on a container. To perform a diagnostic, the kubelet can invoke different actions:
ExecAction(performed with the help of the container runtime)
TCPSocketAction(checked directly by the kubelet)
HTTPGetAction(checked directly by the kubelet)
You can read more about probes in the Pod Lifecycle documentation.
What's next
- Learn about RuntimeClass and how you can use it to configure different Pods with different container runtime configurations.
- Read about Pod topology spread constraints.
- Read about PodDisruptionBudget and how you can use it to manage application availability during disruptions.
- Pod is a top-level resource in the Kubernetes REST API. The Pod object definition describes the object in detail.
- The Distributed System Toolkit: Patterns for Composite Containers explains common layouts for Pods with more than one container.
To understand the context for why Kubernetes wraps a common Pod API in other resources (such as StatefulSets or Deployments), you can read about the prior art, including: | https://kubernetes.io/docs/concepts/workloads/pods/ | CC-MAIN-2022-05 | refinedweb | 1,971 | 53.41 |
CONTENT MOVED: Adaptive and interactive toast notifications for Windows 10 ★★★★★★★★★★★★★★★ leixu2046July 2, 201581 Share 0 0 Content moved Please see the article on docs.microsoft.com for the latest documentation.
Will there be a nuget library to facilitate these notifications? similar to the NotificationsExtensions package.
How can I call an xml file for a custom Toast by code?
@FullMetal99012 (Editor update) Yes! NotificationsExtensions for Windows 10 is available and officially supported by Microsoft!
(Original comment) You can use github.com/…/InteractiveToastExtensions
@Fullmetal99012 As Cabuxa's comment mentioned, the official NotificationsExtensions for Windows 10 is now available through NuGet or GitHub.
@Anrafu13 if you are also asking about extension library, please see if you may find the post below yours helpful. If you are asking about loading an existing xml file from your appx package, then please take a look at msdn.microsoft.com/…/windows.storage.storagefile.getfilefromapplicationuriasync.ASPX
I'm trying to get the audio element with ms-appdata:/// to run under Windows 10 UWP (Desktop) but no luck so far. Tried the temp and the local folder. Has this feature made it into the release build? Is there a limit to the allowed length of the audio? Are there any special requirements with regards to the uri that don't exist with a MediaElement?
Best regards,
Harald
—
In Windows 10 UWP apps, the <audio> element remains unchanged compared to what’s currently supported for Windows Phone 8.1.
You can now also provide a path to a local audio file in your app package or app storage, to play a custom sound specific for your app:
◾ms-appx:///
◾ms-appdata:///
@Harald – Looks like you're right, custom audio isn't working. We're investigating this issue. As of now, both ms-appx and ms-appdata don't work on Desktop, and only ms-appdata works on Mobile. Thanks for reporting this!
I am using the adaptive toast with a Win32 app, and I cannot manage to get my toast to stay in the action center when it timed out. If i close it with the close button, it goes in the action center but when let it time out, it just disappear.
With the same toast (i used your first sample) in an Universal app, the toast stay in the action center when it timed out.
Is it the expected behaviour for the win32 app ?
@Keuvain Thanks for trying the new toast features. The default behavior for win32 apps should be the same in which the toast notifications are persisted in action center. We will investigate in the false behavior you are observing currently. Also, we will have some guidance and sample published soon on how to handle application activation from toast once it's inside action center using COM activation.
How do you get a larger inline image like the reminder example? I am unable to get anything other than a small cropped image like the first example. I'm sending the toast from a desktop program if that makes a difference.
@Adrian – For an inline image to display full width, the scenario attribute on the <toast> element needs to be set to either "reminder", "alarm", or "incomingCall".
<toast scenario="reminder">
….
</toast>
However, do realize that the scenario changes other things. Those three scenarios will all force the notification to stay on screen until the user does something with it. Don't pick a scenario that conflicts with what your user expects (for example if a new text message used the reminder scenario, users would be annoyed that they're forced to dismiss the text message to continue doing anything on their device).
Hi, when i am trying to open the Background task from the action button in toast, but i am getting an compilation error "the type or namespace "NotificationActionTriggerDetails" could not be found". Am i doing it in the right way.
please help.
I am running my windows 8 app in windows 10 machine. the problem i am facing is i am unable to get the LaunchActivatedEventArgs in launch event ?
can anyone suggest the issue please ?
Sorry for not providing full information for the above question.
Windows 8 store app in windows 10 machine and the question is regarding the ToastNotification. when user taps on it.
One problem I'm seeing is that my notifications sometimes don't show up in the UI, but rather are sent to the Action Center. How can we avoid this and *always* show the Toast UI?? For example, I'd like to alert the user to the fact that a refresh has completed in my app via a toast notification
how I load xml file to XmlDocument?
@Amer: stackoverflow.com/…/895305
Is anyone facing the problem which i am facing ? please see the previous 5 comment from this comment.
@Suresh – Ah I see you did comment over here originally, great! Ok, so Windows 8 app running on Windows 10 no longer receives the LaunchActivatedEventArgs inside OnLaunched for toasts… That definitely sounds like a bug. Probably due to the fact that we've switched to using OnActivated as documented in this blog post… but Windows 8 apps SHOULD be grandfathered in… We'll investigate it. Thank you for reporting it!
@Brandon – Toasts should always show up on-screen first before going into action center, unless the user changed their settings and disabled banners. You can check your settings on your PC by opening Settings -> System -> Notifications & Actions, and then clicking on your app, and confirming that "Show notification banners" is enabled. If it's enabled and toasts are still inconsistently appearing, please give us more info (sample app if you have one) and we can investigate further.
@Amer – Even better, use the new NotificationsExtensions library so you don't have to generate XML! You can use IntelliSense and objects to create your notifications! blogs.msdn.com/…/introducing-notificationsextensions-for-windows-10.aspx Alternatively, to load a string to XmlDocument, create a new XmlDocument, and then call .LoadXml(string);
Has the issue with custom sound been fixed? And how will the fix be rolled out to users, via a regular Windows Update or in a new Windows 10 "build" update?
Is it possible to have a notification play a long sound file (30 seconds to 1 minute)?
I remember it wasn't possible in W(P) 8.1. I wanted to test it in a UWP app, but it didn't work and I found out in the comments here that there's a bug.
There is an error in the sample code: it's not NotificationActionTriggerDetails, it's ToastNotificationActionTriggerDetail.
@Suresh – I just tested a Windows 8.1 app on Windows 10 and the OnLaunched got triggered correctly, with the toast launch args. You're still having issues with that?
@Abdusamad – Custom audio… We incorrectly thought that we supported custom audio on Desktop. Turns out that was cut, so audio has remained unchanged from Windows 8.1 (only mobile supports ms-appx and ms-appdata). However, there's new bugs affecting the mobile custom audio (ms-appx doesn't work, and also on "alarm" or "incomingCall" scenarios, neither ms-appdata nor ms-appx work). We're still working on fixing them, no update yet.
@opayen – Thanks for pointing that out!! Updated the code snippet.
Thank you for the replie(s on your blog). That's too bad. I have an app in the Windows Phone 8.1 store with almost 700 downloads and lots of users requesting a custom long notification sound (non looping). I'm in the process of porting the app to UWP Desktop/Tablet and Mobile and I'm a bit disappointed it still hasn't been implemented on the Windows platform.
I hope it will be implemented soon because I think there's lots of developers and users who'd like that feature and it's basically the #1 requested feature for my app.
Any news on the Tile Template Visualizer btw? Thanks again.
What's the longest audio file you've tried? And on the toast, you set duration="long"?
Tile Template Visualizer is still pending approval to use the actual DLL from Start (otherwise it won't be 100% exact, only a visualization).
The longest was 3:20. Duration="long" works doesn't work on WP 8.1. And on UWP I can't test with custom sound because it's buggy/not implemented yet, so that's my dilemma. Is there a different way to set source for custom sound other than ms-appx or ms-appdata?
Thanks for the update. 🙂
ms-appdata works on Windows 10 Mobile, as long as you're not also using it while specifying "incomingCall" or "alarm". So you could try that.
So you theoretically should be able to achieve it right now, assuming duration="long" works on Mobile now? I haven't tried that, as Lei's article says, we really were only keeping the "long" option around for app compat, so it's possible we didn't bring it to mobile.
@andrewbares7 – sorry for the late reply. And thanks for answering.
I have done a small mistake too. i solved the problem my self. Like in the blog he said toast launch args will be received in OnActivatedEvent i did the same in my app and we need to update the toast payload(toast xml) too. This toast payload will not work in windows 8 machine. it only works in windows 10 machines.
In windows 10 machine toast notifications will be received even though the app in running in the foreground.
thanks once again for this good blog.
@suresh thanks a lot for trying these new features out, and yes, the new toast payload does not work in Windows 8 machine since the old parser wouldn't recognize the new stuff we came up with.
Apologize for missing your previous questions but I'm glad Andrew helped out. Please do reach out if you have more questions.
@leixu2046 "The default behavior for win32 apps should be the same in which the toast notifications are persisted in action center."
I've implemented usage of new toast notifications in Telegram Desktop messaging app and the notifications disappear from Action Center as soon as they disappear from screen (or as soon as the action center is closed, if it was opened while the notification was still on the screen). It is a bad behavior and many users have complained about this.
May I have any information about that issue? Was it reproduced in MS? Will it be fixed by a Windows Update, or it will persist that way much longer? I'm interested in any information about that.
Also I've got some problems with per-app notification settings, there are no apps listed, but I use one my own custom app with notifications and one downloaded from the Store, both sending notifications, which could be seen here: updates.tdesktop.com/…/noapps.png
How can I get my win32 app to that list? Why I don't have any apps there and how this could be fixed?
Where can I find a list of the protocols that can be launched? specifically I'd like to launch the default browser to an url, but arguments="" doesn't work.
@John – I've told Lei to follow up with you.
@Lindsay – The available URI launch protocols can be seen here: msdn.microsoft.com/…/mt228340.aspx They're the same that are supported with LaunchUriAsync. Launching websites works, just tested it on my personal RTM laptop. Make sure that you're setting activationType="protocol". Tell us what's happening and maybe we can help you. For example, the following payload generates a toast with a button that, when clicked, opens Slashdot.
<toast>
<visual>
<binding template='ToastGeneric'>
<text>HTTP Toast</text>
</binding>
</visual>
<actions>
<action activationType="protocol" arguments="" content="Open SlashDot"/>
</actions>
</toast>
How do I send a toast notification that works on both Windows 10 and Windows/WP 8.1? I've tried adding two <visual> elements, but this leads to Win10 just displaying "New notification" and not any of the actual notification content. If I send just the 8.1 or just the Win10 <visual> it works. But I need to send both because users may be using a mix of devices (especially Win10 PCs with 8.1 phones since Win10 Mobile isn't out yet).
There is ToastNotification.Activated event which provides ToastActivatedEventArgs and it does not contains UserInput property while Application.OnActivated event provides ToastNotificationActivatedEventArgs which contains UserInput property. Why windows is losing information in ToastNotificationActivated event?
Is there a way i can get the UserInput property in ToastNotification.Activated event?
@Half baked toast – Is there a reason you're using the Activated event on the toast object instead of the OnActivated method? Please tell us your scenario so you can help. If the user taps on your toast from within action center, that Activated event will NOT fire.
We recommend using the OnActivated method, since the Activated event isn't useful for most scenarios. For example, what happens when the user clicks on your toast after they've closed your app? The Activated event won't be able to trigger. But OnActivated method does.
@andrewbares7 – I'm raising the toast notification from a dll and want to handle the toast events in that dll only. The application is not a UWP app and I don't want any event if the application is closed. Since there is no Application class so I don't have the Application.OnActivated method.
When the ToastNotification.Activated event can handle the most of the scenarios of toast notification like button click on notification, cancel and timeout, why UserInput is not available in that event?
@Brandon – Unfortunately there's no good solution for sending a single payload that supports both 8.1 and the new features of 10. You would have to store on your server what OS the device is on, and then send the correct payload.
@Half baked – I've told Lei to follow up with you about Win32 apps. He's working on a blog post that covers this.
I am using the a win32 app, and I cannot manage to get my toast to stay in the action center when it timed out.
With the same toast in an Universal app, the toast stay in the action center when it timed out.
Is it the expected behaviour ?
Also – how to handle application activation from toast once it's inside action center?
defaultSelection or defaultInput… ?
I think defaultInput is righ, not defaultSelection
@AC Hi AC, check out this blog post on how win32 apps can send and handle toast notifications in Windows 10:
@Dat Nguyen – Thanks for reporting that mistake! You're correct, it should be defaultInput. I've updated the article.
@andrewbares7 – Is there any update on ms-appx support for custom audio? Or custom audio for Desktop?
I've implemented custom audio for Windows 10 Mobile using ms-appdata, but it doesn't work on my Lumia 520 with Insider Preview. I have a method (in app.xaml.cs) that fires after first install or an update, which copies the sound file to the appdata folder so I can use it for custom audio, but when I launch the app the first time, it gets to the splashscreen and closes. So I think something goes wrong when copying the file. I haven't been able to reproduce this on the emulators, it works fine there. I dont know if it's a Insider Preview issue or what. Still trying to figure it out. Being able to use ms-appx would be a lot more efficient, since I won't have to copy the file.
@Abdusamad – ms-appx for mobile should be fixed in the latest mobile preview. I'll test it tomorrow on internal builds. You can assume that it'll work in the final release of mobile.
Desktop custom audio is not being added at this time.
Hi,
Can’t use ms-appx and ms-appdata to set source for ToastAudio on Desktop. I see it’s an old trouble.
Last comment was almost a year ago.
Are there any updates or fixes?
Just tested on Mobile build 10572, ms-appx works. 🙂 Thanks.
@leixu2046 "The default behavior for win32 apps should be the same in which the toast notifications are persisted in action center."
Is there any update on this?
In win32 app, My Toast notification is vanished from Action center after time out.
But I need it to be persisted until user responds to it.
is there any workaround for it?
@Kiran – See our new post on how to send toast notifications from Win32 apps: blogs.msdn.com/…/quickstart-handling-toast-activations-from-win32-apps-in-windows-10.aspx
You'll have to set up a COM server, as that article describes, so that your app can be activated from toasts persisted in Action Center. Otherwise, if you didn't have that COM server, and the user closed your app, and then the user clicked the persisted toast, the toast wouldn't do anything (your Activated event that was registered as a callback is no longer active since your code isn't running).
Sorry for not replying to your comment. Thanks for nagging us, we're happy to help!
I cant get quick reply scenario working properly, I mean button local icon/image never shows, from web works nice.
@Methew – How are you referencing your local images? Are you using ms-appx:/// with three slashes? A copy of the XML you're using, in addition to a screenshot of your Visual Studio project's file structure (specifically showing the path of the image you're referencing) would be helpful. Local images definitely work, we've used them before.
I am using a win8 app, and I cannot manage to get my toast to stay in the action center when it expired.
With the same toast in an Universal app, the toast stay in the action center when it timed out.
Is it the expected behaviour ?
Also – how to handle application activation from toast once it's inside action center?
@AYC – Are you actually talking about *Win32* apps? If so, then you have to read the documentation for Win32, since this post is about UWP apps. The Win32 documentation is here: blogs.msdn.com/…/quickstart-handling-toast-activations-from-win32-apps-in-windows-10.aspx
Note:
One important step is missing if you want to uses a background task:
You need to register the background agent first:
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
{
Name = "ToastAgent",
TaskEntryPoint = "Task.ToastAgent"
};
builder.SetTrigger(new ToastNotificationActionTrigger());
BackgroundTaskRegistration registration = builder.Register();
Thanks Rudy for that important code snippet of registering the background task, which we forgot! I've moved all this code to the Quickstart and added the registeration step, and simply made this page link to it so there's no redundant information: blogs.msdn.com/…/quickstart-sending-a-local-toast-notification-and-handling-activations-from-it-windows-10.aspx
this is a sample that works for tile notifications 😀
code.msdn.microsoft.com/Tile-notifications-in-e217d57f
I have precisely the same issue as Half baked toast and I totally support his question.
@andrewbares7 Are you guys working on that blog post still?
Hey Elena, you're talking about Win32 apps? We have a blog post for that (blogs.msdn.com/…/quickstart-handling-toast-activations-from-win32-apps-in-windows-10.aspx). There are a number of open issues that Lei is trying to address with Win32.
If you're writing a UWP, we explain how to handle activation in this Quickstart: blogs.msdn.com/…/quickstart-sending-a-local-toast-notification-and-handling-activations-from-it-windows-10.aspx
Hey, Andrew, thanks for your swift reply. Yes, I am talking about Win32 apps. The blog post you gave me unfortunately does not solve my problem. I've already left some comments there as well. Can we find out what are the "open issues" that Lei is trying to address? This would be extremely helpful.
I second the comments here about the UserInput missing in ToastActivatedEventArgs . Most of us gets that indeed without the Activate event we won’t be able to have persistent notifications working in the notification center but right now in order for us to move slowly to full UWP apps we have to extract and put as much as possible into a DLL with .NET code that is used by the old school app to slowly port the code base. Notifications is a must have these days and really have the UserInput field would already be a good step to have good notifications support. Then of course in the future we can have full persistent notifications with activations that launch the app. The fact that some of us uses .NET in that secondary DLL library is which is pretty good to construct the notifications. is a good start to have some support of the ActivatedEvent but again there is no sample somewhere ready to test. It would be appreciated to have one.
Thanks for the work.
I remember I was really happy to see your post because I’ve been looking for how to get user input from toast notification.
Thanks for this post.
But I have a big problem with getting user input from toast notification when user types text in Korean.
I’m showing user toast notification including input and User may type their reply to the toast input box and click reply action button then my background task receives ToastNotificationActionTriggerDetail.
But the UserInput value set in ToastNotificationActionTriggerDetail includes only empty string, “”, if the input text is “ㅋㅋ”, “ㅎㅎ” or “ㅇㅇ” those are the most popular abbreviations used on chat message in Korea.
They are similar “kk”, “hh” or “IC” in English.
It seemed the toast input box cannot get these Korean text above because it recognizes text input is not completed yet.
It’s just my opinion from my experience and I’d like to hear your advice.
Hey Daniel, I can’t seem to repro your issue. I popped a toast using a text box, and pasted in “ㅋㅋ”, and I successfully got back that same text in the UserInput values.
What device (Mobile or Desktop) and what build are you seeing this issue on? I tried it on Desktop TH2, where it seemed to work.
It has been fixed at RS1 timeline.
Thanks for the thought.
Our current balloon notification implementation is WPF, and the issue we are observing is that when the user uses Win 10 where they automatically get converted to Toast Notification (OS Controls it) is text is cut for some languages in the desktop environment. If we use the legacy (Win 7) balloon notification in Windows 10, there is no as such character limitation in the balloon pop-up. What is the character limitation for toast in the desktop environment?
Hey Vero!
There’s no specific character limit on toasts, since different devices might be able to display different amounts of text (and also different languages have different character sizes). Also, we’re slightly changing how toast notifications look and feel in new versions of Windows 10, which affects how many characters would be displayed.
For your scenario, you should make sure that the user can click the toast to read the full content, so that if the content couldn’t all fit, when they click the toast, they can see everything.
I am facing two issues with Toast notification with Desktop application on Windows 10
1) When user does nothing with the toast, it simply disappear without going to the action center (ToastNotification.Dismissed is ToastDismissalReason.TimedOut). It is not sticky, how do I make it work?
2) Chasing the notification is also not working, I have Activated event, tapping on the toast notification does not do anything. Consider after generating notification my application will not be running. But I have created a shortcut under Users Start menu Program using AppuserModelID concept, and It is the same AppID used while creating the notification.
Hi Rocky, sounds like you’re talking about Win32 Desktop apps, not UWP. Please bring your conversation over to the Win32 article:
And for (1), toasts are temporary, after a few seconds, they’ll go into Action Center.?
Is there any XSD file available for the Toast XML schema? It can be used for the XML data binding for my backend.
Hey James! No, we haven’t published an XSD for the Toast XML schema. If you’re using C# on your backend, you could use NotificationsExtensions to generate your notifications rather than using raw XML.
Hello!
How to implementation action events in powershell script?
Hey Roman, I’m not sure what you mean… Powershell scripts? This article is about Windows 10 UWP apps.
I use powershell script to send toast notification and it works, but there is no way to intercept the events and add EventHandler with objects of WinRT classes.
The MSDN documentation regarding the src attribute of the image element says that among other protocols both the http:// and the https:// protocol are supported. However, when using such an URI (example: src=””), the image is not displayed in the toast. Downloading the same file locally and using the (like “:\images\wikipedia.png”) works as expected.
Is the MSDN documentation outdated regarding the supported protocols? Was the http://- and https:// protocol support dropped from Windows 8(.1) to Windows 10? If so, was this done on purpose? Or is that a bug? Do Windows 10 toasts still support images from foreign http:// or https:// sources?
Hey Charly, sorry for the late reply, I think email notifications once again were turned off for some reason :/
http:// and https:// images are supported for UWP’s. Sounds like maybe you’re writing a Win32 app? Win32 apps do not support http images, since they do not have the package manifest like a UWP containing the internet capability. Hence for Win32 apps, you need to download the image and then reference it via file://.
Thanks!
Andrew
Hi,
I got problem on toast activated.
I used activated method to show the form but after a few seconds the form is gone and it was not even disposed.
How to prevent this on happening?
Thanks
I have a question related to ToastGeneric template “Text” element.
Is there a character size limit for each “text” element only 40 , 60 etc.
If there is any how to increase this limit ?
Please give any pointers or details on this.
Thanks Rajesh
Hey Rajesh! Nope, there’s no limits on the character lengths of
elements (nor are there limits on URI’s, etc).
However, the entire XML payload must be less than 5 KB. Therefore, you’ll want to make sure to trim your strings at reasonable lengths. Maybe 500 chars max of text on the toast? Or if you’re using multiple text elements, maybe 200 chars per each text element? You’ll want to take into consideration other parts of your payload too, like the launch args, buttons, etc… everything adds up, and you’ll need to keep it under 5 KB.
Hi!
I have a Win32 application and I’ve noticed that when I tap/click the toast to acknowledge it, the focus doesn’t get properly set to my main application (in my toast handler I say MainWindow.Activate() or something similar). I see my application come up, but keyboard focus is not on it. Should i be doing something different?
it seems on toast acknowledge ShellExperienceHost.exe gets focus… and it can’t be taken away unless a physical mouse click or tap touches another application.
Well for what it’s worth I’ve filed a connect bug with a patch file to apply to the github project to reproduce the issue. I’m pretty sure it’s a Win10 bug as on 8.1 this same type of behaviour of putting focus on an element after toast click works fine.
Thanks Johnny, I’ve sent this info to our Win32 dev expert!. | https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/07/02/adaptive-and-interactive-toast-notifications-for-windows-10/?replytocom=6655 | CC-MAIN-2019-13 | refinedweb | 4,695 | 65.32 |
SmartNinja NoSQL - a simple ODM for NoSQL databases: TinyDB, Firestore, Datastore, MongoDB and Cosmos DB.
Project description
SmartNinja NoSQL
About
SmartNinja NoSQL is a simple ODM tool which helps you switch between these NoSQL database systems: TinyDB, Datastore, Firestore, MongoDB and Cosmos DB (via MongoDB API).
TinyDB is used for localhost development. The advantage is that it saves you time configuring a Firestore, Datastore, MonogDB or Cosmos emulator on localhost.
When you deploy your web app to Google App Engine, Heroku or Azure App Service, the ODM figures out the new environment (through env variables) and switches the database accordingly.
Bear in mind that this is a simple ODM meant to be used at the SmartNinja courses for learning purposes. So not all features of these NoSQL databases are covered, only the basic ones.
Installation
Add this dependency in your
requirements.txt:
smartninja-nosql
Make sure to install it locally using this command:
pip install -r requirements.txt
Other dependencies
SmartNinja NoSQL has two mandatory dependencies:
tinydb and
tinydb_serialization. These two help SmartNinja NoSQL use a TinyDB database for localhost development.
Datastore
Google Cloud Datastore dependency in
requirements.txt:
google-cloud-datastore
Firestore
Google Cloud Firestore dependency in
requirements.txt:
google-cloud-firestore
MongoDB & Cosmos DB
To use MongoDB on Heroku or Cosmos DB on Azure App Service, you'll need to add the following library in your
requirements.txt file:
pymongo
Heroku
If you'll use MongoDB on Heroku, make sure to choose the mLab MongoDB add-on.
Environment variables
The environment variables should already be automatically created, but still make sure they (still) have the correct names.
Heroku:
- MONGODB_URI (shows up when you add the mLab MongoDB add-on)
- DYNO (standard Heroku env var, not visible on the dashboard)
Azure:
- APPSETTING_WEBSITE_SITE_NAME (env vars that start with "APPSETTING_" are Azure's standard env vars. Not visible on the dashboard)
- APPSETTING_MONGOURL (shows up when you enable Cosmos DB with the Mongo API)
Google Cloud:
- GAE_APPLICATION (standard GAE env var)
Important: Datastore environment variable
If you'd like to use Datastore on GAE, you must add this piece of code into your
app.yaml file:
env_variables: GAE_DATABASE: "datastore"
If you'd like to use Firestore instead, enter "firestore" or don't have this env. variable at all (Firestore is default).
Usage
Creating classes
This is the simplest way to create classes that use SmartNinja NoSQL:
from smartninja_nosql.odm import Model class User(Model): pass
When you initialize a new object, you can add as many attributes as you want (no need to define them in the User model):
user = User(first_name="Matt", last_name="Ramuta", age=31, human=True)
But usually you'd want to specify at least some mandatory fields in a class:
class User(Model): def __init__(self, first_name, last_name, age, human=True, **kwargs): self.first_name = first_name self.last_name = last_name self.age = age self.human = human self.created = datetime.datetime.now() super().__init__(**kwargs)
As you can see,
last_name and
age are mandatory fields, while
human is optional and has a default value of
True.
The
created field is automatically assigned a value of
datetime.datetime.now().
Important: The
super().__init__(**kwargs) line must be the last one in the
__init__ method! Also
**kwargs must be added as a function parameter.
Custom class methods
Your classes will inherit the following methods from the Model class:
create()
edit()
get_collection()
delete()
get()
fetch()
fetch_one()
But you can of course create your own custom methods. Example:
class User(Model): def __init__(self, first_name, last_name, age, human=True, **kwargs): self.first_name = first_name self.last_name = last_name self.age = age self.human = human self.created = datetime.datetime.now() super().__init__(**kwargs) def get_full_name(self): return "{0} {1}".format(self.first_name, self.last_name)
Creating new objects
user = User(first_name="Matt", last_name="Ramuta", age=31) user.create() print(user.id)
As you can see, creating an object needs two things: initializing an object and saving it into a database with the
create() method. If you don't call this method, the object will not be saved into a database.
The
create() method returns back the object ID, which is automatically created by the database. The ID is also stored in the object itself.
Get one object from the database
You can get an object out of the database if you know its
id:
# Add new object to the database: user = User(first_name="Matt", last_name="Ramuta", age=31) user_id = user.create() # Get the User object from the database new_obj = User.get(obj_id=user_id)
You can also find an object based on some other field using the
fetch_one() method:
# search on one field one_user = User.fetch_one(query=["first_name", "==", "Matt"]) # search on many fields query_age = ["age", ">", 30] query_human = ["human", "==", True] one_user = User.fetch_one(query_age=query_age, query_human=query_human)
Edit an object
You need to pass the object id and the fields you want to edit:
User.edit(obj_id=user_id, first_name="John", age=25)
Delete an object
Call the
delete() method and pass the object id:
User.delete(obj_id=user_id)
Query the database and fetch objects that match the query
You can specify one query:
query = ["first_name", "==", "Matt"] users = User.fetch(query=query) print(users[0].first_name) print(users[0].id)
What you'll get is a list of objects that match the query.
You can also have multiple queries:
query_age = ["age", ">", 30] query_human = ["human", "==", True] users = User.fetch(query_age=query_age, query_human=query_human)
But be aware, that some databases (like Firestore) might require that you create an index for these composite queries.
Important:
- This query structure must be followed (as shown in examples):
["field", "operator", value]. So the field name and the operator must be written in quotes.
- The "not equal" queries ("!=") are not allowed, because Firestore does not support them (although TinyDB and Cosmos DB do).
Enable a TinyDB test database (for localhost testing)
Create an environment variable named
TESTING:
import os os.environ["TESTING"] = "1"
This will create a test TinyDB database:
test_db.json.
How the right database is determined
SmartNinja NoSQL automatically determines which database to use. If the environment has the
GAE_APPLICATION variable, then
the selected database is Firestore (unless you added the
GAE_DATABASE: "datastore" environment variable in
app.yaml).
If SmartNinja NoSQL finds a
APPSETTING_WEBSITE_SITE_NAME it assumes the environment is Azure, so the selected database is Cosmos DB. But if none of these two environment variables is found, the
selected database is TinyDB.
TODO
- Tests
- Continuous integration
- "order" support
- automatic composite index generator for Cloud Datastore (index.yaml)
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/smartninja-nosql/ | CC-MAIN-2020-40 | refinedweb | 1,099 | 56.25 |
A
Service is an application component that can perform
long-running operations in the background, and it doesn't provide a user interface. Another
application component can start a service, and it continues to run in the background even if the
user switches to another application. Additionally, a component can bind to a service to
interact with it and even perform interprocess communication (IPC). For example, a service can
handle network transactions, play music, perform file I/O, or interact with a content provider, all
from the background.
These are the three different types of services:
- Foreground
- A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
- Background
- A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.
Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. In most cases like this, your app should use a scheduled job instead.
- Bound
- A service is bound when an application component binds to it by calling
bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
Although this documentation generally discusses started and bound services separately,
your service can work both ways—it can be started (to run indefinitely) and also allow
binding. It's simply a matter of whether you implement a couple of callback methods:
onStartCommand() to allow components to start it and
onBind() to allow binding.
Regardless of whether your service.
This is discussed more in the section about Declaring the service in the
manifest..
Choosing between a service and a thread
A service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.
If you must perform work outside of your main thread, but only while the user is interacting
with your application, you should instead create a new thread. threads.
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.
The basics
To create a service, you must create a subclass of
Service or use one
of its existing subclasses. In your implementation, you must override some callback methods that
handle key aspects of the service lifecycle and provide a mechanism that allows the components to
bind to the service, if appropriate. These are the most important callback methods that you should
override:
onStartCommand()
- The system invokes this method by calling
startService()when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is complete by calling
stopSelf()or
stopService(). If you only want to provide binding, you don't need to implement this method.
onBind()
- The system invokes this method by calling
bindService()when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an
IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.
onCreate()
- The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either
onStartCommand()or
onBind()). If the service is already running, this method is not called.
onDestroy()
- The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, or receivers. This is the last call that the service receives.
If a component starts the service by calling
startService() (which results in a call to
onStartCommand()), the service
continues to run until it stops itself with
stopSelf() or another
component stops it by calling
stopService().
If a component calls
bindService() to create the service and
onStartCommand() is not called, the service runs
only as long as the component is bound to it. After the service is unbound from all of its clients,
the system destroys it.
The Android system stops a service only when memory is low and it must recover system
resources for the activity that has user focus. If the service is bound to an activity that has user
focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed.
If the service is started and is long-running, the system lowers its position
in the list of background tasks over time, and the service becomes highly susceptible to
killing—if your service is started, you must design it to gracefully handle restarts
by the system. If the system kills your service, it restarts it as soon as resources become
available, but this also depends on the value that you return from
onStartCommand(). For more information
about when the system might destroy a service, see the Processes and Threading
document.
In the following sections, you'll see how you can create the
startService() and
bindService() service methods, as well as how to use
them from other application components.
Declaring a service in the manifest
You must declare all services in your application's manifest file, just as you do for activities and other components.
To declare your service, add a
<service> element
as a child of the
<application>
element. Here is an example:
<manifest ... > ... <application ... > <service android: ... </application> </manifest>
See the
<service> element
reference for more information about declaring your service in the manifest.
There are other attributes that you can include in the
<service> element to
define properties such as the permissions that are required to start the service and the process in
which the service should run. The
android:name
attribute is the only required attribute—it specifies the class name of the service. After
you publish your application, leave this name unchanged to avoid the risk of breaking
code due to dependence on explicit intents to start or bind the service (read the blog post, Things
That Cannot Change).
Caution: To ensure that your app is secure, always use an
explicit intent when starting a
Service and don't declare intent filters for
your services. Using an implicit intent to start a service is a security hazard because you cannot
be certain of the service that responds to the intent, and the user cannot see which service
starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call
bindService() with an implicit intent.
You can ensure that your service is available to only your app by
including the
android:exported
attribute and setting it to
false. This effectively stops other apps from starting your
service, even when using an explicit intent.
Note:
Users can see what services are running on their device. If they see
a service that they don't recognize or trust, they can stop the service. In
order to avoid having your service stopped accidentally by users, you need
to add the
android:description
attribute to the
<service>
element in your app manifest. In the description,
provide a short sentence explaining what the service does and what benefits
it provides.
Creating a started service
A started service is one that another component starts by calling
startService(), which results in a call to the service's
onStartCommand() method.
When a service is started, it has a lifecycle that's independent of the
component that started it. The service can run in the background indefinitely, even if
the component that started it is destroyed. As such, the.
For instance, suppose an activity needs to save some data to an online database. The activity
can start a companion service and deliver it the data to save by passing an intent to
startService(). The service receives the intent in
onStartCommand(), connects to the Internet, and performs the
database transaction. When the transaction is complete, the service stops itself and is
destroyed.
Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service slows down activity performance. To avoid impacting application performance, start a new thread inside the service.
Traditionally, there are two classes you can extend to create a started service:
Service
- This is the base class for all services. When you extend this class, it's important to create a new thread in which the service can complete all of its work; the service uses your application's main thread by default, which can slow the performance of any activity that your application is running..
Kotlin
class HelloService : Service() { private var serviceLooper: Looper? = null private var serviceHandler: ServiceHandler? = null // Handler that receives messages from the thread private inner class ServiceHandler(looper: Looper) : Handler(looper) { override fun handleMessage(msg: Message) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000) } catch (e: InterruptedException) { // Restore interrupt status. Thread.currentThread().interrupt() } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1) } } override fun("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND).apply { start() // Get the HandlerThread's Looper and use it for our Handler serviceLooper = looper serviceHandler = ServiceHandler(looper) } } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show() // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job serviceHandler?.obtainMessage()?.also { msg -> msg.arg1 = startId serviceHandler?.sendMessage(msg) } // If we get killed, after returning from here, restart return START_STICKY } override fun onBind(intent: Intent): IBinder? { // We don't provide binding, so return null return null } override fun onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show() } }
Java
public class HelloService extends Service { private Looper serviceLooper; private ServiceHandler service. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } // doesn't disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler serviceLooper = thread.getLooper(); serviceHandler = new ServiceHandler(servic = serviceHandler.obtainMessage(); msg.arg1 = startId; service(); } } it. The return value
from
onStartCommand() must be one of the following
constants:
START_NOT_STICKY
- If the system kills the service after
onStartCommand()returns, do not recreate the service unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.
START_STICKY
- If the system kills the service after
onStartCommand()returns, recreate (or similar services) that are not executing commands but are running indefinitely and waiting for a job..
For more details about these return values, see the linked reference documentation for each constant.
Starting a service
You can start a service from an activity or other application component by
passing an
Intent
to
startService() or
startForegroundService(). The
Android system calls the service's
onStartCommand() method and passes it the
Intent,
which specifies which service to start.
Note: If your app targets API level 26 or higher, the system
imposes restrictions on using or creating background services unless the app
itself is in the foreground. If an app needs to create a foreground service,
the app should call
startForegroundService(). That method creates a background service, but the
method signals to the system that the service will promote itself to the
foreground. Once the service has been created, the service must call its
startForeground() method within
five seconds.
For example, an activity can start the example service in the previous section (
HelloService) using an explicit intent with
startService(), as shown here:
Kotlin
Intent(this, HelloService::class.java).also { intent -> startService(intent) }
Java
Intent intent = new Intent(this, HelloService.class); startService(intent);
The
startService() method returns immediately, and
the Android system calls the service's
onStartCommand() method. If the service isn't already running, the system first calls
onCreate(), and then it calls
onStartCommand().
If the service doesn't also provide binding, the intent that is delivered with
startService() is the only mode of communication between the
application component and the service. However, if you want the service to send a result back,
the client that starts the service can create a
PendingIntent for a broadcast
(with
getBroadcast()) and deliver it to the service
in the
Intent that starts the service. The service can then use the
broadcast to deliver a result.
Multiple requests to start the service result in multiple corresponding calls to the service's
onStartCommand(). However, only one request to stop
the service (with
stopSelf() or
stopService()) is required to stop it.
Stopping a service
A started service must manage its own lifecycle. That is, the system doesn't stop or
destroy the service unless it must recover system memory and the service
continues to run after
onStartCommand() returns. The
service must stop itself by calling
stopSelf(), or another
component can stop it by calling
stopService().
Once requested to stop with
stopSelf() or
stopService(), the system destroys the service as soon as
possible.
If your service handles multiple requests to
onStartCommand() concurrently, you shouldn't stop the
service when you're done processing a start request, as you might have received a new
start request (stopping at the end of the first request would terminate the second one). To avoid
this problem, you can use
stopSelf(int) to ensure that your request to
stop the service is always based on the most recent start request. That is, when you call
stopSelf(int), you pass the ID of the start request (the
startId
delivered to
onStartCommand()) to which your stop request
corresponds. Then, if the service receives a new start request before you are able to call
stopSelf(int), the ID doesn't match and the service doesn't stop.
Caution: To avoid wasting system resources and consuming
battery power, ensure that your application stops its services when it's done working.
If necessary, other components can stop the service by calling
stopService(). Even if you enable binding for the service,
you must always stop the service yourself if it ever receives a call to
onStartCommand().
For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.
Creating a bound service
A bound service is one that allows application components to bind to it by calling
bindService() to create a long-standing connection.
It generally doesn't allow components to start it by calling
startService().
Create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications through interprocess communication (IPC).
To create a bound service, implement the
onBind() callback method to return an
IBinder that
defines the interface for communication with the service. Other application components can then call
bindService() to retrieve the interface and
begin calling methods on the service. The service lives only to serve the application component that
is bound to it, so when there are no components bound to the service, the system destroys it.
You do not need to stop a bound service in the same way that you must when the service is
started through
onStartCommand().
To create a bound service, you must define the interface that specifies how a client can
communicate with the service. This interface between the service
and a client must be an implementation of
IBinder and is what your service must
return from the
onBind() callback method. After the client receives the
IBinder, it can begin
interacting with the service through that interface.
Multiple clients can bind to the service simultaneously. When a client is done interacting with
the service, it calls
unbindService() to unbind.
When there are no clients bound to the service, the system destroys the service.
There are multiple ways to implement a bound service, and the implementation is more complicated than a started service. For these reasons, the bound service discussion appears in a separate document about Bound Services.
Sending notifications to the user
When a service is running, it can notify the user of events using Toast Notifications or Status Bar Notifications.
A toast notification is a message that appears on the surface of the current window for only a moment before disappearing. A status bar notification provides an icon in the status bar with a message, which the user can select in order to take an action (such as start an activity).
Usually, a status bar notification is the best technique to use when background work such as a file download has completed, and the user can now act on it. When the user selects the notification from the expanded view, the notification can start an activity (such as to display the downloaded file).
See the Toast Notifications or Status Bar Notifications developer guides for more information.:
Kotlin
val pendingIntent: PendingIntent = Intent(this, ExampleActivity::class.java).let { notificationIntent -> PendingIntent.getActivity(this, 0, notificationIntent, 0) } val notification: Notification =)
Java
Intent notificationIntent = new Intent(this, ExampleActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new);.
Managing the lifecycle of a service
The lifecycle of a service is much simpler than that of an activity. However, it's even more important that you pay close attention to how your service is created and destroyed because a service can run in the background without the user being aware.
The service lifecycle—from when it's created to when it's destroyed—can follow either of these two paths:
- A started service
The service is created when another component calls
startService(). The service then runs indefinitely and must stop itself by calling
stopSelf(). Another component can also stop the service by calling
stopService(). When the service is stopped, the system destroys it.
- A bound service
The service is created when another component (a client) calls
bindService(). The client then communicates with the service through an
IBinderinterface. The client can close the connection by calling
unbindService(). Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. The service does not need to stop itself.
These two paths aren't entirely separate. You can bind to a service that is already
started with
startService(). For example, you can
start a background music service by calling
startService() with an
Intent that identifies the music to play. Later,
possibly when the user wants to exercise some control over the player or get information about the
current song, an activity can bind to the service by calling
bindService(). In cases such as this,
stopService() or
stopSelf() doesn't actually stop the service until all of the clients unbind.
Implementing the lifecycle callbacks
Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service demonstrates each of the lifecycle methods: mStartMode } override fun
onBind(intent: Intent): IBinder? { // A client is binding to the service with bindService() return mBinder } override fun
onUnbind(intent: Intent): Boolean { // All clients have unbound with unbindService() return mAllow mStartMode; } @Override public IBinder
onBind(Intent intent) { // A client is binding to the service with
bindService()return mBinder; } @Override public boolean
onUnbind(Intent intent) { // All clients have unbound with
unbindService()return mAllowRebind; } @Override public void
onRebind(Intent intent) { // A client is binding to the service with
bindService(), // after onUnbind() has already been called } @Override public void
onDestroy() { // The service is no longer used and is being destroyed } }
Note: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods.
Figure 2. The service lifecycle. The diagram on the left
shows the lifecycle when the service is created with
startService() and the diagram on the right shows the lifecycle when the service is created
with
bindService().
Figure 2 illustrates the typical callback methods for a service. Although the figure separates
services that are created by
startService() from those
created by
bindService(), keep
in mind that any service, no matter how it's started, can potentially allow clients to bind to it.
A service that was initially started with
onStartCommand() (by a client calling
startService())
can still receive a call to
onBind() (when a client calls
bindService()).
By implementing these methods, you can monitor these two nested loops of the service's lifecycle:
- The entire lifetime of a service occurs between the time that
onCreate()is called and the time that
onDestroy()returns. Like an activity, a service does its initial setup in
onCreate()and releases all remaining resources in
onDestroy(). For example, a music playback service can create the thread where the music is played in
onCreate(), and then it can stop the thread in
onDestroy().
Note: The
onCreate()and
onDestroy()methods are called for all services, whether they're created by
startService()or
bindService().
- The active lifetime of a service begins with a call to either
onStartCommand()or
onBind(). Each method is handed the
Intentthat was passed to either
startService()or
bindService().
If the service is started, the active lifetime ends at the same time that the entire lifetime ends (the service is still active even after
onStartCommand()returns). If the service is bound, the active lifetime ends when
onUnbind()returns.
Note: Although a started service is stopped by a call to
either
stopSelf() or
stopService(), there isn't a respective callback for the
service (there's no
onStop() callback). Unless the service is bound to a client,
the system destroys it when the service is stopped—
onDestroy() is the only callback received.
For more information about creating a service that provides binding, see the Bound Services document,
which includes more information about the
onRebind()
callback method in the section about Managing the lifecycle of
a bound service. | https://developer.android.com/guide/components/services.html?hl=de | CC-MAIN-2020-05 | refinedweb | 3,826 | 51.78 |
So I've been over Traiblazer and Reform documentation and I often see this kind of code
class AlbumForm < Reform::Form
collection :songs, populate_if_empty: :populate_songs! do
property :name
end
def populate_songs!(fragment:, **)
Song.find_by(name: fragment["name"]) or Song.new
end
end
def populate_songs!(fragment:, **)
**others
**
what does
**mean in the block above?
It's a kwsplat, but it's not assigned a name. So this method will accept arbitrary set of keyword arguments and ignore all but
:fragment.
why use this syntax?
To ignore arguments you're not interested in.
A little demo
class Person attr_reader :name, :age def initialize(name:, age:) @name = name @age = age end def description "name: #{name}, age: #{age}" end end class Rapper < Person def initialize(name:, **) name = "Lil #{name}" # amend one argument super # send name and the rest (however many there are) to super end end Person.new(name: 'John', age: 25).description # => "name: John, age: 25" Rapper.new(name: 'John', age: 25).description # => "name: Lil John, age: 25" | https://codedump.io/share/lbRsoxVEulQU/1/what-does-double-splat--argument-mean-in-this-code-example-and-why-use-it | CC-MAIN-2019-13 | refinedweb | 165 | 60.92 |
You can subscribe to this list here.
Showing
1
results of 1
Paul,
I want to thank you for providing such thorough help on this issue. It
turns out I was 90% of the way there and just needed to connect a few
more dots.
What I Learned
--------------
My main misunderstanding was related to how parse actions and
ParseResults work together. I now understand that a parse action is
passed a ParseResult that functions like a list of tokens. Actually, it
is a list of whatever is returned from deeper calls of parsing, so it
can be tokens or AST objects or whatever. This list of children is
accessed via ParseResult.asList(). So all a parse action has to do to
create an AST is package up its children appropriately into some AST
object and return that object.
If you take this approach groups are unnecessary. I only used a group
once when I needed to handle multiplicity in one of the children of a
pyparsing element and didn't want to create another pyparsing element
specifically for that "sub-expression". (I effectively combined multiple
levels/elements in my grammar into one pyparsing element and thus needed
a bit of extra structure.)
For example (sufficient excerpts to illustrate):
def getAstFromParseResult(parseResult):
return parseResult.asList()[0]
# Packages a single token as an atomic AST object
def astVariableParseAction(parseResult):
return ('variable', getAstFromParseResult(parseResult))
# Packages named "sub-expressions" into an AST object
# "head" is an AST object from a deeper call
# "body" can have multiple children in the AST, so the whole ParseResult
list is incorporated
def astClauseParseAction(parseResult):
return ('clause',
('head', parseResult.head),
('body', parseResult.body.asList()))
clause.setParseAction(astClauseParseAction)
Further response
----------------
In my case I really do need an AST and strings are my "object
representation." My task is to parse the Prolog, gather some information
about it, compile some related information from a different source, and
spit out the original with annotations as comments. The annotations
include both specific and aggregate information so I need to process the
whole AST before starting output. In the process I do end up converting
a few parts of the AST to objects (e.g. certain integers that are keys
for other information), but the majority of the AST elements need no
conversion and all have to be output as strings, so a "full" object
representation would actually be more work.
Prior to asking for help, I looked at some of the examples but most of
them seemed to concentrate on implementing the grammar, not dealing with
the results of parsing. No example description includes "ast" or "tree".
Unfortunately, SimpleBool.py would not have helped clarify things for me
as there is no mention of parse actions or parse results which were my
main confusions.
Feature Suggestion
------------------
Some form of incremental parsing would be a nice addition. I am thinking
of situations (like Prolog) where you have many top-level elements to
parse, but each is relatively simple. It would be nice to be able to
parse them one-by-one in an iterative fashion:
# lang :: ( comment | fact | clause )*
for langElement in lang.parseIncremental(input):
if langElement.name == 'fact':
...
elif langElement.name == 'clause':
...
...
This would allow parsing to scale well to large inputs as an entire AST
would never have to be constructed. The only complication is handling
when the repetition is a few levels down in the grammar (like class
members in Java or body elements in HTML for example). (I could probably
retrofit my task to the incremental model and see some fair efficiency
gains.)
Aubrey
On 09/29/2011 01:10 AM, Paul McGuire wrote:
> Aubrey -
>
> If all you want is an AST, then you should be able to construct this using
> Group's and parseActions. For instance, let's say you want a parser for an
> assignment statement, where the lvalue can be a variable and the rvalue can
> be simple expression, with terms that can be integers, variables, or
> function calls.
>
> """
> Simple BNF:
>
> assignment :: lvalue '=' rvalue
> lvalue :: variableRef
> rvalue :: term [ op term ]
> term :: fnCall | variable | integer
> fnCall :: fnName '(' [rvalue[,rvalue]*] ')
> variable :: [a-zA-Z_][a-zA-Z0-9_]*
> integer :: \d+
> op :: '+' | '-'
> """
>
> from pyparsing import *
>
> LPAR,RPAR,EQ = map(Suppress, "()=")
> op = oneOf("+ -")
> integer = Word(nums)
> identifier = Word(alphas+'_', alphanums+'_')
> variableRef = identifier.copy()
> fnName = identifier.copy()
> rvalue = Forward()
> arglist = delimitedList(rvalue)
> fnCall = fnName + Group(LPAR + Optional(arglist, default=[]) + RPAR)
> rvalue<< (fnCall | variableRef | integer)
> assignment = variableRef + EQ + Group(rvalue)
>
> print assignment.parseString("y = sin(60)-180").asList()
>
> Will print:
>
> ['y', ['sin', ['60']]]
>
> Knowing that this was an assignment statement, you could then use assignment
> unpacking to pull out the left and right hand sides of the assignment:
>
> lhs, rhs = assignment.parseString("...").asList()
>
>
> With some simple parse actions, you can decorate these structures similar to
> what you show in your AST example:
>
> assignment.setParseAction(lambda t : ['assign'] + t.asList())
> fnCall.setParseAction(lambda t : ['function-call'] + t.asList())
> print assignment.parseString("y = sin(60)-180").asList()
>
> will print:
>
> ['assign', 'y', ['function-call', 'sin', ['60']]]
>
>
> But now I have to ask, what do you plan to do with this AST? I suspect that
> the next step is to walk the structure, and perform actions depending on the
> decorating labels. Instead, I would suggest you use the parse actions to
> construct representational objects. At parse time, you already know what
> the substructures are going to be ("a function call will have a name and a
> potentially empty argument list" for instance), why not use a parse action
> to construct an object that gives a representation for this?
>
> class ASTNode(object):
> def __init__(self, tokens):
> self.tokens = tokens
> self.assignFields()
> def __str__(self):
> return self.__class__.__name__ + ':' + str(self.__dict__)
> __repr__ = __str__
>
> class Assignment(ASTNode):
> def assignFields(self):
> self.lhs, self.rhs = self.tokens
> del self.tokens
>
> class FunctionCall(ASTNode):
> def assignFields(self):
> self.fnName, self.args = self.tokens
> del self.tokens
> fnCall.setParseAction(FunctionCall)
> assignment = (variableRef + EQ + rvalue).setParseAction(Assignment)
>
> print assignment.parseString("y = sin(60)-180")[0]
>
> Will print:
>
> Assignment:{'rhs': FunctionCall:{'fnName': 'sin', 'args': (['60'], {})},
> 'lhs': 'y'}
>
>
> Now we have bypassed the intermediate AST step, and gone straight to an
> object representation. These classes can be extended to include an eval or
> exec method, which could be directly called, instead of retracing steps
> already taken during parse time - why test args with isdigit, for instance?
> At parse time, your grammar already defines when an integer is being
> encountered - just add a parse action that does the string-to-integer
> conversion.
>
> I think the SimpleBool.py example on the pyparsing wiki gives a more
> complete treatment of this concept. In the article I wrote for Python
> magazine, I showed how you could even pickle these representational objects,
> and then unpickle and execute them in varying VM's (GUI, console, server)
> without reparsing the original code.
>
> If you just want an AST, use Groups to add structure, and parse actions to
> decorate the groups with your AST structure labels. I think though that the
> representational objects are more powerful.
>
> -- Paul
>
>
>
>
> -----Original Message-----
> From: Aubrey Barnard [mailto:barnard@...]
> Sent: Wednesday, September 28, 2011 7:35 PM
> To: pyparsing-users@...
> Subject: [Pyparsing] ParseResults as AST?
>
> Pyparsing users,
>
> I am having trouble figuring out how to make an abstract syntax tree
> (AST) from a ParseResults object. I do not understand the data model
> that is the ParseResults object as it relates to holding the information
> of an AST. (I have spent a whole day on this so far, so it is time to
> ask for help.)
>
> I am writing a Prolog parser, so I really do need an AST as opposed to
> some flattened representation like ParseResults. Order matters. Type
> matters. Depth matters.
>
> Sample Input
> ------------
>
> This is only Datalog with atoms, integers, and variables.
>
> '''
> % Facts
> r1(a). r1(b). r1(c).
> r2(a, 1). r2(a, 2). r2(d, 3). r2(e, 4).
> % Clauses
> r3(A, B) :-
> r1(A),
> r2(A, B).
> '''
>
> Desired Output
> --------------
>
> I would like to get something back from parsing like the following:
>
> ('datalog',
> [
> ('comment', '% Facts'),
> ('fact', [('name', 'r1'), ('body', [('atom', 'a')])]),
> ('fact',<result>),
> ...
> ('clause', [('head',<result>), ('body', [<result>...])]),
> ]
> )
>
> where<result> stands for the parse result from deeper recursion. The
> structure is just lists of pairs. Each pair is the name (type) of the
> parsed object and its content, the result.
>
> Parsing
> -------
>
> I believe I have my grammar implemented correctly in pyparsing as I get
> the expected AST back as XML by calling ParseResults.asXML(). (Except
> that I have an extra top-level element,
> "<datalog><datalog>...</datalog></datalog>", but that is easy to
> workaround.)
>
> Tried
> -----
>
> I have tried to understand the ParseResults object. Clearly the AST
> information exists as ParseResults.asXML() gives me an AST in XML.
> However, some of the information used in asXML() is not part of the
> public API.
>
> I have tried to use parse actions to construct my own AST but I couldn't
> figure this out either (in part because the product of parsing is still
> a ParseResults object).
>
> Options
> -------
>
> * Use asXML() and reparse the XML. Not performant. Too much code. Misses
> the point.
> * Write asAST() into pyparsing.py as a near clone of asXML(). This is my
> current favorite option. (I'm on a deadline.)
> * Use parse actions effectively.
> * Use a different parsing library (I have also tried pyPEG.)
> * Other?
>
> Any suggestions and/or help would be very much appreciated.
>
> Sincerely,
>
> Aubrey
>
> ----------------------------------------------------------------------------
> --
> All the data continuously generated in your IT infrastructure contains a
> definitive record of customers, application performance, security
> threats, fraudulent activity and more. Splunk takes this data and makes
> sense of it. Business sense. IT sense. Common sense.
>
> _______________________________________________
> Pyparsing-users mailing list
> Pyparsing-users@...
>
> | http://sourceforge.net/p/pyparsing/mailman/pyparsing-users/?viewmonth=201110 | CC-MAIN-2014-23 | refinedweb | 1,599 | 55.84 |
View Full Document
This
preview
has intentionally blurred sections.
Unformatted text preview: CS 61B, MT2 Version B, Spring 1999 CS 61B, Spring 1999 MT2 Version B Professor M. Clancy Background Some of the problems on this exam involve intevals of integers . (Note the difference between these intervals and thsoe you worked with in homework assignment 4, which represented intervals on the real number line.) The interval [a,b] represents all the integers that are greater than or equal to a and less than or equal to b . For example, [3,5] represents the set of integers {3, 4, 5} , [-5,-4] represents the set {-5,-4} , and the interval [5,3] represents the empty set. The Interval class is defined as follows. public class Interval { private int myLeft; private int myRight; // Constructor. public Interval (int left, int right) { ... } // Return this 's left endpoint. public int left ( ) { return myLeft; } // Return this 's right endpoint. public int rightt ( ) { return myRight; } // Return a hash value for this. public int hashCode ( ) { ... } // Return exactly when this represents the smae interval as intvl. public boolean equals (Interval intvl) { ... } // Return true exactly when this contains x. public boolean contains (int x) { ... (1 of 4)1/27/2007 6:33:04 PM CS 61B, MT2 Version B, Spring 1999 } // Return true when this overlaps intvl, // i.e. contains integers in common with intvl. public boolean overlaps (Interval intvl) {......
View Full Document
- Spring '01
- Canny
- Computer Science, hash function, Bloom filter, Cryptographic hash function, CS 61B
Click to edit the document details | https://www.coursehero.com/file/3251933/Computer-Science-61B-Spring-1999-Clancy-Midterm-2/ | CC-MAIN-2017-51 | refinedweb | 253 | 68.26 |
Today we are pleased to announce that Beats 5.2.0 was released. This is the latest stable version and it comes with a few goodies like uptime monitoring, network connections tracking, and the Prometheus exporters integration, enough good reasons to upgrade.
Latest stable release:
Heartbeat, for uptime monitoring
Heartbeat (Beta) is the newest addition to the official Elastic Beats. It periodically checks the status of your services to determine whether they are available and measures the round-trip-time. Like all the other Beats, Heartbeat is lightweight and has no dependencies, so you can install it on multiple locations in your infrastructure and monitor reachability in a distributed fashion.
The idea for Heartbeat came from the Elastic Cloud team, who is using it already for monitoring thousands of Elasticsearch and Kibana clusters. A second source of inspiration was one of the first community Beats, Pingbeat, written by Joshua Rich.
Heartbeat can also be useful for scenarios other than uptime monitoring, such as security use cases, when you need to verify that no one from the outside can access the services on your private enterprise server.
With Heartbeat you can monitor a list of hosts via:
- ICMP (IPv4 and Ipv6) Echo Requests to check whether a service is available. Note that ICMP requires root access.
- TCP to check whether you can connect via TCP to the service. You can optionally verify the endpoint by sending and/or receiving a custom payload
- HTTP to check whether you can connect via HTTP to the service. You can optionally verify that the service returns the expected response, such as specific status code, response header, or content.
Here is an example configuration for using the HTTP monitor to check an Elasticsearch endpoint:
# Configure monitors heartbeat.monitors: - type: http # List or urls to query urls: [""] # Configure task schedule schedule: '@every 10s' # Total test connection and data exchange timeout #timeout: 16s
Heartbeat already supports automatic configuration reloading, so you can dynamically add or remove monitored targets without restarting.
By default, it monitors one IP address for a hostname, but it has support for pinging all resolvable IPs for a hostname. This is useful if you are using a DNS-load balancer and want to ping every IP address for the specified hostname.
Heartbeat is released as Beta in 5.2.0, and we do not recommend to use it in production during the Beta phase.
Track network connections with Metricbeat
Starting with the 5.2 release, Metricbeat exports the network connections between your applications on Linux systems, so you can see the traffic exchanged between services. The system.socket metricset was added. For each TCP socket, it reports the process that opened the socket, the local and remote IPs involved in the communication, and the direction (incoming, outgoing or listening). It can also perform a reverse lookup on the remote IP.
Metricbeat gets the network connections by polling the Linux kernel to get the sockets, so a short polling interval is recommended to catch short lived connections.
Because data gets more valuable when you can visualize it, here is a sample of using Graph to visualize the network connections:
Collect metrics from Prometheus exporters
Starting with the 5.2.0 release, Metricbeat comes with a Prometheus module that collects metrics from the Prometheus exporters or any application that offers a Prometheus endpoint and indexes them to Elasticsearch.
With this module, you can use the Elastic Stack to monitor apps instrumented with the Prometheus libraries, or monitor services for which a Prometheus exporter exists but for which we don’t have a Metricbeat module yet.
To fetch metrics periodically from a Prometheus exporter, you just need to configure collector as part of
metricsets and add the host from where to pull the metrics. The metric will be exported under the field configured in
namespace. With this, Metricbeat adds support for dynamic metrics where the metrics and their types are not known in advance. While the Prometheus module can be used to get data from a variety of systems, we recommend using the native Metricbeat modules when they are available, because they structure the data in a way that matches the Elastic stack better.
For example to collect metrics from jmx exporter and Varnish exporter, you can use the following configuration:
- module: prometheus metricsets: ["collector"] enabled: true period: 10s hosts: ["localhost:5555"] namespace: jmx - module: prometheus metricsets: ["collector"] enabled: true period: 10s hosts: ["localhost:9131"] namespace: varnish
The Prometheus module in Metricbeat is released as experimental in 5.2.0, and we reserve the right to do breaking compatibility changes.
Feedback
If you want to make use of the new features added in Beats 5.2.0, please download the latest stable version, install it, and let us know what you think on Twitter (@elastic) or in our forum. | https://www.elastic.co/jp/blog/beats-5-2-0-released | CC-MAIN-2017-22 | refinedweb | 801 | 50.06 |
We're working on an app that displays a lot of user-generated data, so we frequently have to deal with the potential for text overflow. Most UI frameworks provide the ability to truncate the text and show an ellipsis (...) to indicate additional text is not shown.
I don't see a direct way to do this in the new 4.6 UI. Is there any good way to do this manually?
Thanks in advance, --Bob
Answer by drod7425
·
Feb 12, 2015 at 08:32 PM
Something I've been wanting to do for a while now. Create this UI structure in your scene:
Text (default Text with some long test text)
Ellipsis (default Text with text '...', Layout Element with a min width)
And here is the script that goes on the TextOverflowEllipsis gameobject:
using UnityEngine;
using UnityEngine.UI;
public class TextOverflowEllipsis : MonoBehaviour {
public Text text;
public GameObject ellipsis;
RectTransform parentRect;
float textWidth,parentWidth;
string textStr="";
void Start () {
parentRect = GetComponent<RectTransform>();
}
void Update () {
if(text.text != textStr || !parentRect.rect.width.AlmostEquals(parentWidth,.01f)){ //If the current text is not the same as the cached text or the container width changes
CheckTextWidth(); //Check the text's width
textStr = text.text;
}
}
void CheckTextWidth() {
textWidth = LayoutUtility.GetPreferredWidth(text.rectTransform); //This is the width the text would LIKE to be
parentWidth = parentRect.rect.width; //This is the actual width of the text's parent container
ellipsis.SetActive(textWidth > parentWidth); //If the text width is bigger than the container, show the ellipsis
}
}
Just set the Text component of the Text gameobject to the 'text' field and the Ellipsis gameobject to the 'ellipsis' field in the inspector of the TextOverflowEllipsis gameobject. After that, you can just design the Text and Ellipsis to match your current style.
@drod7425, this is helpful, but it doesn't tell you where to put the ellipses. If I know the text gets cut off, how do I know what the last word shown is, after which the ellipses should appear? I guess with ellipses you could just display them in a separate Text, but I have a similar problem where I'd like the extra text to overflow into another text box. Any advice?
Text
Answer by raulssorban
·
Aug 19, 2016 at 12:11 AM
Hey, this is my (simple) way to do it:
Check the text's length, as:
if(text.Length > calculatedSize); text.Remove (calculatedSize) + "...";
Simple as that.
Simple and elegant! And most important! Works as simple it must be! Thanks for sharing with us!
Thanks, glad it helped you!
Answer by TheMoot
·
Jan 28, 2016 at 01:25 PM
If anyone is looking for a different solution to this this is how I did it. I wrote a simple extension to the text class in unity.ui
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TextTruncExt : Text
{
string updatedText = string.Empty;
protected override void OnPopulateMesh(VertexHelper toFill)
{
Vector2 extents = rectTransform.rect.size;
var settings = GetGenerationSettings(extents);
cachedTextGenerator.Populate(base.text, settings);
float scale = extents.x / preferredWidth;
//text is going to be truncated,
//cant update the text directly as we are in the graphics update loop
if (scale < 1)
{
updatedText = base.text.Substring(0, cachedTextGenerator.characterCount-4);
updatedText += "...";
}
base.OnPopulateMesh(toFill);
}
void Update()
{
if(updatedText != string.Empty && updatedText != base.text)
{
base.text = updatedText;
}
}
}
Its not the most efficient way but it works. It currently just cuts off the string and adds the ellipsis. You could easily make it cut back to the next space then add the ellipsis if you only wanted whole words.
Hope this helps someone.
Answer by Asmodeus
·
Feb 05, 2015 at 05:01 AM
I'm trying to figure this out as well. This article is kinda old.
Answer by CalebBarton
·
Sep 05, 2018 at 05:35 AM
I'm going to post an answer, as this page came up as my first search response, but there's a very simple solution.
This link has a very simple solution:
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}
Usage:
var s = "abcdefg";
Console.WriteLine(s.Truncate(3));
So when setting the text value, you can pass in the text through the truncate function first. You could also create a listener for the text value changing if you wanted to get technical with it. Hope this helps.
New UI: Text scale/drawing problem
1
Answer
Unity 4.6 UI Text is really small when I build the game?
1
Answer
Best method for updating children of instantiated buttons?
0
Answers
What's your equivalent of old GUIStyle ?
0
Answers
Try to reproduce this Text UI element "bug" if you are developing for IOS
0
Answers | https://answers.unity.com/questions/836642/new-ui-46-how-to-show-ellipsis-for-text-overflow.html | CC-MAIN-2019-09 | refinedweb | 780 | 66.44 |
Welcome Guys, till now we have seen a lot about this series, in this module, we are going to talk about what is loop statement in C Programming, like suppose if you want to repeat a set of expressions many times then for that purpose C provides the concepts of loops in programming.
So, let’s dive into the depth of this particular concept.
What is Loop Statement in C?
Loops are often called an iteration statement in programming i.e. if you want to repeat a particular statement or expressions a particular number of times. It executes a statement multiple times until the condition results to be false.
Loops consist of two parts i.e., loop body and a control condition. The control condition consists of a set of statements that directs the loop body to be executed, i.e., the loop body will get executed until the condition results to be false.
In simple, we can say that loops are used to repeat a particular block until some specified condition is met. C Programming provides us three types of loops for meeting the looping requirements.
- While loop
- Do-while loop
- For loop
Let’s see each of them in detail.
What is While loop in C Programming?
It is the simplest kind of loop and more straightforward. It evaluates a certain condition. It first checks the condition and if it is true, then it allows the program to enter inside the loop body, and as the condition fails, the program comes out of the loop. The syntax for declaring the while loop is:
while (expression) { // statement to be executed or repeated }
After getting out of the loop, the program executes the very first statement written outside the loop. The loop body can contain more than one statement to be repeated, as per the requirement by the programmer. If the loop body contains only one statement then there is no need for curly braces, however, if there is more than one statement in the loop body, then curly braces are important. Although it is a good practice to use curly braces while programming, that’s the work of the smart coder.
Let’s see one example demonstrating a while loop.
#include <stdio.h> int main( ) { int n = 15; while (n>0) { printf("%d ",n); n = n - 1; } printf("Loop body finished"); return 0; }
In the above program, we have initialized the variable n to value 15, then we have used while loop and the condition are that the value of n should be greater than 0, and in the loop body we have printed the value of n and then decrementing the value of n by 1, so this case the loop body will keep executing until or unless the value of n becomes less than 1. Hence, we got the output.
What is a do-while loop in C Programming?
It is very similar to the while loop, the only difference is that the condition is checked at the last. The body of the loop is executed at least once if the condition gets never fulfilled also because the condition is declared at the last of the loop body. The syntax for declaring the same is.
do { // statement to be executed or repeated } while (condition);
Notice that the condition is at the last with the while statement.
#include <stdio.h> int main() { int n; do { printf("Enter value: "); scanf("%d", &n); printf("The value is: %d\n",n); } while (n != 20); printf("do-while loop body finished"); return 0; }
The output of the above code is:
In the above program, inside the do block, we have performed several actions like taking the input and displaying the same, whereas the condition is given is that the value entered should not be equal to 20, as the user enters the value 20, the program will come out of the loop.
What is for loop in C Programming?
It is the most used loop in C Programming, and is more efficient also, this loop is designed to iterate a statement a number of times. Like while loop, for loops, also checks the condition first then allows executing a certain block. The syntax for declaring the for loop is:
for (initialization; condition; increment/decrement) { // statement to be executed }
It works in the following ways:
- Initialization is performed only once in the for a loop.
- The condition is the set of expressions that tests and compares to a fixed value for each iteration. It stops the iterations if the condition results to be false.
- The increment or decrement changes the condition value as per required.
Let’s see some examples to get the concept clearer.
#include <stdio.h> int main() { int i; for (i=0; i<10; i++) { printf("%d ", i); } printf("for loop body finished"); return 0; }
The output of the above code is:
In the above code, we are printing the value 0-9 with the help of for loop, firstly we have initialized the value to 0, and then we have given the condition that the value should be less than 10 and the increment the value. Hence, we got the output.
What is the difference between entry controlled loop and exit controlled loop in c programming
We have talked about three types of loops till now, so these loops lie under two categories and which are entry controlled and exit controlled loops. So, let’s see the difference in both to get more clearer.
I hope you all enjoyed learning this module, it is the most exciting topic of the series, Stay connected for upcoming modules.
Keep Learning, Keep Practicing, Happy Coding! | https://usemynotes.com/what-is-loop-statement-in-c/ | CC-MAIN-2021-43 | refinedweb | 943 | 67.79 |
<Blog x:
I was recently tasked with learning PRISM… The next few post will document my learning experience! PLEASE NOTE: I have no experience with previous technologies like CAB… This is truly my idiots opinion about what I have learned trying out PRISM!
I have identified some key “things” I MUST know in order to use PRISM (This list might change in the future). As I learn more about each one of these… I will post about it! The first item on my list is Unity!
“The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.”
If you want to learn more about dependency injection and IoC, here are some resources that helped me:
IoC and Unity - The Basics and Interception
IMHO… Their are 2 key things that unity provide that I should know. Lets look at the following interface
public interface ILogger
{
void LogSomething();
}
And lets create a concrete class implementing this interface
public class ConsoleLogger : ILogger
{
public void LogSomething()
{
Console.WriteLine("ConsoleLogger.LogSomething()");
}
}
This now makes it very simple for me to in the future create a different logger (ie. SqlLogger, TraceLogger, etc) and swap them at my will!
ILogger logger = new ConsoleLogger();
The only problem with the code above is that I am now tightly coupled to the ConsoleLogger… I actually need to reference the namespace in which I created ConsoleLogger!
This is were the IoC/DI stuff helps! Lets create a container
IUnityContainer container = new UnityContainer();
And then I can register types or instances with this container
container.RegisterType<ILogger, ConsoleLogger>();
and now if I ask my container for a ILogger… It will take care of creating the correct concrete class
ILogger logger = container.Resolve<ILogger>();
The code that actually creates the instance of ILogger, doesn’t need any knowledge of the concrete class!!!
It is actually very simple to create a basic IoC container yourself, here are some examples
Understanding IoC Container - sfeldman.NET
Building an IoC container in 15 lines of code
Ken Egozi's IOC in 15 lines
OK, that is the first key “thing”… The next “thing” is the dependency injection… Lets build on our first example that has a logger! Now we also have a CustomerRepository that depends on the ILogger
public class CustomerRepository : ICustomerRepository
{
ILogger _logger;
public CustomerRepository(ILogger logger)
{
_logger = logger;
}
public void GetACustomer()
{
_logger.LogSomething();
}
}
How does unity help us out here? Well, how would this have been done without unit?
ICustomerRepository repository = new CustomerRepository(new ConsoleLogger);
Do you see the tightly coupled stuff? Not so good! Assuming we already have a unity container and a logger registered… here is the unity way
ICustomerRepository repository = container.Resolve<CustomerRepository>();
I supply no parameters… The unit container auto-magically resolves it!!!
This only scratches the surfaces of what IoC/DI is capable of… Also remember that Unity is by no means the only one of its kind… here is a cool list of other containers!!!
And that concludes my first baby steps into the world of loosely coupled applications, Inversion of Control, Dependency Injection and much more…
[UPDATE] More Resources
.NET Hitman has a nice article about IoC & Unity
Andrey Shchekin has a nice 2 part post about comparing popular the IoC containers (Part 1 & Part 2)
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Very intresting topic. Will be waiting for new posts. I've been using CompositeWPF (former Prism) for some time and guess it's worth writing about :)
Pingback from 2008 September 08 - Links for today « My (almost) Daily Links
If you missed the first post in this series, please read it first. I received quite a few emails in response
Background Learning PRISM – Unity Learning PRISM – Unity Redux Modularity is not a new concept! Here | http://dotnet.org.za/rudi/archive/2008/09/05/learning-prism-05-09-2008.aspx | crawl-002 | refinedweb | 633 | 51.48 |
This section will help you to understand LinkedList in Java. How to create LinkedList, how to Add element in LinkedList, how to Remove element from the LinkedList etc.
AdsTutorials
LikedList implements List interface which perform all operation like add, remove, delete etc. LinkedList class provide method to insert, remove , to get the element, insert at the beginning. These operation allow linkedList to use as stack, queue, dequeue. This class can implement dequeue interface which provide first in first out, for add, remove along with other stack operation. The operation which perform adding or removing element will traverse the element from beginning and end of the list.
LinkedList has following constructor:
LinkedList class define some useful method which manipulate and access the element.
Some of the element of linked list are as follows:
The following program will illustrate the LinkedList example
import java.util.*; public class LinkedListDemo { public static void main(String args[]) { LinkedList
list = new LinkedList (); // add elements to the linked list list.add("W"); list.add("B"); list.add("K"); list.add("H"); list.add("L"); list.addLast("Z"); list.addFirst("A"); list.add(1, "A2"); System.out.println("Original contents of list: " + list); // remove elements from the linked list list.remove("B"); list.remove(3); System.out.println("Contents of list after deletion: "+ list); // remove first and last elements list.removeFirst(); list.removeLast(); System.out.println("list after deleting first and last: "+ list); // get and set a value System.out.println("list after change: " + list); } }
Output from the program:
Advertisements
Posted on: July 6, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: Linked List Example In Java
Post your Comment | http://roseindia.net/java/jdk6/java-LinkedListExample.shtml | CC-MAIN-2017-13 | refinedweb | 286 | 55.64 |
In my previous post I described the need to run one-off asynchronous tasks on app start up. This post follows on directly from the last one, so if you haven't already, I suggest you read that one first.
In this post I show a proposed adaptation of the "run the task manually in program.cs" approach from my last post. The implementation uses a few simple interfaces and classes to encapsulate the logic of running tasks on app start up. I also show an alternative approach that uses service decoration of
IServer to execute tasks before Kestrel starts.
Running asynchronous tasks on app startup
As a recap, we're trying to find a solution that allows us to execute arbitrary asynchronous tasks on app start up. These tasks should be executed before the app starts accepting requests, but may require configuration and services, so should be executed after DI configuration is complete. Examples include things like database migrations, or populating a cache.
The solution I proposed at the end of my previous post involved running the task "manually" in Program.cs, between the calls to
IWebHostBuilder.Build() and
IWebHost.Run(): listeningaccepting requests // There's an async overload, so we may as well use it await webHost.RunAsync(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }
This approach works, but it's a bit messy. We're going to be bloating the Program.cs file with code that probably shouldn't be there, but we could easily extract that to another class. More of an issue is having to remember to invoke the task manually. If you're using the same pattern in multiple apps, then it would be nice to have this handled for you automatically.
Registering startup tasks with the DI container
The solution I'm proposing is based on the patterns used by
IStartupFilter and
IHostedService. These interfaces allow you to register classes with the dependency injection container which will be executed later.
First, we create a simple interface for the startup tasks:
public interface IStartupTask { Task ExecuteAsync(CancellationToken cancellationToken = default); }
And a convenience method for registering startup tasks with the DI container:
public static class ServiceCollectionExtensions { public static IServiceCollection AddStartupTask<T>(this IServiceCollection services) where T : class, IStartupTask => services.AddTransient<IStartupTask, T>(); }
Finally, we add an extension method that finds all the registered
IStartupTasks on app startup, runs them in order, and then starts the); } }
That's all there is to it!
To see it in action, I'll use the EF Core database migration example from the previous post.
An example - async database migration
Implementing
IStartupTask is very similar to implementing
IStartupFilter. You can inject services from the DI container, but if you require access to Scoped services, you should inject an
IServiceProvider and create a new scope manually.
Side note - this seems like something a lot of people will get wrong, so I considered automatically creating a new scope for every task in the
RunWithTasksAsyncextension method. That would let you directly inject scoped services into the
IStartupTask. I decided against that to keep the behaviour consistent with
IStartupFilterand
IHostedService- I'd be interested in any thoughts people have in the comments.
The EF Core migration startup task would look something like the following:
public class MigratorStartupFilter: IStartupTask { //(); } } }
And we'd add the startup task to the DI container in>(); }
Finally, we need to update Program.cs>(); }
This takes advantage of the
async Task Main feature of C# 7.1. Overall this code is functionally equivalent to the "manual" equivalent from my last post and above, but it has a few advantages.
- It keeps the task implementation code out of Program.cs
- I think it's easier to understand what's happening in Program.cs - we're running startup tasks and then running the application. Most of that is due to simply moving implementation code out of Program.cs
- It allows you to easily add extra tasks by adding them to the DI container.
- If you don't have any tasks, the behaviour is the same as calling
RunAsync()
For me, the biggest advantage is that once you have added
RunWithTasksAsync(), you can easily add additional tasks by adding them to the DI container, without having to make any other changes.
Thomas Levesque recently wrote a similar post tackling the same problem, and came to a similar solution. He has a NuGet package available for the approach.
It's not entirely sunshine and roses though…
The small print - we haven't quite finished building the app yet
Other than the fact this isn't baked into the framework (so people have to customize their Program.cs classes), there's one tiny caveat I see to the approach shown above. Even though the tasks run after the
IConfiguration and DI container configuration has completed, they run before the
IStartupFilters have run and the middleware pipeline has been configured.
Personally, this hasn't been a problem for me, and I can't think of any cases where it would be. None of the tasks I've written have a dependency on the
IStartupFilters having run. That doesn't mean it won't happen though.
Unfortunately, there's not an easy way round this with the current
WebHost code (though that may change in 3.0 when ASP.NET Core runs as an
IHostedService). The problem is that the application is bootstrapped (by configuring the middleware pipeline and running
IStartupFilters) and started in the same function. When you call
WebHost.Run() in Program.Cs, this internally calls
WebHost.StartAsync which is shown below with logging and some other minor code removed for brevity:); }
The problem is that we want to insert code between the call to
BuildApplication() and the call to
Server.StartAsync(), but there's no mechanism for doing so.
I'm not sure if the solution I settled on feels hacky or elegant, but it works, and gives an even nicer experience for consumers, as they don't need to modify Program.cs…
An alternative approach by decorating IServer
The only way I could see to run async code between
BuildApplication() and
Server.StartAsync() is to replace the
IServer implementation (Kestrel) with our own! This isn't quite as horrendous as it sounds at first - we're not really going to replace the server, we're just going to decorate); }
The
TaskExecutingServer takes an instance of
IServer in its constructor - this the original
KestrelServer registered by ASP.NET Core. We delegate most of the
IServer implementation directly to Kestrel, we just intercept the call to
StartAsync and run the injected tasks first.
The difficult part of the implementation is getting the decoration working properly. As I discussed in a previous post, using decoration with the default ASP.NET Core container can be tricky. I typically use Scrutor to create decorators, but you could always do the decoration manually if you don't want to take a dependency on another library. Be sure to look at how Scrutor does it for guidance!
The extension method shown below for adding an
IStartupTask does two things - it registers an
IStartupTask with the DI container, and it decorates a previously-registered
IServer instance (I've left out the
Decorate() implementation for brevity) . If it finds that the
IServer is already decorated, it skips the second step. That way you can call
AddStartupTask<T>() safely any number of times:>(); } }
With these two pieces of code we no longer require users to make any changes to their Program.cs file plus we execute our tasks after the application has been fully built, including
IStartupFilters and the middleware pipeline.
The sequence diagram of the startup process now looks a bit like this:
That's pretty much all there is to it. It's such a small amount of code that I wasn't sure it was worth making into a library, but it's out on GitHub and NuGet nonetheless!
I decided to only write a package for the latter approach as it's so easier to consume, and Thomas Levesque already has a NuGet package available for the first approach.
In the implementation on GitHub I manually constructed the decoration (heavily borrowing from Scrutor), to avoid forcing a dependency on Scrutor. But the best approach is probably to just copy and paste the code into your own projects 🙂 and go from there!
Summary
In this post I showed two possible ways to run tasks asynchronously on app start up while blocking the actual startup process. The first approach requires modifying your Program.cs slightly, but is "safer" in that it doesn't require messing with internal implementation details like
IServer. The second approach, decorating
IServer, gives a better user experience, but feels more heavy-handed. I'd be interested in which approach people feel is the better one and why, so do let me know in the comments! | https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-part-2/ | CC-MAIN-2021-31 | refinedweb | 1,480 | 53.51 |
Insertion Sort
It is a comparison sorting algorithm that works on a sorted array or a list. It is not very efficient on large lists but has many advantages. Few of them are:
- Small data can be efficiently sorted
- It runs O(n+d) time where d is the number of inversions and works on an already sorted array or list.
- It is more efficient than algorithms with O(n²) complexity.
# Working of Insertion Sort
In insertion sort, to find the correct position we search till the last item just greater than the targeted item is found. Then we shift all the items from point one, down the list and then insert the targeted item at the vacant place.
# Program to show Insertion Sort
#include<iostream.h> using namespace std; void insertion_Sort(int array[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = array[i]; j = i - 1; while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } } void disp_arr(int array[], int n) { int i; for (i = 0; i < n; i++) cout << array[i] << " "; cout << endl; } int main() { int array[] = { 60, 20, 30, 10, 12 }; int n = sizeof(array) / sizeof(array[0]); insertion_Sort(array, n); disp_arr(array, n); return 0; }
Report Error/ Suggestion | https://www.studymite.com/data-structure/insertion-sort/?utm_source=home_recentpost&utm_medium=home_recent | CC-MAIN-2020-50 | refinedweb | 216 | 63.22 |
import java.io.*; class pattern { public static void main(String args[]) throws IOException { int n; BufferedReader br = new BufferedReader(InputStreamReader(System.in())); System.out.println("Please Enter Your Pattern Length:- "); n = Integer.parseInt(br.readLine()); while(n>2) { for(int i=0;i<=n;i++) { if((i==1)||(i==n)) { for(int k=0;k<=n;k++){ System.out.print("*"); System.out.println(); } } else { int o = n-2; System.out.print("*"); for(int h=0;h<=0;h++){ System.out.print(" "); } System.out.print("*"); System.out.println(); } } } } }
the problem is it is pointing at (System.in()) under the . saying it cannot find symbol. But I cannot understand what is wrong with it? Please help me.
It is System.in, not
System.in().
In your code there are two blunder mistakes.
1) you can not use InputStreamReader(System.in) directly as a parameter of BufferedReader class.
2) Although i have made corrections in your code but even then it is running for infinite
Here is the modified lines of code :
import java.io.*; class pattern { public static void main(String args[]) throws IOException { int n; InputStreamReader ir=new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir);
Or change line 8 to:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Although i have made corrections in your code but even then it is running for infinite
Yes, that happens when a value
> 2 is entered for
n, the while loop will keep looping as long as
n > 2, and since the value of
n never changes during loop execution, that will in theory be forever.
hai all and bhadra.anurag,
check at line no 27 also
for(int h=0;h<=0;h++){
is this correct assignment value for variable 'h'?
(assigning zero and comparing with zero)
please check it once (in case if you dont get answer)
happy coding
its correct, it just doesn't make any sense. it 'll cause the loop never to be executed, but if that's what the OP was going for ...
(although I suspect he may have intended the second 0 to actually be his o variable) | http://www.daniweb.com/software-development/java/threads/446554/cannot-find-symbol | CC-MAIN-2014-15 | refinedweb | 352 | 59.4 |
IBM Software has announced an update to the .NET support for their Informix database. This update includes add-ins for VS2005, plus some big performance improvements..
A new data provider for Informix™ Client SDK V3.0 and its runtime product IBM Informix Connect Runtime (RT) V3.0 allows .NET applications to access IDS by using the common base classes that are declared in the System.Data.Common namespace. The .NET Framework 2.0 support for IDS V7.31, V9.4, and V10.00 on the Windows™ platform enables development of a generic .NET database application without referencing any data provider-specific classes. It provides IBM Database Add-Ins for Microsoft™ Visual Studio 2005, which is a collection of add-ins to the Microsoft Visual Studio .NET IDE, simplifying the creation of IDS applications that use the ADO.NET 2.0 interface. Client SDK V3.0 also contains significant performance improvements to the .NET data provider.
The full announcement from IBM is here. | https://blogs.msdn.microsoft.com/dotnetinterop/2007/05/07/ibm-connects-net-to-informix-databases/ | CC-MAIN-2016-44 | refinedweb | 162 | 62.75 |
I'm trying to cross-compile Firefox from CVS, for a win32 target. Have poked around for help but this is a bit of a last resort. Might interest someone. configure reports: checking for i586-mingw32msvc-ranlib... (cached) ranlib checking for i586-mingw32msvc-ar... (cached) ar checking for i586-mingw32msvc-as... (cached) /usr/bin/as checking for i586-mingw32msvc-ld... (cached) ld checking for i586-mingw32msvc-strip... (cached) strip checking for i586-mingw32msvc-windres... i586-mingw32msvc-windres checking for w32api version >= 2.4... no configure: error: w32api version 2.4 or higher required. The program that fails is: #include "confdefs.h" #include <w32api.h> int main() { #if (__W32API_MAJOR_VERSION < 2) || (__W32API_MAJOR_VERSION == 2 && __W32API_MINOR_VERSION < 4) #error "test failed." #endif ; return 0; } I can see the w32api.h file is present at /usr/i586-mingw32msvc/include/w32api.h. How can I tell configure to look in here, and should it not be doing this already given that it was passed the option --target=i586-mingw32msvc? Antony | https://lists.debian.org/debian-user/2005/08/msg00070.html | CC-MAIN-2015-22 | refinedweb | 163 | 72.42 |
Using Resource Quota and Namespaces to Manage Multiple Teams on Your Kubernetes Cluster
Using Resource Quota and Namespaces to Manage Multiple Teams on Your Kubernetes Cluster
In the second article of this series, we review namespaces and how resources quotas, when applied to them, can make your namespaces more efficient.
Join the DZone community and get the full member experience.Join For Free
Site24x7 - Full stack It Infrastructure Monitoring from the cloud. Sign up for free trial.
In a previous blog post, we discussed how to use resource requests and limits in Kubernetes to constrain the resource usage per individual pod or container. In this follow-up blog post we look at the concept of resource quota to better control the amount of resources assigned to a particular namespace.
Why Use Namespaces Anyway?
When multiple teams work on a shared Kubernetes cluster (or OpenShift, or any other Kubernetes flavour), it is a good practice to create different namespaces for each team. Namespaces allow you to subdivide your cluster in virtual clusters for each team. This provides an isolated environment with a unique scope for naming resources, as well as to set policies. Resources created in one namespace are hidden from other namespaces. Within each namespace, the cluster administrator can also control the amount of resources that each team has access to, to ensure that the cluster capacity is shared in a fair way.
How Do Resource Quotas Work?
Resource quota are set via the ResourceQuota object that should be configured with the appropriate constraints per namespace. Constraints can be set on the amount of objects (pods, services, persistent volume claims, etc.) in a namespace, as well as on the total amount of compute resources (CPU and memory) that can be used per namespace. Users can then create resources (pods, services, etc.) in the namespace, and the quota system tracks usage to ensure it does not exceed the constraints defined in a ResourceQuota. If a new pod (or other object) exceeds the resource quota, it will not be created.
How to Create a Namespace
The first thing is to create a namespace to which you can assign a resource quota. This can be be done using the kubectl create namespace command
$ kubectl create namespace my-namespace
How to Set Resource Quota
As mentioned, a ResourceQuota object needs to be created for a particular namespace and the constraints should be set in its configuration, as in the example below.
apiVersion: v1 kind: ResourceQuota metadata: name: quota-example spec: hard: pods: "8" requests.cpu: "1" requests.memory: 1Gi limits.cpu: "2" limits.memory: 2Gi
This basically states that no more than 8 pods are allowed in the namespace and the total amount of requests and limits over all containers of a namespace must remain below the set constraints. It's important to note that this inherently also implies that every container must have requests and limits specified for CPU and memory. If you attempt to create a default pod with unbounded CPU and memory, it will be rejected if resource quota have been set in its namespace (unless the administrator has set default values for requests and limits via the LimitRange object).
You can now save this YAML to a file and create the resource quota object for your namespace.
$ kubectl create -f quota-example.yaml --namespace=my-namespace
How to Analyze Resource Quota Usage
Once the resource quota have been set, you want to analyze how the quota are being used. This can be done in the following way.
$ kubectl get quota --namespace=myspace NAME AGE quota-example 30s
$ kubectl describe quota quota-example --namespace=my-namespace Name: quota-example Namespace: my-namespace Resource Used Hard -------- ---- ---- limits.cpu 0 2 limits.memory 0 2Gi pods 0 8 requests.cpu 0 1 requests.memory 0 1Gi
In this example, no pods have been created yet. As long as the resource requirements of the new pods in the namespace stay below the resource quota, they will be created. Else, an error message will be returned.
Instead of manually tracking resource quota and their usage via commands, you ideally want to monitor this automatically and on an ongoing basis, to get alerts of when you are close to exhausting your resource quota or when new pods fail to be created. This is where a monitoring tool such as CoScale comes in handy.
Monitoring Resource Quota Usage with CoScale
CoScale was built specifically for container and Kubernetes monitoring. It integrates with Docker, Kubernetes and other container technologies to collect container-specific metrics and events. That means that in CoScale you can also check the resource quota of each namespace.
The dashboard below shows an overview of much of the resources and pods are assigned and used per namespace. You can also drill into an individual namespace to get a better understanding of which containers and services are using the most resources.
CoScale collects this information on a continuous basis and allows you to report on real-time as well as historic data. In addition, you can also set alerts, for example when CPU usage has reached a certain limit of the values specified in the resource quota. In the example below we specify that want to get an alert if the CPU usage within a namespace reaches 80% of the CPU limits value. CoScale even supports forecasted alerts so you can get notified ahead of time.
Besides getting early warnings like with the alert above, you might also want to get an immediate alert if a pod cannot be created because of exceeded resource quota. Thanks to its deep Kubernetes integration, CoScale automatically captures all Kubernetes events and messages. Then it's just a matter of alerting on the right message, as shown in the screenshot below.
Conclusion
In the previous blog post we discussed how to control resources for individual pods using limits and requests. In this blog post, we discussed how you can assign resource quota to namespaces to control fair resource usage of your Kubernetes cluster shared between different teams. Together, these two concepts allow you to efficiently manage how resources are being utilized on your cluster. Next to taking advantage of these concepts, it is equally important to monitor and alert on resource usage relative to these constraints. Whether you are a cluster administrator or user, this helps you to ensure that capacity is used as planned, and to be able to quickly intervene and make changes as needed. }} | https://dzone.com/articles/using-resource-quota-and-namespaces-to-manage-mult | CC-MAIN-2018-39 | refinedweb | 1,077 | 53.1 |
Created on 2020-07-14 22:02 by eryksun, last changed 2020-07-14 22:02 by eryksun.
A console script should be able to handle Windows console logoff and shutdown events with relatively simple ctypes code, such as the following:
import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT = 1
CTRL_CLOSE_EVENT = 2
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT = 6
@ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_ulong)
def console_ctrl_handler(event):
if event == CTRL_SHUTDOWN_EVENT:
return handle_shutdown()
if event == CTRL_LOGOFF_EVENT:
return handle_logoff()
if event == CTRL_CLOSE_EVENT:
return handle_close()
if event == CTRL_BREAK_EVENT:
return handle_break()
if event == CTRL_C_EVENT:
return handle_cancel()
return False # chain to next handler
if not kernel32.SetConsoleCtrlHandler(console_ctrl_handler, True):
raise ctypes.WinError(ctypes.get_last_error())
As of 3.9, it's not possible for python.exe to receive the above logoff and shutdown events via ctypes. In these two cases, the console doesn't even get to send a close event, so a console script cannot exit gracefully.
The session server (csrss.exe) doesn't send the logoff and shutdown console events to python.exe because it's seen as a GUI process, which is expected to handle WM_QUERYENDSESSION and WM_ENDSESSION instead. That requires creating a hidden window and running a message loop, which is not nearly as simple as a console control handler.
The system registers python.exe as a GUI process because user32.dll is loaded, which means the process is ready to interact with the desktop in every way, except for the final step of actually creating UI objects. In particular, loading user32.dll causes the system to extend the process and its threads with additional kernel data structures for use by win32k.sys (e.g. a message queue for each thread). It also opens handles for and connects to the session's "WinSta0" interactive window station (a container for an atom table, clipboard, and desktops) and "Default" desktop (a container for UI objects such as windows, menus, and hooks). (The process can connect to a different desktop or window station if set in the lpDesktop field of the process startup info. Also, if the process access token is for a service or batch logon, by default it connects to a non-interactive window station that's named for the logon ID. For example, the SYSTEM logon ID is 0x3e7, so a SYSTEM service or batch process gets connected to "Service-0x0-3e7$".)
Prior to 3.9, python3x.dll loads shlwapi.dll (the lightweight shell API) to access the Windows path functions PathCanonicalizeW and PathCombineW. shlwapi.dll in turn loads user32.dll. 3.9+ is one step closer to the non-GUI goal because it no longer depends on shlwapi.dll. Instead it always uses the newer PathCchCanonicalizeEx and PathCchCombineEx functions from api-ms-win-core-path-l1-1-0.dll, which is implemented by the base API (kernelbase.dll) instead of the shell API.
The next hurdle is extension modules, especially the _ctypes extension module, since it's needed for the console control handler. _ctypes.pyd loads ole32.dll, which in turn loads user32.dll. This is just to call ProgIDFromCLSID, which is rarely used. I see no reason that ole32.dll can't be delay loaded or just manually link to ProgIDFromCLSID on first use via GetModuleHandleW / LoadLibraryExW and GetProcAddress. I did a quick patch to implement the latter, and, since user32.dll no longer gets loaded, the console control handler is enabled for console logoff and shutdown events. So this is the minimal fix to resolve this issue in 3.9+.
---
Additional modules
winsound loads user32.dll for MessageBeep. The Beep and PlaySound functions don't require user32.dll, so winsound is still useful if it gets delay loaded.
_ssl and _hashlib depend on libcrypto, which loads user32.dll for MessageBoxW, GetProcessWindowStation and GetUserObjectInformationW. The latter two are called in OPENSSL_isservice [1] in order to get the window station name. If StandardError isn't a valid file handle, OPENSSL_isservice determines whether an error should be reported as an event or interactively shown with a message box. user32.dll can be delay loaded for this, which, if I'm reading the source right, will never occur as long as StandardError is a valid file.
[1]: | https://bugs.python.org/issue41298 | CC-MAIN-2021-17 | refinedweb | 695 | 58.48 |
You can subscribe to this list here.
Showing
2
results of 2
Bugs item #2841177, was opened at 2009-08-20 21:45
Message generated for change (Tracker Item Submitted) made by the_zett: the_zett (the_zett)
Assigned to: Nobody/Anonymous (nobody)
Summary: ioctl: Strange behaviour leads to infinite loop
Initial Comment:
Hi,
I have caught a strange behaviour of libevent-1.4.12-stable on my linux vds.
# > uname -a
# Linux localhost 2.6.18-028stab062.3-ent #1 SMP Thu Mar 26 15:12:05 MSK 2009 i686 i686 i386 GNU/Linux
I have used 'evbuffer_read()' with a regular file descriptor. The file had size 4347 bytes and there were two calls of 'evbuffer_read()'. The first call returned 4096 bytes, but second one never completed.
I did some traces and found that 'ioctl(fd, FIONREAD, &n)' sets 'n' to a negative value! I didn't find any description of such behaviour but it is real.
<++> gdb.log.1
evbuffer_read (buf=0x94dce00, fd=9, howmuch=251) at buffer.c:354
354 size_t oldoff = buf->off;
...
355 int n = EVBUFFER_MAX_READ; /* 4096 */
...
362 if (ioctl(fd, FIONREAD, &n) == -1 || n == 0) {
...
(gdb) p n
$4 = -4096
<-->
<++> strace.log
ioctl(6, FIONREAD, [-4096]) = 0
<-->
So then it would enter an infinite loop at
<++> gdb.log.2
264 int
265 evbuffer_expand(struct evbuffer *buf, size_t datlen)
266 {
...
285 while (length < need)
286 length <<= 1;
<-->
('length' is going to be 0 through overflow)
I think it is needed to find the source of such 'ioctl()' behavior. But I don't know where to start at. And at least 'evbuffer_expand()' should be protected against integer overflow.
---
Thanks,
Alexander Pronchenkov
----------------------------------------------------------------------
You can respond by visiting:
Bugs item #2839240, was opened at 2009-08-17 14:05
Message generated for change (Tracker Item Submitted) made by aglangley: Adam Langley (aglangley)
Assigned to: Nobody/Anonymous (nobody)
Summary: epoll backend allocates too much memory
Initial Comment:
In epoll.c we find the following code:
#define NEVENT 32000
...
int epfd, nfiles = NEVENT;
...
if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
rl.rlim_cur != RLIM_INFINITY) {
nfiles = rl.rlim_cur - 1;
}
...
epfd = epoll_create(nfiles)
...
epollop->events = malloc(nfiles * sizeof(struct epoll_event));
...
pollop->fds = calloc(nfiles, sizeof(struct evepoll));
For systems which don't have a resource limit set on the number of file descriptors, that will allocate about 32000*(16 + 16) = 1MB of memory every time.
The code already exists in epoll.c to resize the arrays as needed, so the initial size should be something like 32 on the assumption that most users aren't going to use every descriptor available. Chromium has been running such a patch for many months now:
@@ -94,7 +94,7 @@ const struct eventop epollops = {
#define FD_CLOSEONEXEC(x)
#endif
-#define NEVENT 32000
+#define NEVENT 32
/* On Linux kernels at least up to 2.6.24.4, epoll can't handle timeout
* values bigger than (LONG_MAX - 999ULL)/HZ. HZ in the wild can be
@@ -115,16 +115,6 @@ epoll_init(struct event_base *base)
if (getenv("EVENT_NOEPOLL"))
return (NULL);
- if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
- rl.rlim_cur != RLIM_INFINITY) {
- /*
- * Solaris is somewhat retarded - it's important to drop
- * backwards compatibility when making changes. So, don't
- * dare to put rl.rlim_cur here.
- */
- nfiles = rl.rlim_cur - 1;
- }
-
/* Initalize the kernel queue */
if ((epfd = epoll_create(nfiles)) == -1) {
----------------------------------------------------------------------
You can respond by visiting: | http://sourceforge.net/p/levent/mailman/levent-tracker/?viewmonth=200908 | CC-MAIN-2014-52 | refinedweb | 542 | 65.83 |
Run CrateDB on Softlayer¶
Table of contents
Introduction¶
SoftLayer, IBM’s cloud platform, has a slightly different take on “the cloud”. They are focusing on high performance (physical) hardware embedded in the best possible infrastructure, because “computing doesn’t come out of the sky”. However, besides their strong physical hardware that you can choose from, SoftLayer also offers virtual machines with a wide range of configuration possibilities.
This combination makes SoftLayer an ideal hosting provider for your own CrateDB cluster, no matter if you just need a small cluster to play around or run your production cluster even across data centres.
We at Crate.IO have been using bare metal servers to perform benchmarks on CrateDB. When using bare metal you have the advantage that you can mix and match hardware. On the other hand the setup/provisioning is more conventional (like on-premise-hosting), since it is not possible to launch/terminate instances in real-time.
A balanced instance configuration for a production CrateDB host could look similar like that:
8 × 2.0GHz cores = 32 GB memory = 100 GB local SSD storage 1000 Mbps public/private network interface
We used SaltStack’s Salt Cloud to launch and provision instances for the test cluster. Salt Cloud provides an abstraction layer for multiple cloud hosting providers, also for SoftLayer.
Server provisioning with Salt Cloud¶
Example of
/etc/salt/cloud.profiles:
softlayer: provider: crate-softlayer-hw domain: crate.io image: CENTOS_LATEST # location: ams01 # Amsterdam cpu_number: 8 ram: 65536 # 64GB disk_size: 100 # GB local_disk: True max_net_speed: 1000 # 1Gbps hourly_billing: False private_vlan: minion: grains: role: - crate_softlayer
Example of
/etc/salt/cloud.map:
softlayer: - sl1 - sl2 - sl3
Launching the instances defined in the cloud.map file is as easy as this command:
$ salt-cloud -m /etc/salt/cloud.map -P
And once the instances are running you will be able to provision them by
running the
highstate on the crate_softlayer role that the instances are
associated with.
$ salt -G 'role:crate_softlayer' state.highstate
The
highstate is defined in the sls (Salt State File). Here’s an
example of our init.sls:
crate_repo: pkgrepo.managed: - name: crate - humanname: Crate - baseurl: - gpgcheck: 1 - gpgkey: - required_in: - packages packages: pkg.installed: - pkgs: - java-11-openjdk-headless - wget - crate /etc/sysconfig/crate: file.managed: - user: crate - mode: 755 - contents: | CRATE_MIN_MEM=16g CRATE_MAX_MEM=16g /etc/crate/crate.yml: file.managed: - source: salt://softlayer/crate.yml - user: root - mode: 644
Example of
crate.yml:
name: {{ grains['host'] }} cluster: name: crate-softlayer path: logs: /path/to/crate/logs data: /path/to/crate/data network: tcp: connect_timeout: 60s discovery.zen.minimum_master_nodes: 2 discovery.zen.ping.unicast.hosts: {%- for server, addrs in salt['mine.get']('*', 'network.ip_addrs').items() %} {% if server.startswith("sl") %} - {{ addrs[0] }}:4300{% endif -%}{% endfor %} | https://crate.io/docs/crate/howtos/en/latest/deployment/cloud/softlayer.html | CC-MAIN-2020-34 | refinedweb | 452 | 50.43 |
Documentation Release 1
1 OpenCV-Python Tutorials 3 1.1 Introduction to OpenCV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.2 Gui Features in OpenCV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.3 Core Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 1.4 Image Processing in OpenCV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 1.5 Feature Detection and Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 1.6 Video Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 1.7 Camera Calibration and 3D Reconstruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 1.8 Machine Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 1.9 Computational Photography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 1.10 Object Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 1.11 OpenCV-Python Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
iii OpenCV-Python Tutorials Documentation, Release 1
Contents:
Contents 1OpenCV-Python Tutorials Documentation, Release 1
2 Contents CHAPTER 1
OpenCV-Python Tutorials
Introduction to OpenCV
Here you will learn how to display and save images and videos, control mouse events and create trackbar.
Core Operations
In this section you will learn basic operations on image like pixel editing, geometric transformations, code optimization, some mathematical tools etc.
In this section you will learn different image processing functions inside OpenCV.
3OpenCV-Python Tutorials Documentation, Release 1
In this section you will learn about feature detectors and descriptors
Video Analysis
In this section you will learn different techniques to work with videos like object tracking etc.
In this section we will learn about camera calibration, stereo imaging etc.
Machine Learning
In this section you will learn different image processing functions inside OpenCV.
Computational Photography
Object Detection
In this section you will object detection techniques like face detection etc.
OpenCV-Python Bindings
5OpenCV-Python Tutorials Documentation, Release 1
OpenCV
OpenCV was started at Intel in 1999 by Gary Bradsky and the first release came out in 2000. Vadim Pisarevskyjoined Gary Bradsky to manage Intels Russian software OpenCV team. In 2005, OpenCV was used on Stanley, thevehicle who won 2005 DARPA Grand Challenge. Later its active development continued under the support of WillowGarage, with Gary Bradsky and Vadim Pisarevsky leading the project. Right now, OpenCV supports a lot of algorithmsrelated to Computer Vision and Machine Learning and it is expanding day-by-day.Currently OpenCV supports a wide variety of programming languages like C++, Python, Java etc and is available ondifferent platforms including Windows, Linux, OS X, Android, iOS etc. Also, interfaces based on CUDA and OpenCLare also under active development for high-speed GPU operations.OpenCV-Python is the Python API of OpenCV. It combines the best qualities of OpenCV C++ API and Pythonlanguage.
OpenCV-Python
Python is a general purpose programming language started by Guido van Rossum, which became very popular inshort time mainly because of its simplicity and code readability. It enables the programmer to express his ideas infewer lines of code without reducing any readability.Compared to other languages like C/C++, Python is slower. But another important feature of Python is that it canbe easily extended with C/C++. This feature helps us to write computationally intensive codes in C/C++ and createa Python wrapper for it so that we can use these wrappers as Python modules. This gives us two advantages: first,our code is as fast as original C/C++ code (since it is the actual C++ code working in background) and second, it. Sowhatever operations you can do in Numpy, you can combine it with OpenCV, which increases number of weapons inyour arsenal. Besides that, several other libraries like SciPy, Matplotlib which supports Numpy can be used with thisalso).A prior knowledge on Python and Numpy is required before starting because they wont be covered in this guide.Especially, a good knowledge on Numpy is must to write optimized codes in OpenCV-Python.This tutorial has been started by Abid Rahman K. as part of Google Summer of Code 2013 program, under the guidanceof Alexander Mordvintsev.
Since OpenCV is an open source initiative, all are welcome to make contributions to this library. And it is same forthisCVin github, make necessary corrections and send a pull request to OpenCV. OpenCV developers will check your pullrequest,particular algorithm can write up a tutorial which includes a basic theory of the algorithm and a code showing basicusage of the algorithm and submit it to OpenCV.Remember, we together can make this project a great success !!!
Contributors
Additional Resources
Goals
In this tutorial We will learn to setup OpenCV-Python in your Windows system.Below steps are tested in a Windows 7-64 bit machine with Visual Studio 2010 and Visual Studio 2012. The screenshotsshows. 7. Goto opencv/build/python/2.7 folder.
If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.
Note: In this case, we are using 32-bit binaries of Python packages. But if you want to use OpenCV for x64, 64-bitbinaries of Python packages are to be installed. Problem is that, there is no official 64-bit binaries of Numpy. Youhave to build it on your own. For that, you have to use the same compiler used to build Python. When you start PythonIDLE, it shows the compiler details. You can get more information here. So your system must have the same VisualStudio version and build Numpy from source.
Note: Another method to have 64-bit Python packages is to use ready-made Python distributions from third-partieslike Anaconda, Enthought etc. It will be bigger in size, but will have everything you need. Everything in a single shell.You can also download 32-bit versions also.
7.4. It will open a new window to select the compiler. Choose appropriate compiler (here, Visual Studio 11) and click Finish._FOLDERS is unchecked (So- lution folders are not supported by Visual Studio Express edition). See the image below:
12. Also make sure that in the PYTHON field, everything is filled. (Ignore PYTHON_DEBUG_LIBRARY). See image below:
18. Open Python IDLE and enter import cv2. If no error, it is installed correctly.
Note: We have installed with no other support like TBB, Eigen, Qt, Documentation etc. It would be difficult toexplain it here. A more detailed video will be added soon or you can just hack around.
Exercises
1. If you have a windows machine, compile the OpenCV from source. Do all kinds of hacks. If you meet any problem, visit OpenCV forum and explain your problem.
In this tutorial We will learn to setup OpenCV-Python in your Fedora system. Below steps are tested for Fedora 18 (64-bit) and Fedora 19 (32-bit).
Introduction
OpenCV-Python can be installed in Fedora in two ways, 1) Install from pre-built binaries available in fedora reposito-ries, 2) Compile from the source. In this section, we will see both.Another important thing is the additional libraries required. OpenCV-Python requires only Numpy (in addition toother dependencies, which we will see later). But in this tutorials, we also use Matplotlib for some easy and niceplotting purposes (which I feel much better compared to OpenCV). Matplotlib is optional, but highly recommended.Similarly we will also see IPython, an Interactive Python Terminal, which is also highly recommended.CValways. For example, at the time of writing this tutorial, yum repository contains 2.4.5 while latest OpenCV version is2.4.6. With respect to Python API, latest version will always contain much better support. Also, there may be chanceof problems with camera support, video playback etc depending upon the drivers, ffmpeg, gstreamer packages presentetc.So my personnel preference is next method, i.e. compiling from source. Also at some point of time, if you want tocontribute to OpenCV, you will need this.
Compiling from source may seem a little complicated at first, but once you succeeded in it, there is nothing compli-cated.First we will install some dependencies. Some are compulsory, some are optional. Optional dependencies, you canleave if you dont want.
Compulsory Dependencies
We need CMake to configure the installation, GCC for compilation, Python-devel and Numpy for creating Pythonextensions etc. yum install cmake yum install python-devel numpy yum install gcc gcc-c++
Next we need GTK support for
Above dependencies are sufficient to install OpenCV in your fedora machine. But depending upon your requirements,you may need some extra dependencies. A list of such optional dependencies are given below. You can either leave itor install it, your call :)OpenCV comes with supporting files for image formats like PNG, JPEG, JPEG2000, TIFF, WebP etc. But it may bea Intels Threading Building Blocks (TBB). But if you want to en-able it, you need to install TBB first. ( Also while configuring installation with CMake, dont forget to pass -DWITH_TBB=ON. More details below.) yum install tbb-devel
OpenCV uses another library Eigen for optimized mathematical operations. So if you have Eigen installed in your sys-tem, you can exploit it. ( Also while configuring installation with CMake, dont forget to pass -D WITH_EIGEN=ON.More details below.) yum install eigen3-devel
If you want to build documentation ( Yes, you can create offline version of OpenCVs complete official documentationin your system in HTML with full search facility so that you need not access internet always if any question, and itis quite FAST!!! ), you need to install Sphinx (a documentation generation tool) and pdflatex (if you want to create
a PDF version of it). ( Also while configuring installation with CMake, dont forget to pass -D BUILD_DOCS=ON.More details below.) yum install python-sphinx yum install texlive
Downloading OpenCV
Next we have to download OpenCV. You can download the latest release of OpenCV from sourceforge site. Thenextract the folder.Or you can download latest source from OpenCVs github repo. (If you want to contribute to OpenCV, choose this. Italways keeps your OpenCV up-to-date). For that, you need to install Git first. yum install git git clone
It will create a folder OpenCV in home directory (or the directory you specify). The cloning may take some timedepending upon your internet connection.Now open a terminal window and navigate to the downloaded OpenCV folder. Create a new build folder andnavigate to it. mkdir build cd build
Now we have installed all the required dependencies, lets install OpenCV. Installation has to be configured withCMake. It specifies which modules are to be installed, installation path, which additional libraries to be used, whetherdocumentation and examples to be compiled etc. Below command is normally used for configuration (executed frombuild folder). cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
It specifies that build type is Release Mode and installation path is /usr/local. Observe the -D before eachoptionexclude Performance tests and building samples. We also disable GPU related modules (since we use OpenCV-Python,we dont ..
Each time you enter cmake statement, it prints out the resulting configuration setup. In the final setup you got, makesure that following fields are filled (below is the some important parts of configuration I got). These fields shouldbe filled appropriately in your system also. Otherwise some problem has happened. So check if you have correctlyperformed)
-- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- Libraries: /lib/libpython2.7.so (ver 2.7.5) -- numpy: /usr/lib/python2.7/site-packages/numpy/core/include (ver 1.7 --should be executed as root. make su
make install
Installation is over. All files are installed in /usr/local/ folder. But to use it, your Python should be able to findOpenCV module. You have two options for that.. 2.
Learn to play videos, capture videos from Camera and write it as a video
Mouse as a Paint-Brush
Read an image
Use the function cv2.imread() to read an image. The image should be in the working directory or a full path of imageshould be given
Note: Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.
Warning: Even if the image path is wrong, it wont throw any error, but print img will give you None
Display an image
Use the function cv2.imshow() to display an image in a window. The window automatically fits to the image size.First argument is a window name which is a string. second argument is our image. You can create as many windowsas you wish, but with different window names.cv2.imshow('image',img)cv2.waitKey(0)cv2.destroyAllWindows()
A screenshot of the window will look like this (in Fedora-Gnome machine):
cv2.waitKey() is a keyboard binding function. Its argument is the time in milliseconds. The function waits forspecified milliseconds for any keyboard event. If you press any key in that time, the program continues. If 0 is passed,it waits indefinitely for a key stroke. It can also be set to detect specific key strokes like, if key a is pressed etc whichwe will discuss below.cv2.destroyAllWindows() simply destroys all the windows we created. If you want to destroy any specific window,use the function cv2.destroyWindow() where you pass the exact window name as the argument.
Note: There is a special case where you can already create a window and load image to it later. In that case, you canspecify whether window is resizable or not. It is done with the function cv2.namedWindow(). By default, the flag iscv2.WINDOW_AUTOSIZE. But if you specify flag to be cv2.WINDOW_NORMAL, you can resize window. It will behelpful when image is too large in dimension and adding track bar to windows.
Write an image
This will save the image in PNG format in the working directory.
Sum it up
Below program loads an image in grayscale, displays it, save the image if you press s and exit, or simply exit withoutsaving if you press ESC key.import numpy as npimport cv2
img = cv2.imread('messi5.jpg',0)cv2.imshow('image',img)k = cv2.waitKey(0)if k == 27: # wait for ESC key to exit cv2.destroyAllWindows()elif k == ord('s'): # wait for 's' key to save and exit cv2.imwrite('messigray.png',img) cv2.destroyAllWindows()
Warning: If you are using a 64-bit machine, you will have to modify k = cv2.waitKey(0) line as follows : k = cv2.waitKey(0) & 0xFF
Using Matplotlib
Matplotlib is a plotting library for Python which gives you wide variety of plotting methods. You will see them incoming articles. Here, you will learn how to display image with Matplotlib. You can zoom images, save it etc usingMatplotlib.import numpy as npimport cv2fromplt.show()
See also:Plenty of plotting options are available in Matplotlib. Please refer to Matplotlib docs for more details. Some, we willsee on the way.
Warning: Color image loaded by OpenCV is in BGR mode. But Matplotlib displays in RGB mode. So color images will not be displayed correctly in Matplotlib if image is read with OpenCV. Please see the exercises for more details.
1. There is some problem when you try to load color image in OpenCV and display it in Matplotlib. Read this discussion and understand it.
Goal
Often, we have to capture live stream with camera. OpenCV provides a very simple interface to this. Lets capture avideo from the camera (I am using the in-built webcam of my laptop), convert it into grayscale video and display it.Just a simple task to get started.To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the nameof a video file. Device index is just the number to specify which camera. Normally one camera will be connected (asin my case). So I simply pass 0 (or -1). You can select the second camera by passing 1 and so on. After that, you cancapture frame-by-frame. But at the end, dont forget to release the capture.import numpy as npimport cv2
cap = cv2.VideoCapture(0)
while(True): # Capture frame-by-frame ret, frame = cap.read()
cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of thevideo by checking this return value.Sometimes, cap may not have initialized the capture. In that case, this code shows error. You can check whether it isinitialized or not by the method cap.isOpened(). If it is True, OK. Otherwise open it using cap.open().You can also access some of the features of this video using cap.get(propId) method where propId is a number from0 to 18. Each number denotes a property of the video (if it is applicable to that video) and full details can be seen here:Property Identifier. Some of these values can be modified using cap.set(propId, value). Value is the new value youwant.For example, I can check the frame width and height by cap.get(3) and cap.get(4). It gives me 640x480 bydefault. But I want to modify it to 320x240. Just use ret = cap.set(3,320) and ret = cap.set(4,240).
Note: If you are getting error, make sure camera is working fine using any other camera application (like Cheese inLinux).
It is same as capturing from Camera, just change camera index with video file name. Also while displaying the frame,use appropriate time for cv2.waitKey(). If it is too less, video will be very fast and if it is too high, video will beslow (Well, that is how you can display videos in slow motion). 25 milliseconds will be OK in normal cases.import numpy as npimport cv2
cap = cv2.VideoCapture('vtest.avi')
while(cap.isOpened()): ret, frame = cap.read()
cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break
cap.release()cv2.destroyAllWindows()
Note: Make sure proper versions of ffmpeg or gstreamer is installed. Sometimes, it is a headache to work with VideoCapture mostly due to wrong installation of ffmpeg/gstreamer.
Saving a Video
So we capture a video, process it frame-by-frame and we want to save that video. For images, it is very simple, justuse cv2.imwrite(). Here a little more work is required.This time we create a VideoWriter object. We should specify the output file name (eg: output.avi). Then we shouldspecify the FourCC code (details in next paragraph). Then number of frames per second (fps) and frame size shouldbe passed. And last one is isColor flag. If it is True, encoder expect color frame, otherwise it works with grayscaleframe.FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org. It isplatform dependent. Following codecs works fine for me. In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video) In Windows: DIVX (More to be tested and added) In OSX : (I dont have access to OSX. Can some one fill this?)FourCC code is passed as cv2.VideoWriter_fourcc(M,J,P,G) orcv2.VideoWriter_fourcc(*MJPG) for MJPG.Below code capture from a Camera, flip every frame in vertical direction and saves it.
import numpy as npimport cv2
while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0)
cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break
Code
In all the above functions, you will see some common arguments as given below: img : The image where you want to draw the shapes color : Color of the shape. for BGR, pass it as a tuple, eg: (255,0,0) for blue. For grayscale, just pass the scalar value. thickness : Thickness of the line or circle etc. If -1 is passed for closed figures like circles, it will fill the shape. default thickness = 1 lineType : Type of line, whether 8-connected, anti-aliased line etc. By default, it is 8-connected. cv2.LINE_AA gives anti-aliased line which looks great for curves.
Drawing Line
To draw a line, you need to pass starting and ending coordinates of line. We will create a black image and draw a blueline on it from top-left to bottom-right corners.import numpy as npimport cv2
Drawing Rectangle
To draw a rectangle, you need top-left corner and bottom-right corner of rectangle. This time we will draw a greenrectangle at the top-right corner of image.img = cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
Drawing Circle
To draw a circle, you need its center coordinates and radius. We will draw a circle inside the rectangle drawn above.img = cv2.circle(img,(447,63), 63, (0,0,255), -1)
Drawing Ellipse
To draw the ellipse, we need to pass several arguments. One argument is the center location (x,y). Next argument isaxes lengths (major axis length, minor axis length). angle is the angle of rotation of ellipse in anti-clockwise direc-tion. startAngle and endAngle denotes the starting and ending of ellipse arc measured in clockwise directionfrom major axis. i.e. giving values 0 and 360 gives the full ellipse. For more details, check the documentation ofcv2.ellipse(). Below example draws a half ellipse at the center of the image.img = cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
Drawing Polygon
To draw a polygon, first you need coordinates of vertices. Make those points into an array of shape ROWSx1x2 whereROWS are number of vertices and it should be of type int32. Here we draw a small polygon of with four vertices inyellow color.pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)pts = pts.reshape((-1,1,2))img = cv2.polylines(img,[pts],True,(0,255,255))
Note: If third argument is False, you will get a polylines joining all the points, not a closed shape.
Note: cv2.polylines() can be used to draw multiple lines. Just create a list of all the lines you want to drawand pass it to the function. All lines will be drawn individually. It is more better and faster way to draw a group oflines than calling cv2.line() for each line.
Result
So it is time to see the final result of our drawing. As you studied in previous articles, display the image to see it.
1. The angles used in ellipse function is not our circular angles. For more details, visit this discussion.
1. Try to create the logo of OpenCV using drawing functions available in OpenCV
Simple Demo
Here, we create a simple application which draws a circle on an image wherever we double-click on it.First we create a mouse callback function which is executed when a mouse event take place. Mouse event can beanything related to mouse like left-button down, left-button up, left-button double-click etc. It gives us the coordinates(x,y) for every mouse event. With this event and location, we can do whatever we like. To list all available eventsavailable, run the following code in Python terminal:>>> import cv2>>> events = [i for i in dir(cv2) if 'EVENT' in i]>>> print events
Creating mouse callback function has a specific format which is same everywhere. It differs only in what the functiondoes. So our mouse callback function does one thing, it draws a circle where we double-click. So see the code below.Code is self-explanatory from comments :import cv2import numpy as np
while(1): cv2.imshow('image',img) if cv2.waitKey(20) & 0xFF == 27: breakcv2.destroyAllWindows()
Now we go for much more better application. In this, we draw either rectangles or circles (depending on the mode weselect) by dragging the mouse like we do in Paint application. So our mouse callback function has two parts, one todraw rectangle and other to draw the circles. This specific example will be really helpful in creating and understandingsome interactive applications like object tracking, image segmentation etc.import cv2import numpy as np
if event == cv2.EVENT_LBUTTONDOWN: drawing = True ix,iy = x,y
Next we have to bind this mouse callback function to OpenCV window. In the main loop, we should set a keyboardbinding for key m to toggle between rectangle and circle.img = np.zeros((512,512,3), np.uint8)cv2.namedWindow('image')cv2.setMouseCallback('image',draw_circle)
while(1): cv2.imshow('image',img) k = cv2.waitKey(1) & 0xFF if k == ord('m'): mode = not mode elif k == 27: break
cv2.destroyAllWindows()
1. In our last example, we drew filled rectangle. You modify the code to draw an unfilled rectangle.
Code Demo
Here we will create a simple application which shows the color you specify. You have a window which shows thecolor and three trackbars to specify each of B,G,R colors. You slide the trackbar and correspondingly window colorchanges. By default, initial color will be set to Black.For cv2.getTrackbarPos() function, first argument is the trackbar name, second one is the window name to which it isattached, third argument is the default value, fourth one is the maximum value and fifth one is the callback function
which is executed everytime trackbar value changes. The callback function always has a default argument which isthe trackbar position. In our case, function does nothing, so we simply pass.Another important application of trackbar is to use it as a button or switch. OpenCV, by default, doesnt have buttonfunctionality. So you can use trackbar to get such functionality. In our application, we have created one switch inwhich application works only if switch is ON, otherwise screen is always black.import cv2import numpy as np
def nothing(x): pass
while(1): cv2.imshow('image',img) k = cv2.waitKey(1) & 0xFF if k == 27: break
if s == 0: img[:] = 0 else: img[:] = [b,g,r]
1. Create a Paint application with adjustable colors and brush radius using trackbars. For drawing, refer previous tutorial on mouse handling.
Learn to read and edit pixel values, working with image ROI and other basic operations.
Learn some of the mathematical tools provided by OpenCV like PCA, SVD etc.
Learn to: Access pixel values and modify them Access image properties Setting Region of Image (ROI) Splitting and Merging images )
You can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green,Red values. For grayscale image, just corresponding intensity is returned.>>> px = img[100,100]>>> print px[157 166 200] likethat. For individual pixel access, Numpy array methods, array.item() and array.itemset() is considered tobe better. But it always returns a scalar. So if you want to access all B,G,R values, you need to call array.item()separately for all.
Image properties include number of rows, columns and channels, type of image data, number of pixels etc.Shape of image is accessed by img.shape. It returns a tuple of number of rows, columns and channels (if image iscolor):>>> print img.shape(342, 548, 3)
Note: If image is grayscale, tuple returned contains only number of rows and columns. So it is a good method tocheck if loaded image is grayscale or color image.
Note: img.dtype is very important while debugging because a large number of errors in OpenCV-Python code iscaused by invalid datatype.
Image ROI
Sometimes, you will have to play with certain region of images. For eye detection in images, first perform facedetection over the image until the face is found, then search within the face region for eyes. This approach improvesaccuracy (because eyes are always on faces :D ) and performance (because we search for a small area).ROI is again obtained using Numpy indexing. Here I am selecting the ball and copying it to another region in theimage:>>> ball = img[280:340, 330:390]>>> img[273:333, 100:160] = ball
The B,G,R channels of an image can be split into their individual planes when needed. Then, the individual channelscansimply use Numpy indexing which is faster.>>> img[:,:,2] = 0
Warning: cv2.split() is a costly operation (in terms of time), so only use it if necessary. Numpy indexing is much more efficient and should be used if possible.
If you want to create a border around the image, something like a photo frame, you can use cv2.copyMakeBorder()function. But it has more applications for convolution operation, zero padding etc. This function takes followingarguments:- c - Cant explain, it will look like this : cdefgh|abcdefgh|abcdefg value - Color of border if border type is cv2.BORDER_CONSTANTBelow is a sample code demonstrating all these border types for better understanding:import cv2import numpy as npfrom):
Learn several arithmetic operations on images like addition, subtraction, bitwise operations etc. You will learn these functions : cv2.add(), cv2.addWeighted() etc.
Image Addition
You can add two images by OpenCV function, cv2.add() or simply by numpy operation, res = img1 + img2.Both images should be of same depth and type, or second image can just be a scalar value.
Note: There is a difference between OpenCV addition and Numpy addition. OpenCV addition is a saturated operationwhile Numpy addition is a modulo operation.
It will be more visible when you add two images. OpenCV function will provide a better result. So always better stickto OpenCV functions.
Image Blending
This is also image addition, but different weights are given to images so that it gives a feeling of blending or trans-parency. Images are added as per the equation below:
() = (1 )0 () + 1 ()
By varying from 0 1, you can perform a cool transition between one image to another.Here I took two images to blend them together. First image is given a weight of 0.7 and second image is given 0.3.cv2.addWeighted() applies following equation on the image.
= 1 + 2 +
dst = cv2.addWeighted(img1,0.7,img2,0.3,0)
cv2.imshow('dst',dst)cv2.waitKey(0)cv2.destroyAllWindows()
Bitwise Operations
This includes bitwise AND, OR, NOT and XOR operations. They will be highly useful while extracting any part ofthe image (as we will see in coming chapters), defining and working with non-rectangular ROI etc. Below we will seean example on how to change a particular region of an image.I want to put OpenCV logo above an image. If I add two images, it will change color. If I blend it, I get an transparenteffect. But I want it to be opaque. If it was a rectangular region, I could use ROI as we did in last chapter. But OpenCVlogo is a not a rectangular shape. So you can do it with bitwise operations as below:# Load two imagesimg1 = cv2.imread('messi5.jpg')img2 = cv2.imread('opencv_logo.png')
# Now create a mask of logo and create its inverse mask alsoimg2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)mask_inv = cv2.bitwise_not(mask)
cv2.imshow('res',img1)cv2.waitKey(0)cv2.destroyAllWindows()
See the result below. Left image shows the mask we created. Right image shows the final result. For more understand-ing, display all the intermediate images in the above code, especially img1_bg and img2_fg.
1. Create a slide show of images in a folder with smooth transition between images using cv2.addWeighted function
In image processing, since you are dealing with large number of operations per second, it is mandatory that your codemodule profile helps to get detailed report on the code, like how much time each function in the code took, how manytimes the function was called etc. But, if you are using IPython, all these features are integrated in an user-friendlymanner. We will see some important ones, and for more details, check links in Additional Resouces section.
cv2.getTickCount function returns the number of clock-cycles after a reference event (like the moment machine wasswitched ON) to the moment this function is called. So if you call it before and after the function execution, you getnumber of clock-cycles used to execute a function.cv2.getTickFrequency function returns the frequency of clock-cycles, or the number of clock-cycles per second. Soto find the time of execution in seconds, you can do following:e1 = cv2.getTickCount()# your code executione2 = cv2.getTickCount()time = (e2 - e1)/ cv2.getTickFrequency()
We will demonstrate with following example. Following example apply median filtering with a kernel of odd sizeranging from 5 to 49. (Dont
Note: You can do the same with time module. Instead of cv2.getTickCount, use time.time() function.Then take the difference of two times.
Many of the OpenCV functions are optimized using SSE2, AVX etc. It contains unoptimized code also. So if oursystem support these features, we should exploit them (almost all modern day processors support them). It is enabledby.Lets see a simple example.# check if optimization is enabledIn [5]: cv2.useOptimized()Out[5]: True
# Disable itIn [7]: cv2.setUseOptimized(False)
In [8]: cv2.useOptimized()Out[8]: False
See, optimized median filtering is ~2x faster than unoptimized version. If you check its source, you can see medianfiltering is SIMD optimized. So you can use this to enable optimization at the top of your code (remember it is enabledby default).
Sometimes you may need to compare the performance of two similar operations. IPython gives you a magic command%timeit to perform this. It runs the code several times to get more accurate results. Once again, they are suitable tomeasure single line codes.For example, do you know which of the following addition operation is more better, x = 5; y = x**2, x =5; y = x*x, x = np.uint8([5]); y = x*x or y = np.square(x) ? We will find it with %timeit inIPython shell.In [10]: x = 5
In [15]: z = np.uint8([5])
You can see that, x = 5 ; y = x*x is fastest and it is around 20x faster compared to Numpy. If you consider thearray creation also, it may reach upto 100x faster. Cool, right? (Numpy devs are working on this issue)
Note: Python scalar operations are faster than Numpy scalar operations. So for operations including one or twoelements, Python scalar is better than Numpy arrays. Numpy takes advantage when size of array is a little bit bigger.
We will try one more example. This time, we will compare the performance of cv2.countNonZero() andnp.count_nonzero() for same image.In [35]: %timeit z = cv2.countNonZero(img)100000 loops, best of 3: 15.8 us per loop
Note: Normally, OpenCV functions are faster than Numpy functions. So for same operation, OpenCV functions arepreferred. But, there can be exceptions, especially when Numpy works with views instead of copies.
There are several other magic commands to measure the performance, profiling, line profiling, memory measurementetc. They all are well documented. So only links to those docs are provided here. Interested readers are recommendedto try them out.
There are several techniques and coding methods to exploit maximum performance of Python and Numpy. Onlyrelevant ones are noted here and links are given to important sources. The main thing to be noted here is that, first tryto implement the algorithm in a simple manner. Once it is working, profile it, find the bottlenecks and optimize them. 1. Avoid using loops in Python as far as possible, especially double/triple loops etc. They are inherently slow. 2. Vectorize the algorithm/code to the maximum possible extent because Numpy and OpenCV are optimized for vector operations. 3. Exploit the cache coherence. 4. Never make copies of array unless it is needed. Try to use views instead. Array copying is a costly operation.Even after doing all these operations, if your code is still slow, or use of large loops are inevitable, use additionallibraries like Cython to make it faster.
Changing Colorspaces
Image Thresholding
Smoothing Images
Learn to blur the images, filter the images with custom kernels etc.
Morphological Transformations
Image Gradients
Image Pyramids
Learn about image pyramids and how to use them for image blending
Contours in OpenCV
Histograms in OpenCV
Template Matching
In this tutorial, you will learn how to convert images from one color-space to another, like BGR Gray, BGR HSV etc. In addition to that, we will create an application which extracts a colored object in a video You will learn following functions : cv2.cvtColor(), cv2.inRange() etc.
Changing Color-space
There are more than 150 color-space conversion methods available in OpenCV. But we will look into only two whichare most widely used ones, BGR Gray and BGR HSV.For color conversion, we use the function cv2.cvtColor(input_image, flag) where flag determines thetype of conversion.For BGR Gray conversion we use the flags cv2.COLOR_BGR2GRAY. Similarly for BGR HSV, we use the flagcv2.COLOR_BGR2HSV. To get other flags, just run following commands in your Python terminal :>>> import cv2>>> flags = [i for i in dir(cv2) if i.startswith('COLOR_')]>>> print flags
Note: For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]. Different softwares usedifferent scales. So if you are comparing OpenCV values with them, you need to normalize these ranges.
Object Tracking
Now we know how to convert BGR image to HSV, we can use this to extract a colored object. In HSV, it is more easierto represent a color than RGB color-space. In our application, we will try to extract a blue colored object. So here isthe method: Take each frame of the video Convert from BGR to HSV color-space We threshold the HSV image for a range of blue color Now extract the blue object alone, we can do whatever on that image we want.Below is the code which are commented in detail :import cv2import numpy as np
while(1):
cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) k = cv2.waitKey(5) & 0xFF if k == 27: break
Note: There are some noises in the image. We will see how to remove them in later chapters.
Note: This is the simplest method in object tracking. Once you learn functions of contours, you can do plenty ofthings like find centroid of this object and use it to track the object, draw diagrams just by moving your hand in frontof camera and many other funny stuffs.
This is a common question found in stackoverflow.com. It is very simple and you can use the same function,cv2.cvtColor(). Instead of passing an image, you just pass the BGR values you want. For example, to find theHSV value of Green, try following commands in Python terminal:
Now you take [H-10, 100,100] and [H+10, 255, 255] as lower bound and upper bound respectively. Apart from thismethod, you can use any image editing tools like GIMP or any online converters to find these values, but dont forgetto adjust the HSV ranges.
1. Try to find a way to extract more than one colored objects, for eg, extract red, blue, green objects simultaneously.
In this tutorial, you will learn Simple thresholding, Adaptive thresholding, Otsus thresholding etc. You will learn these functions : cv2.threshold, cv2.adaptiveThreshold etc.
Simple Thresholding
Here, the matter is straight forward. If pixel value is greater than a threshold value, it is assigned one value (may bewhite), else it is assigned another value (may be black). The function used is cv2.threshold. First argument is thesource image, which should be a grayscale image. Second argument is the threshold value which is used to classifythe pixel values. Third argument is the maxVal which represents the value to be given if pixel value is more than(sometimes less than) the threshold value. OpenCV provides different styles of thresholding and it is decided by thefourth parameter of the function. Different types are: cv2.THRESH_BINARY cv2.THRESH_BINARY_INV cv2.THRESH_TRUNC cv2.THRESH_TOZERO cv2.THRESH_TOZERO_INVDocumentation clearly explain what each type is meant for. Please check out the documentation.Two outputs are obtained. First one is a retval which will be explained later. Second output is our thresholded image.Code :import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('gradient.png')
for i in xrange(6): plt.subplot(2,3,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([])
Note: To plot multiple images, we have used plt.subplot() function. Please checkout Matplotlib docs for more details.
Adaptive Thresholding
In the previous section, we used a global value as threshold value. But it may not be good in all the conditions whereimage has different lighting conditions in different areas. In that case, we go for adaptive thresholding. In this, thealgorithm calculate the threshold for a small regions of the image. So we get different thresholds for different regionsof the same image and it gives us better results for images with varying illumination.It has three special input params and only one output argument.Adaptive Method - It decides how thresholding value is calculated. cv2.ADAPTIVE_THRESH_MEAN_C : threshold value is the mean of neighbourhood area.)
for i in xrange(4): plt.subplot(2,2,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([])plt.show()
Result :
Otsus Binarization
In the first section, I told you there is a second parameter retVal. Its use comes when we go for Otsus Binarization.So what is it?In global thresholding, we used an arbitrary value for threshold value, right? So, how can we know a value we selectedis good or not? Answer is, trial and error method. But consider a bimodal image (In simple words, bimodal image isan image whose histogram has two peaks). For that image, we can approximately take a value in the middle of thosepeaks as threshold value, right ? That is what Otsu binarization does. So in simple words, it automatically calculatesa threshold value from image histogram for a bimodal image. (For images which are not bimodal, binarization wontbe accurate.)For this, our cv2.threshold() function is used, but pass an extra flag, cv2.THRESH_OTSU. For threshold value, simplypass zero. Then the algorithm finds the optimal threshold value and returns you as the second output, retVal. IfOtsu thresholding is not used, retVal is same as the threshold value you used.
Check out below example. Input image is a noisy image. In first case, I applied global thresholding for a value of127. In second case, I applied Otsus thresholding directly. In third case, I filtered image with a 5x5 gaussian kernelto remove the noise, then applied Otsu thresholding. See how noise filtering improves the result.import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('noisy2.png',0)
# global thresholdingret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
# Otsu's thresholdingret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)()
This section demonstrates a Python implementation of Otsus binarization to show how it works actually. If you arenot interested, you can skip this.Since we are working with bimodal images, Otsus algorithm tries to find a threshold value (t) which minimizes theweighted within-class variance given by the relation : 2 () = 1 ()12 () + 2 ()22 ()
where 1 () = () & 1 () = () =1 =+1 () () 1 () = & 2 () = =1 1 () () =+1 2 () () 12 () = [ 1 ()]2 & 22 () = [ 1 ()]2 =1 1 () =+1 2 ()
It actually finds a value of t which lies in between two peaks such that variances to both classes are minimum. It canbe simply implemented in Python as follows:img = cv2.imread('noisy2.png',0)blur = cv2.GaussianBlur(img,(5,5),0)
hist_norm = hist.ravel()/hist.max()Q = hist_norm.cumsum()
bins = np.arange(256)
fn_min = np.infthresh = -1
for i in xrange(1,256): p1,p2 = np.hsplit(hist_norm,[i]) # probabilities q1,q2 = Q[i],Q[255]-Q[i] # cum sum of classes b1,b2 = np.hsplit(bins,[i]) # weights
(Some of the functions may be new here, but we will cover them in coming chapters)
1. There are some optimizations available for Otsus binarization. You can search and implement it.
Learn to apply different geometric transformation to images like translation, rotation, affine transformation etc. You will see these functions: cv2.getPerspectiveTransform
Transformations
OpenCV provides two transformation functions, cv2.warpAffine and cv2.warpPerspective, with which you can haveall kinds of transformations. cv2.warpAffine takes a 2x3 transformation matrix while cv2.warpPerspective takes a3x3 transformation matrix as input.
Scaling
Scaling is just resizing of the image. OpenCV comes with a function cv2.resize() for this purpose. The size ofthe image can be specified manually, or you can specify the scaling factor. Different interpolation methods areused. Preferable interpolation methods are cv2.INTER_AREA for shrinking and cv2.INTER_CUBIC (slow) &cv2.INTER_LINEAR for zooming. By default, interpolation method used is cv2.INTER_LINEAR for all resizingpurposes. You can resize an input image either of following methods:import cv2import numpy as np
img = cv2.imread('messi5.jpg')
#OR
Translation
Translation is the shifting of objects location. If you know the shift in (x,y) direction, let it be ( , ), you can createthe transformation matrix M as follows: [ ] 1 0 = 0 1
You can take make it into a Numpy array of type np.float32 and pass it into cv2.warpAffine() function. See belowexample for a shift of (100,50):import cv2import numpy as np
img = cv2.imread('messi5.jpg',0)rows,cols = img.shape
M = np.float32([[1,0,100],[0,1,50]])dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('img',dst)cv2.waitKey(0)cv2.destroyAllWindows()
Warning: Third argument of the cv2.warpAffine() function is the size of the output image, which should be in the form of (width, height). Remember width = number of columns, and height = number of rows.
Rotation
Rotation of an image for an angle is achieved by the transformation matrix of the form [ ] = But OpenCV provides scaled rotation with adjustable center of rotation so that you can rotate at any location youprefer. Modified transformation matrix is given by [ ] (1 ) . . . + (1 ) .where: = cos , = sin To find this transformation matrix, OpenCV provides a function, cv2.getRotationMatrix2D. Check below examplewhich rotates the image by 90 degree with respect to center without any scaling.img = cv2.imread('messi5.jpg',0)rows,cols = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)dst = cv2.warpAffine(img,M,(cols,rows))
Affine Transformation
In affine transformation, all parallel lines in the original image will still be parallel in the output image. To find thetransformation matrix, we need three points from input image and their corresponding locations in output image. Thencv2.getAffineTransform will create a 2x3 matrix which is to be passed to cv2.warpAffine.
Check below example, and also look at the points I selected (which are marked in Green color):img = cv2.imread('drawing.png')rows,cols,ch = img.shape
pts1 = np.float32([[50,50],[200,50],[50,200]])pts2 = np.float32([[10,100],[200,50],[100,250]])
M = cv2.getAffineTransform(pts1,pts2)
dst = cv2.warpAffine(img,M,(cols,rows))
plt.subplot(121),plt.imshow(img),plt.title('Input')plt.subplot(122),plt.imshow(dst),plt.title('Output')plt.show()
Perspective Transformation
For perspective transformation, you need a 3x3 transformation matrix. Straight lines will remain straight even afterthe transformation. To find this transformation matrix, you need 4 points on the input image and corresponding pointson the output image. Among these 4 points, 3 of them should not be collinear. Then transformation matrix can befound by the function cv2.getPerspectiveTransform. Then apply cv2.warpPerspective with this 3x3 transformationmatrix.See the code below:img = cv2.imread('sudokusmall.png')rows,cols,ch = img.shape
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(300,300))
Result:
Learn to: Blur imagess with various low pass filters Apply custom-made filters to images (2D convolution)
As for one-dimensional signals, images also can be filtered with various low-pass filters (LPF), high-pass filters (HPF),etc. A LPF helps in removing noise, or blurring the image. A HPF filters helps in finding edges in an image.OpenCV provides a function, cv2.filter2D(), to convolve a kernel with an image. As an example, we will try an
averaging filter on an image. A 5x5 averaging filter kernel can be defined as follows: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 = 25 1 1 1 1 1 1 1 1 1 1
Filtering with the above kernel results in the following being performed: for each pixel, a 5x5 window is centered onthis pixel, all pixels falling within this window are summed up, and the result is then divided by 25. This equates tocomputing the average of the pixel values inside that window. This operation is performed for all the pixels in theimage to produce the output filtered image. Try this code and check the result:import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('opencv_logo.png')
kernel = np.ones((5,5),np.float32)/25dst = is achieved by convolving the image with a low-pass filter kernel. It is useful for removing noise. Itactually removes high frequency content (e.g: noise, edges) from the image resulting in edges being blurred when thisis filter is applied. (Well, there are blurring techniques which do not blur edges). OpenCV provides mainly four typesof blurring techniques.
1. Averaging
This is done by convolving the image with a normalized box filter. It simply takes the average of all the pixelsunder kernel area and replaces the central element with this average. This is done by the function cv2.blur() orcv2.boxFilter(). Check the docs for more details about the kernel. We should specify the width and height of kernel.A 3x3 normalized box filter would look like this: 1 1 1 1 = 1 1 1 9 1 1 1
Note: If you dont want to use a normalized box filter, use cv2.boxFilter() and pass the argumentnormalize=False to the function. approach, instead of a box filter consisting of equal filter coefficients, a Gaussian kernel is used. It is done withthe function, cv2.GaussianBlur(). We should specify the width and height of the kernel which should be positive andodd. We also should specify the standard deviation in the X and Y directions, sigmaX and sigmaY respectively. Ifonly sigmaX is specified, sigmaY is taken as equal to sigmaX. If both are given as zeros, they are calculated from thekernel size. Gaussian filtering is highly effective in removing Gaussian noise from the image.If you want, you can create a Gaussian kernel with the function, cv2.getGaussianKernel().The above code can be modified for Gaussian blurring:blur = cv2.GaussianBlur(img,(5,5),0)
3. Median Filtering
Here, the function cv2.medianBlur() computes the median of all the pixels under the kernel window and the centralpixel is replaced with this median value. This is highly effective in removing salt-and-pepper noise. One interestingthing to note is that, in the Gaussian and box filters, the filtered value for the central element can be a value which maynot exist in the original image. However this is not the case in median filtering, since the central element is alwaysreplaced by some pixel value in the image. This reduces the noise effectively. The kernel size must be a positive oddinteger.In this demo, we add a 50% noise to our original image and use a median filter. Check the result:median = cv2.medianBlur(img,5)
4. Bilateral Filtering
As we noted, the filters we presented earlier tend to blur edges. This is not the case for the bilateral filter,cv2.bilateralFilter(), which was defined for, and is highly effective at noise removal while preserving edges. Butthe operation is slower compared to other filters. We already saw that a Gaussian filter takes the a neighborhoodaround the pixel and finds its Gaussian weighted average. This Gaussian filter is a function of space alone, that is,nearby pixels are considered while filtering. It does not consider whether pixels have almost the same intensity valueand does not consider whether the pixel lies on an edge or not. The resulting effect is that Gaussian filters tend to bluredges, which is undesirable.The bilateral filter also uses a Gaussian filter in the space domain, but it also uses one more (multiplicative) Gaussianfilter component which is a function of pixel intensity differences. The Gaussian function of space makes sure thatonly pixels are spatial neighbors are considered for filtering, while the Gaussian component applied in the intensitydomain (a Gaussian function of intensity differences) ensures that only those pixels with intensities similar to that ofthe central pixel (intensity neighbors) are included to compute the blurred intensity value. As a result, this methodpreserves edges, since for pixels lying near edges, neighboring pixels placed on the other side of the edge, and thereforeexhibiting large intensity variations when compared to the central pixel, will not be included for blurring.The sample below demonstrates the use of bilateral filtering (For details on arguments, see the OpenCV docs).blur = cv2.bilateralFilter(img,9,75,75)
Note that the texture on the surface is gone, but edges are still preserved.
Take an image, add Gaussian noise and salt and pepper noise, compare the effect of blurring via box, Gaussian, medianand bilateral filters for both noisy images, as you change the level of noise.
In this chapter, We will learn different morphological operations like Erosion, Dilation, Opening, Closing etc. We will see different functions like : cv2.erode(), cv2.dilate(), cv2.morphologyEx() etc.
Theory
Morphological transformations are some simple operations based on the image shape. It is normally performed onbinary images. It needs two inputs, one is our original image, second one is called structuring element or kernelwhich decides the nature of operation. Two basic morphological operators are Erosion and Dilation. Then its variantforms like Opening, Closing, Gradient etc also comes into play. We will see them one-by-one with help of followingimage:
1. Erosion
The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground object (Alwaystry to keep foreground in white). So what does it do? The kernel slides through the image (as in 2D convolution). Apixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1, otherwise itis eroded (made to zero).So what happends is that, all the pixels near boundary will be discarded depending upon the size of kernel. So thethickness or size of the foreground object decreases or simply white region decreases in the image. It is useful forremoving small white noises (as we have seen in colorspace chapter), detach two connected objects etc.Here, as an example, I would use a 5x5 kernel with full of ones. Lets see it how it works:import cv2import numpy as np
img = cv2.imread('j.png',0)kernel = np.ones((5,5),np.uint8)erosion = cv2.erode(img,kernel,iterations = 1)
2. Dilation
It is just opposite of erosion. Here, a pixel element is 1 if atleast one pixel under the kernel is 1. So it increasesthe white region in the image or size of foreground object increases. Normally, in cases like noise removal, erosion
is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Sincenoise is gone, they wont come back, but our object area increases. It is also useful in joining broken parts of an object.dilation = cv2.dilate(img,kernel,iterations = 1)
3. Opening
Opening is just another name of erosion followed by dilation. It is useful in removing noise, as we explained above.Here we use the function, cv2.morphologyEx()opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
4. Closing
Closing is reverse of Opening, Dilation followed by Erosion. It is useful in closing small holes inside the foregroundobjects, or small black points on the object.closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
5. Morphological Gradient
6. Top Hat
It is the difference between input image and Opening of the image. Below example is done for a 9x9 kernel.tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
7. Black Hat
It is the difference between the closing of the input image and input image.blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)
Structuring Element)
OpenCV provides three types of gradient filters or High-pass filters, Sobel, Scharr and Laplacian. We will see eachone of them.
Sobel operators is a joint Gausssian smoothing plus differentiation operation, so it is more resistant to noise. Youcan specify the direction of derivatives to be taken, vertical or horizontal (by the arguments, yorder and xorderrespectively). You can also specify the size of kernel by the argument ksize. If ksize = -1, a 3x3 Scharr filter is usedwhich gives better results than 3x3 Sobel filter. Please see the docs for kernels used.
2. Laplacian Derivatives
2 2It calculates the Laplacian of the image given by the relation, = 2 + 2 where each derivative is foundusing Sobel derivatives. If ksize = 1, then following kernel is used for filtering: 0 1 0 = 1 4 1 0 1 0
Below code shows all operators in a single diagram. All kernels are of 5x5 size. Depth of output image is passed -1 toget the result in np.uint8 type.import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('dave.jpg',0)
laplacian = cv2.Laplacian(img,cv2.CV_64F)sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)
plt.subplot(2,2,1),plt.imshow(img,cmap = 'gray')plt.title('Original'), plt.xticks([]), plt.yticks([])plt.subplot(2,2,2),plt.imshow(laplacian,cmap = 'gray')plt.title('Laplacian'), plt.xticks([]), plt.yticks([])plt.subplot(2,2,3),plt.imshow(sobelx,cmap = 'gray')plt.title('Sobel X'), plt.xticks([]), plt.yticks([])plt.subplot(2,2,4),plt.imshow(sobely,cmap = 'gray')plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])
In our last example, output datatype is cv2.CV_8U or np.uint8. But there is a slight problem with that. Black-to-Whitetransition is taken as Positive slope (it has a positive value) while White-to-Black transition is taken as a Negative slope(It has negative value). So when you convert data to np.uint8, all negative slopes are made zero. In simple words, youmissfor a horizontal Sobel filter and difference in results.import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('box.png',0)
# Output dtype = cv2.CV_64F. Then take its absolute and convert to cv2.CV_8Usobelx64f = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)abs_sobel64f = np.absolute(sobelx64f)sobel_8u = np.uint8(abs_sobel64f)
plt.subplot(1,3,1),plt.imshow(img,cmap = 'gray')plt.title('Original'), plt.xticks([]), plt.yticks([])plt.subplot(1,3,2),plt.imshow(sobelx8u,cmap = 'gray')plt.title('Sobel CV_8U'), plt.xticks([]), plt.yticks([])plt.subplot(1,3,3),plt.imshow(sobel_8u,cmap = 'gray')plt.title('Sobel abs(CV_64F)'), plt.xticks([]), plt.yticks([])
Canny Edge Detection is a popular edge detection algorithm. It was developed by John F. Canny in 1986. It is amulti-stage algorithm and we will go through each stages. 1. Noise Reduction
Since edge detection is susceptible to noise in the image, first step is to remove the noise in the image with a 5x5Gaussian filter. We have already seen this in previous chapters. 2. Finding Intensity Gradient of the ImageSmoothened image is then filtered with a Sobel kernel in both horizontal and vertical direction to get first derivative inhorizontal direction ( ) and vertical direction ( ). From these two images, we can find edge gradient and directionfor each pixel as follows: _ () = 2 + 2 ( ) () = tan1
Gradient direction is always perpendicular to edges. It is rounded to one of four angles representing vertical, horizontaland two diagonal directions. 3. Non-maximum SuppressionAfter getting gradient magnitude and direction, a full scan of image is done to remove any unwanted pixels which maynot constitute the edge. For this, at every pixel, pixel is checked if it is a local maximum in its neighborhood in thedirection of gradient. Check the image below:
Point A is on the edge ( in vertical direction). Gradient direction is normal to the edge. Point B and C are in gradientdirections. So point A is checked with point B and C to see if it forms a local maximum. If so, it is considered for nextstage, otherwise, it is suppressed ( put to zero).In short, the result you get is a binary image with thin edges. 4. Hysteresis ThresholdingThis stage decides which are all edges are really edges and which are not. For this, we need two threshold values,minVal and maxVal. Any edges with intensity gradient more than maxVal are sure to be edges and those below minValare sure to be non-edges, so discarded. Those who lie between these two thresholds are classified edges or non-edgesbased on their connectivity. If they are connected to sure-edge pixels, they are considered to be part of edges.Otherwise, they are also discarded. See the image below:
The edge A is above the maxVal, so considered as sure-edge. Although edge C is below maxVal, it is connected toedge A, so that also considered as valid edge and we get that full curve. But edge B, although it is above minVal andis in same region as that of edge C, it is not connected to any sure-edge, so that is discarded. So it is very importantthat we have to select minVal and maxVal accordingly to get the correct result.This stage also removes small pixels noises on the assumption that edges are long lines.So what we finally get is strong edges in the image.
OpenCV puts all the above in single function, cv2.Canny(). We will see how to use it. First argument is our inputimage. Second and third arguments are our minVal and maxVal respectively. Third argument is aperture_size. It is thesize of Sobel kernel used for find image gradients. By default it is 3. Last argument is L2gradient which specifies theequation for finding gradient magnitude. If it is True, it uses the equation mentioned above which is more accurate,otherwise it uses this function: _ () = | | + | |. By default, it is False.import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0([])
1. Write a small application to find the Canny edge detection whose threshold values can be varied using two trackbars. This way, you can understand the effect of threshold values.
In this chapter, We will learn about Image Pyramids We will use Image pyramids to create a new fruit, Orapple We will see these functions: cv2.pyrUp(), cv2.pyrDown()
Normally, we used to work with an image of constant size. But in some occassions, we need to work with imagesof different resolution of the same image. For example, while searching for something in an image, like face, we arenot sure at what size the object will be present in the image. In that case, we will need to create a set of images withdifferent resolution and search for object in all the images. These set of images with different resolution are calledImage Pyramids (because when they are kept in a stack with biggest image at bottom and smallest image at top looklike a pyramid).There are two kinds of Image Pyramids. 1) Gaussian Pyramid and 2) Laplacian PyramidsHigher level (Low resolution) in a Gaussian Pyramid is formed by removing consecutive rows and columns in Lowerlevel (higher resolution) image. Then each pixel in higher level is formed by the contribution from 5 pixels in un-derlying level with gaussian weights. By doing so, a image becomes /2 /2 image. So area reducesto one-fourth of original area. It is called an Octave. The same pattern continues as we go upper in pyramid (ie,resolution decreases). Similarly while expanding, area becomes 4 times in each level. We can find Gaussian pyramidsusing cv2.pyrDown() and cv2.pyrUp() functions.
img = cv2.imread('messi5.jpg')lower_reso = cv2.pyrDown(higher_reso)
Now you can go down the image pyramid with cv2.pyrUp() function.higher_reso2 = cv2.pyrUp(lower_reso)
Remember, higher_reso2 is not equal to higher_reso, because once you decrease the resolution, you loose the infor-mation. Below image is 3 level down the pyramid created from smallest image in previous case. Compare it withoriginal image:
Laplacian Pyramids are formed from the Gaussian Pyramids. There is no exclusive function for that. Laplacianpyramid images are like edge images only. Most of its elements are zeros. They are used in image compression. Alevel in Laplacian Pyramid is formed by the difference between that level in Gaussian Pyramid and expanded versionof its upper level in Gaussian Pyramid. The three levels of a Laplacian level will look like below (contrast is adjustedto enhance the contents):
One application of Pyramids is Image Blending. For example, in image stitching, you will need to stack two imagestogether, but it may not look good due to discontinuities between images. In that case, image blending with Pyramidsgives you seamless blending without leaving much data in the images. One classical example of this is the blendingof two fruits, Orange and Apple. See the result now itself to understand what I am saying:
Please check first reference in additional resources, it has full diagramatic details on image blending, Laplacian Pyra-mids etc. Simply it is done as follows: 1. Load the two images of apple and orange 2. Find the Gaussian Pyramids for apple and orange (in this particular example, number of levels is 6) 3. From Gaussian Pyramids, find their Laplacian Pyramids 4. Now join the left half of apple and right half of orange in each levels of Laplacian Pyramids 5. Finally from this joint image pyramids, reconstruct the original image.
Below is the full code. (For sake of simplicity, each step is done separately which may take more memory. You canoptimize it if you want so).import cv2import numpy as np,sys
A = cv2.imread('apple.jpg')B = cv2.imread('orange.jpg')
# now reconstructls_ = LS[0]for i in xrange(1,6): ls_ = cv2.pyrUp(ls_) ls_ = cv2.add(ls_, LS[i])
cv2.imwrite('Pyramid_blending2.jpg',ls_)cv2.imwrite('Direct_blending.jpg',real)
1. Image Blending
Contour Features
Contour Properties
Contours Hierarchy
Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same coloror intensity. The contours are a useful tool for shape analysis and object detection and recognition. For better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection. findContours function modifies the source image. So if you want source image even after finding contours, already store it to some other variables. In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.Lets see how to find contours of a binary image:import numpy as npimport cv2
im = cv2.imread('test.jpg')imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)ret,thresh = cv2.threshold(imgray,127,255,0)image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
See, there are three arguments in cv2.findContours() function, first one is source image, second is contour retrievalmode, third is contour approximation method. And it outputs the image, contours and hierarchy. contours is aPython list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundarypoints of the object.
Note: We will discuss second and third arguments and about hierarchy in details later. Until then, the values given tothem in code sample will work fine for all images.
To draw the contours, cv2.drawContours function is used. It can also be used to draw any shape provided youhave its boundary points. Its first argument is source image, second argument is the contours which should be passedas a Python list, third argument is index of contours (useful when drawing individual contour. To draw all contours,pass -1) and remaining arguments are color, thickness etc.To draw all the contours in an image:img = cv2.drawContours(img, contours, -1, (0,255,0), 3)
Note: Last two methods are same, but when you go forward, you will see last one is more useful.
This is the third argument in cv2.findContours function. What does it denote actually?Above, we told that contours are the boundaries of a shape with same intensity. It stores the (x,y) coordinates of theboundary, weneed just two end points of that line. This is what cv2.CHAIN_APPROX_SIMPLE does. It removes all redundantpointsimage shows the one with cv2.CHAIN_APPROX_SIMPLE (only 4 points). See, how much memory it saves!!!
Contour Features
1. Moments
Image moments help you to calculate some features like center of mass of the object, area of the object etc. Check outthe wikipedia page on Image MomentsThe function cv2.moments() gives a dictionary of all moment values calculated. See below:import cv2import
10From this moments, you can extract useful data like area, centroid etc. Centroid is given by the relations, = 00 01and = 00 . This can be done as follows:cx = int(M['m10']/M['m00'])cy = int(M['m01']/M['m00'])
2. Contour Area
3. Contour Perimeter
It is also called arc length. It can be found out using cv2.arcLength() function. Second argument specify whethershape is a closed contour (if passed True), or just a curve.perimeter = cv2.arcLength(cnt,True)
4. Contour Approximation
It approximates a contour shape to another shape with less number of vertices depending upon the precision we specify.It is an implementation of Douglas-Peucker algorithm. Check the wikipedia page for algorithm and demonstration.To understand this, suppose you are trying to find a square in an image, but due to some problems in the image, youdidnt get a perfect square, but a bad shape (As shown in first image below). Now you can use this function toapproximate the shape. In this, second argument is called epsilon, which is maximum distance from contour toapproximated contour. It is an accuracy parameter. A wise selection of epsilon is needed to get the correct output.epsilon = 0.1*cv2.arcLength(cnt,True)approx = cv2.approxPolyDP(cnt,epsilon,True)
Below, in second image, green line shows the approximated curve for epsilon = 10% of arc length. Thirdimage shows the same for epsilon = 1% of the arc length. Third argument specifies whether curve isclosed or not.
5. Convex Hull
Convex Hull will look similar to contour approximation, but it is not (Both may provide same results in some cases).Here, cv2.convexHull() function checks a curve for convexity defects and corrects it. Generally speaking, convexcurves are the curves which are always bulged out, or at-least flat. And if it is bulged inside, it is called convexitydefects. For example, check the below image of hand. Red line shows the convex hull of hand. The double-sidedarrow marks shows the convexity defects, which are the local maximum deviations of hull from contours.)
But if you want to find convexity defects, you need to pass returnPoints = False. To understand it, we willtake the rectangle image above. First I found its contour as cnt. Now I found its convex hull with returnPoints= True, I got following values: [[[234 202]], [[ 51 202]], [[ 51 79]], [[234 79]]] whichare the four corner points of rectangle. Now if do the same with returnPoints = False, I get following result:[[129],[ 67],[ 0],[142]]. These are the indices of corresponding points in contours. For eg, check the firstvalue: cnt[129] = [[234, 202]] which is same as first result (and so on for others).You will see it again when we discuss about convexity defects.
6. Checking Convexity
7.a. Straight Bounding Rectangle It is a straight rectangle, it doesnt consider the rotation of the object. So area ofthe bounding rectangle wont be minimum. It is found by the function cv2.boundingRect().Let (x,y) be the top-left coordinate of the rectangle and (w,h) be its width and height.x,y,w,h = cv2.boundingRect(cnt)img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
7.b. Rotated Rectangle Here, bounding rectangle is drawn with minimum area, so it considers the rotation also.The function used is cv2.minAreaRect(). It returns a Box2D structure which contains following detals - ( top-leftcorner(x,y), (width, height), angle of rotation ). But to draw this rectangle, we need 4 corners of the rectangle. It isobtainedthe rotated rect.
Next we find the circumcircle of an object using the function cv2.minEnclosingCircle(). It is a circle which com-pletely covers the object with minimum area.(x,y),radius = cv2.minEnclosingCircle(cnt)center = (int(x),int(y))radius = int(radius)img = cv2.circle(img,center,radius,(0,255,0),2)
9. Fitting an Ellipse)
Similarly we can fit a line to a set of points. Below image contains a set of white points. We can approximate a straightline)
Contour Properties
Here we will learn to extract some frequently used properties of objects like Solidity, Equivalent Diameter, Maskimage, Mean Intensity etc. More features can be found at Matlab regionprops documentation.(NB : Centroid, Area, Perimeter etc also belong to this category, but we have seen it in last chapter)
1. Aspect Ratio
x,y,w,h = cv2.boundingRect(cnt)aspect_ratio = float(w)/h
2. Extent
area = cv2.contourArea(cnt)x,y,w,h = cv2.boundingRect(cnt)rect_area = w*hextent = float(area)/rect_area
3. Solidity
area = cv2.contourArea(cnt)hull = cv2.convexHull(cnt)hull_area = cv2.contourArea(hull)solidity = float(area)/hull_area
4. Equivalent Diameter
Equivalent Diameter is the diameter of the circle whose area is same as the contour area. 4 =
area = cv2.contourArea(cnt)equi_diameter = np.sqrt(4*area/np.pi)
5. Orientation
Orientation is the angle at which object is directed. Following method also gives the Major Axis and Minor Axislengths.(x,y),(MA,ma),angle = cv2.fitEllipse(cnt)
In some cases, we may need all the points which comprises that object. It can be done as follows:mask = np.zeros(imgray.shape,np.uint8)cv2.drawContours(mask,[cnt],0,255,-1)pixelpoints = np.transpose(np.nonzero(mask))#pixelpoints = cv2.findNonZero(mask)
Here, two methods, one using Numpy functions, next one using OpenCV function (last commented line) are given todo the same. Results are also same, but with a slight difference. Numpy gives coordinates in (row, column) format,while OpenCV gives coordinates in (x,y) format. So basically the answers will be interchanged. Note that, row = xand column = y.
Here, we can find the average color of an object. Or it can be average intensity of the object in grayscale mode. Weagain use the same mask to do it.mean_val = cv2.mean(im,mask = mask)
9. Extreme Points
Extreme Points means topmost, bottommost, rightmost and leftmost points of the object.leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])topmost = tuple(cnt[cnt[:,:,1].argmin()][0])bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])
1. There are still some features left in matlab regionprops doc. Try to implement them.
1. Convexity Defects We saw what is convex hull in second chapter about contours. Any deviation of the objectfrom this hull can be considered as convexity defect.OpenCV comes with a ready-made function to find this, cv2.convexityDefects(). A basic function call would looklike below:hull = cv2.convexHull(cnt,returnPoints = False)defects = cv2.convexityDefects(cnt,hull)
Note: Remember we have to pass returnPoints = False while finding convex hull, in order to find convexitydefects.
It returns an array where each row contains these values - [ start point, end point, farthest point, approximatedistance to farthest point ]. We can visualize it using an image. We draw a line joining start point and end point, thendraw a circle at the farthest point. Remember first three values returned are indices of cnt. So we have to bring thosevalues from cnt.import cv2import()
2. Point Polygon Test This function finds the shortest distance between a point in the image and a contour. It returnsthe distance which is negative when point is outside the contour, positive when point is inside and zero if point is onthe contour.For example, we can check the point (50,50) as follows:dist = cv2.pointPolygonTest(cnt,(50,50),True)
In the function, third argument is measureDist. If it is True, it finds the signed distance. If False, it findswhether the point is inside or outside or on the contour (it returns +1, -1, 0 respectively).
Note: If you dont want to find the distance, make sure third argument is False, because, it is a time consumingprocess. So, making it False gives about 2-3X speedup.
3. Match Shapes OpenCV comes with a function cv2.matchShapes() which enables us to compare two shapes, ortwo contours and returns a metric showing the similarity. The lower the result, the better match it is. It is calculatedbased on the hu-moment values. Different measurement methods are explained in the docs.import cv2import numpy as np
img1 = cv2.imread('star.jpg',0)img2 = cv2.imread('star2.jpg',0)
ret = cv2.matchShapes(cnt1,cnt2,1,0.0)print ret
1. Check the documentation for cv2.pointPolygonTest(), you can find a nice image in Red and Blue color. It represents the distance from all pixels to the white curve on it. All pixels inside curve is blue depending on the distance. Similarly outside points are red. Contour edges are marked with White. So problem is simple. Write a code to create such a representation of distance. 2. Compare images of digits or letters using cv2.matchShapes(). ( That would be a simple step towards OCR )
Contours Hierarchy
This2.findContours() function, we have passed an argument, ContourRetrieval Mode. We usually passed cv2.RETR_LIST or cv2.RETR_TREE and it worked nice. But what does itactually mean ?Also, in the output, we got three arrays, first is the image, second is our contours, and one more output which wenamed as hierarchy (Please checkout the codes in previous articles). But we never used this hierarchy anywhere.
Then what is this hierarchy and what is it for ? What is its relationship with the previous mentioned function argument?That is what we are going to deal in this article.
What is Hierarchy? Normally we use the cv2.findContours() function to detect objects in an image, right ? Some-times objects are in different locations. But in some cases, some shapes are inside other shapes. Just like nestedfigures. In this case, we call outer one as parent and inner one as child. This way, contours in an image has somerelationship to each other. And we can specify how one contour is connected to each other, like, is it child of someother contour, or is it a parent etc. Representation of this relationship is called the Hierarchy.Consider an example image below :
In this image, there are a few shapes which I have numbered from 0-5. 2 and 2a denotes the external and internalcontours of the outermost box.Here, contours 0,1,2 are external or outermost. We can say, they are in hierarchy-0 or simply they are in samehierarchy level.Next comes contour-2a. It can be considered as a child of contour-2 (or in opposite way, contour-2 is parent ofcontour-2a). So let it be in hierarchy-1. Similarly contour-3 is child of contour-2 and it comes in next hierarchy.Finally contours 4,5 are the children of contour-3a, and they come in the last hierarchy level. From the way I numberedthe boxes, I would say contour-4 is the first child of contour-3a (It can be contour-5 also).I mentioned these things to understand terms like same hierarchy level, external contour, child contour, parentcontour, first child etc. Now lets. Previous denotes previous contour at the same hierarchical level.It is same as above. Previous contour of contour-1 is contour-0 in the same level. Similarly for contour-2, it iscontour-1. And for contour-0, there is no previous, so put it as -1. First_Child denotes its first child contour.There is no need of any explanation. For contour-2, child is contour-2a. So it gets the corresponding index valueof contour-2a. What about contour-3a? It has two children. But we take only first child. And it is contour-4. SoFirst_Child = 4 for contour-3a. Parent denotes index of its parent contour.It is just opposite of First_Child. Both for contour-4 and contour-5, parent contour is contour-3a. For contour-3a, itis contour-3 and so on.
So now we know about the hierarchy style used in OpenCV, we can check into Contour Retrieval Modes inOpenCV with the help of same image given above. ie what do flags like cv2.RETR_LIST, cv2.RETR_TREE,cv2.RETR_CCOMP, cv2.RETR_EXTERNAL etc mean?
1. RETR_LIST This is the simplest of the four flags (from explanation point of view). It simply retrieves all thecontours, but doesnt create any parent-child relationship. Parents and kids are equal under this rule, and they arejust contours. ie they all belongs to same hierarchy level.So here, 3rd and 4th term in hierarchy array is always -1. But obviously, Next and Previous terms will have theircorresponding values. Just check it yourself and verify it.Below is the result I got, and each row is hierarchy details of corresponding contour. For eg, first row corresponds tocontour 0. Next contour is contour 1. So Next = 1. There is no previous contour, so Previous = 0. And the remainingtwo, as told before, it is -1.>>> hierarchyarray([[[.
2. RETR_EXTERNAL If you use this flag, it returns only extreme outer flags. All child contours are left behind.We can say, under this law, Only the eldest in every family is taken care of. It doesnt care about other membersofit with above result. Below is what I got :>>> hierarchyarray([[[ 1, -1, -1, -1], [ 2, 0, -1, -1], [-1, 1, -1, -1]]])
You can use this flag if you want to extract only the outer contours. It might be useful in some cases.
3. RETR_CCOMP This flag retrieves all the contours and arranges them to a 2-level hierarchy. ie external contoursof the object (ie its boundary) are placed in hierarchy-1. And the contours of holes inside object (if any) is placed inhierarchy-2. If any object inside it, its contour is placed again in hierarchy-1 only. And its hole in hierarchy-2 and soonbelongschildcontour-3. So array is [-1,-1,-1,3].Remaining you can fill up. This is the final answer I got:>>> hierarchyarray([[[ 3, -1, 1, -1], [ 2, -1, -1, 0], [-1, 1, -1, 0], [ 5, 0, 4, -1], [-1, -1, -1, 3], [ 7, 3, 6, -1], [-1, -1, -1, 5], [ 8, 5, -1, -1], [-1, 7, -1, -1]]])
4. RETR_TREE And this is the final guy, Mr.Perfect. It retrieves all the contours and creates a full family hierarchylist. It even tells, who is the grandpa, father, son, grandson and even beyond... :).For examle, I took above image, rewrite the code for cv2.RETR_TREE, reorder the contours as per the result given byOpenCV and analyze it. Again, red letters give the contour number and green letters give the hierarchy order.
Take contour-0 : It is in hierarchy-0. Next contour in same hierarchy is contour-7. No previous contours. Child iscontour-1. And no parent. So array is [7,-1,1,-1].Take contour-2 : It is in hierarchy-1. No contour in same level. No previous one. Child is contour-2. Parent iscontour-0. So array is [-1,-1,2,0].And remaining, try yourself. Below is the full answer:
>>> hierarchyarray([[[ 7, -1, 1, -1], [-1, -1, 2, 0], [-1, -1, 3, 1], [-1, -1, 4, 2], [-1, -1, 5, 3], [ 6, -1, -1, 4], [-1, 5, -1, 4], [ 8, 0, -1, -1], [-1, 7, -1, -1]]])
Histograms - 3 : 2D Histograms
Learn to Find histograms, using both OpenCV and Numpy functions Plot histograms, using OpenCV and Matplotlib functions You will see these functions : cv2.calcHist(), np.histogram() etc.
So what is histogram ? You can consider histogram as a graph or plot, which gives you an overall idea about theintensity distribution of an image. It is a plot with pixel values (ranging from 0 to 255, not always) in X-axis andcorresponding number of pixels in the image on Y-axis.It is just another way of understanding the image. By looking at the histogram of an image, you get intuition aboutcontrast, brightness, intensity distribution etc of that image. Almost all image processing tools today, provides featureson histogram. Below is an image from Cambridge in Color website, and I recommend you to visit the site for moredetails.
You can see the image and its histogram. (Remember, this histogram is drawn for grayscale image, not color image).Left region of histogram shows the amount of darker pixels in image and right region shows the amount of brighterpixels. From the histogram, you can see dark region is more than brighter region, and amount of midtones (pixelvalues in mid-range, say around 127) are very less.
Find Histogram
Now we have an idea on what is histogram, we can look into how to find this. Both OpenCV and Numpy comewith in-built function for this. Before using those functions, we need to understand some terminologies related withhistograms.BINS :The above histogram shows the number of pixels for every pixel value, ie from 0 to 255. ie you need 256values to show the above histogram. But consider, what if you need not find the number of pixels for all pixel valuesseparately, but number of pixels in a interval of pixel values? say for example, you need to find the number of pixelslying between 0 to 15, then 16 to 31, ..., 240 to 255. You will need only 16 values to represent the histogram. And thatis what is shown in example given in OpenCV Tutorials on histograms.So what you do is simply split the whole histogram to 16 sub-parts and value of each sub-part is the sum of all pixelcount in it. This each sub-part is called BIN. In first case, number of bins where 256 (one for each pixel) while insecond case, it is only 16. BINS is represented by the term histSize in OpenCV docs.DIMS : It is the number of parameters for which we collect the data. In this case, we collect data regarding only onething, intensity value. So here it is 1.RANGE : It is the range of intensity values you want to measure. Normally, it is [0,256], ie all intensity values.
1. Histogram Calculation in OpenCV So now we use cv2.calcHist() function to find the histogram. Lets famil-iar lets.
2. Histogram Calculation in Numpy Numpy also provides you a function, np.histogram(). So instead of calcHist()function, you can try below line :hist,bins = np.histogram(img.ravel(),256,[0,256])
hist is same as we calculated before. But bins will have 257 elements, because Numpy calculates bins as 0-0.99,1-1.99, 2-2.99 etc. So final range would be 255-255.99. To represent that, they also add 256 at end of bins. But wedont need that 256. Upto 255 is sufficient.See also:
Numpy has another function, np.bincount() which is much faster than (around 10X) np.histogram(). So for one-dimensional histograms, you can better try that. Dont forget to set minlength = 256 in np.bincount. For example,hist = np.bincount(img.ravel(),minlength=256)
Note: OpenCV function is more faster than (around 40X) than np.histogram(). So stick with OpenCV function.
Plotting Histograms
img = cv2.imread('home.jpg',0)plt.hist(img.ravel(),256,[0,256]); plt.show()
Or you can use normal plot of matplotlib, which would be good for BGR plot. For that, you need to find the histogramdata first. Try below code:
import cv2import numpy as npfrom can deduct from the above graph that, blue has some high value areas in the image (obviously it should be due tothe sky)
2. Using OpenCV Well, here you adjust the values of histograms along with its bin values to look like x,y coor-dinates so that you can draw it using cv2.line() or cv2.polyline() function to generate same image as above. This isalready available with OpenCV-Python2 official samples. Check the Code
Application of Mask
We used cv2.calcHist() to find the histogram of the full image. What if you want to find histograms of some regionsof an image? Just create a mask image with white color on the region you want to find histogram and black otherwise.Then pass this as the mask.
img = cv2.imread('home.jpg',0)
# create a maskmask = np.zeros(img.shape[:2], np.uint8)mask[100:300, 100:400] = 255masked_img = cv2.bitwise_and(img,img,mask = mask)
See the result. In the histogram plot, blue line shows histogram of full image while green line shows histogram ofmasked region.
In this section, We will learn the concepts of histogram equalization and use it to improve the contrast of our images.
Consider an image whose pixel values are confined to some specific range of values only. For eg, brighter image willhave all pixels confined to high values. But a good image will have pixels from all regions of the image. So youneed to stretch this histogram to either ends (as given in below image, from wikipedia) and that is what HistogramEqualization does (in simple words). This normally improves the contrast of the image.
I would recommend you to read the wikipedia page on Histogram Equalization for more details about it. It has avery good explanation with worked out examples, so that you would understand almost everything after reading that.Instead, here we will see its Numpy implementation. After that, we will see OpenCV function.import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('wiki.jpg',0)
hist,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist.cumsum()cdf_normalized = cdf * hist.max()/ cdf.max()
You can see histogram lies in brighter region. We need the full spectrum. For that, we need a transformation functionwhich maps the input pixels in brighter region to output pixels in full region. That is what histogram equalization does.Now we find the minimum histogram value (excluding 0) and apply the histogram equalization equation as given inwiki page. But I have used here, the masked array concept array from Numpy. For masked array, all operations areperformedvalue. So we just apply the transform.img2 = cdf[img]
Now we calculate its histogram and cdf as before ( you do it) and result looks like below :
Another important feature is that, even if the image was a darker image (instead of a brighter one we used), afterequalization we will get almost the same image as we got. As a result, this is used as a reference tool to make allimages with same lighting conditions. This is useful in many cases. For example, in face recognition, before trainingthe face data, the images of faces are histogram equalized to make them all with same lighting conditions.
OpenCV has a function to do this, cv2.equalizeHist(). Its input is just grayscale image and output is our histogramequalized image.Below is a simple code snippet showing its usage for same image we used :img = cv2.imread('wiki.jpg',0)equ = cv2.equalizeHist(img)res = np.hstack((img,equ)) #stacking images side-by-sidecv2.imwrite('res.png',res)
So now you can take different images with different light conditions, equalize it and check the results.Histogram equalization is good when histogram of the image is confined to a particular region. It wont work good inplaces where there is large intensity variations where histogram covers a large region, ie both bright and dark pixelsare present. Please check the SOF links in Additional Resources.
The first histogram equalization we just saw, considers the global contrast of the image. In many cases, it is not a goodidea. For example, below image shows an input image and its result after global histogram equalization.
It is true that the background contrast has improved after histogram equalization. But compare the face of statue inboth images. We lost most of the information there due to over-brightness. It is because its histogram is not confinedto a particular region as we saw in previous cases (Try to plot histogram of input image, you will get more intuition).So to solve this problem, adaptive histogram equalization is used. In this, image is divided into small blocks calledtiles (tileSize is 8x8 by default in OpenCV). Then each of these blocks are histogram equalized as usual. So in asmall area, histogram would confine to a small region (unless there is noise). If noise is there, it will be amplified.To avoid this, contrast limiting is applied. If any histogram bin is above the specified contrast limit (by default 40in OpenCV), those pixels are clipped and distributed uniformly to other bins before applying histogram equalization.After equalization, to remove artifacts in tile borders, bilinear interpolation is applied.Below code snippet shows how to apply CLAHE in OpenCV:import numpy as npimport cv2
img = cv2.imread('tsukuba_l.png',0)
cv2.imwrite('clahe_2.jpg',cl1)
See the result below and compare it with results above, especially the statue region:
Histograms - 3 : 2D Histograms
In this chapter, we will learn to find and plot 2D histograms. It will be helpful in coming chapters.
In the first article, we calculated and plotted one-dimensional histogram. It is called one-dimensional because weare taking only one feature into our consideration, ie grayscale intensity value of the pixel. But in two-dimensionalhistograms, you consider two features. Normally it is used for finding color histograms where two features are Hue &Saturation values of every pixel.There is a python sample in the official samples already for finding color histograms. We will try to understand howto create such a color histogram, and it will be useful in understanding further topics like Histogram Back-Projection.
2D Histogram in OpenCV
It is quite simple and calculated using the same function, cv2.calcHist(). For color histograms, we need to convert theimage from BGR to HSV. (Remember, for 1D histogram, we converted from BGR to Grayscale). For 2D histograms,its parameters will be modified as follows: channels = [0,1] because we need to process both H and S plane. bins = [180,256] 180 for H plane and 256 for S plane. range = [0,180,0,256] Hue value lies between 0 and 180 & Saturation lies between 0 and 256.Now check the code below:import cv2import numpy as np
img = cv2.imread('home.jpg')hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
Thats it.
2D Histogram in Numpy
Numpy also provides a specific function for this : np.histogram2d(). (Remember, for 1D histogram we usednp.histogram() ).
First argument is H plane, second one is the S plane, third is number of bins for each and fourth is their range.Now we can check how to plot this color histogram.
Plotting 2D Histograms
Method - 1 : Using cv2.imshow() The result we get is a two dimensional array of size 180x256. So we can showthem as we do normally, using cv2.imshow() function. It will be a grayscale image and it wont give much idea whatcolors are there, unless you know the Hue values of different colors.
Method - 2 : Using Matplotlib We can use matplotlib.pyplot.imshow() function to plot 2D histogram with differ-ent color maps. It gives us much more better idea about the different pixel density. But this also, doesnt gives us ideawhat color is there on a first look, unless you know the Hue values of different colors. Still I prefer this method. It issimple and better.
Note: While using this function, remember, interpolation flag should be nearest for better results.
Consider code:import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('home.jpg')hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)hist = cv2.calcHist( [hsv], [0, 1], None, [180, 256], [0, 180, 0, 256] )
plt.imshow(hist,interpolation = 'nearest')plt.show()
Below is the input image and its color histogram plot. X axis shows S values and Y axis shows Hue.
In histogram, you can see some high values near H = 100 and S = 200. It corresponds to blue of sky. Similarly anotherpeak can be seen near H = 25 and S = 100. It corresponds to yellow of the palace. You can verify it with any imageediting tools like GIMP.
Method 3 : OpenCV sample style !! There is a sample code for color-histogram in OpenCV-Python2 samples. Ifyou run the code, you can see the histogram shows the corresponding color also. Or simply it outputs a color codedhistogram. Its result is very good (although you need to add extra bunch of lines).In that code, the author created a color map in HSV. Then converted it into BGR. The resulting histogram image ismultiplied with this color map. He also uses some preprocessing steps to remove small isolated pixels, resulting in agood histogram.I leave it to the readers to run the code, analyze it and have your own hack arounds. Below is the output of that codefor the same image as above:
You can clearly see in the histogram what colors are present, blue is there, yellow is there, and some white due tochessboard is there. Nice !!!
It was proposed by Michael J. Swain , Dana H. Ballard in their paper Indexing via color histograms.What is it actually in simple words? It is used for image segmentation or finding objects of interest in an image. Insimple words, it creates an image of the same size (but single channel) as that of our input image, where each pixelcorresponds to the probability of that pixel belonging to our object. In more simpler worlds, the output image willhave our object of interest in more white compared to remaining part. Well, that is an intuitive explanation. (I cantmake it more simpler). Histogram Backprojection is used with camshift algorithm etc.
How do we do it ? We create a histogram of an image containing our object of interest (in our case, the ground, leavingplayer and other things). The object should fill the image as far as possible for better results. And a color histogramis preferred over grayscale histogram, because color of the object is more better way to define the object than itsgrayscale intensity. We then back-project this histogram over our test image where we need to find the object, ie inother words, we calculate the probability of every pixel belonging to the ground and show it. The resulting output onproper thresholding gives us the ground alone.
Algorithm in Numpy
1. First we need to calculate the color histogram of both the object we need to find (let it be M) and the image wherewe are going to search (let it be I).import cv2import numpy as npfrom matplotlib import pyplot as plt
# Find the histograms using calcHist. Can be done with np.histogram2d alsoM = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )I = cv2.calcHist([hsvt],[0, 1], None, [180, 256], [0, 180, 0, 256] )
2. Find the ratio = . Then backproject R, ie use R as palette and create a new image with every pixel as itscorresponding probability of being target. ie B(x,y) = R[h(x,y),s(x,y)] where h is hue and s is saturationof the pixel at (x,y). After that apply the condition (, ) = [(, ), 1].h,s,v = cv2.split(hsvt)B = R[h.ravel(),s.ravel()]B = np.minimum(B,1)B = B.reshape(hsvt.shape[:2])
3. Now apply a convolution with a circular disc, = * ,)
4. Now the location of maximum intensity gives us the location of object. If we are expecting a region in the image,thresholding for a suitable value gives a nice result.ret,thresh = cv2.threshold(B,50,255,0)
Thats it !!we convolve the image with a disc kernel and apply threshold. Below is my code and output :import cv2import numpy as np
roi = cv2.imread('rose_red.png')hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)
target = cv2.imread('rose.png')hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)
res = np.vstack((target,thresh,res))cv2.imwrite('res.jpg',res)
Below is one example I worked with. I used the region inside blue rectangle as sample object and I wanted to extractthe full ground.
1. Indexing via color histograms, Swain, Michael J. , Third international conference on computer vision,1990.
Fourier Transform
Fourier Transform
Fourier Transform is used to analyze the frequency characteristics of various filters. For images, 2D Discrete FourierTransform (DFT) is used to find the frequency domain. A fast algorithm called Fast Fourier Transform (FFT) isused for calculation of DFT. Details about these can be found in any image processing or signal processing textbooks.Please see Additional Resources section.For a sinusoidal signal, () = sin(2 ), we can say is the frequency of signal, and if its frequency domainis taken, we can see a spike at . If signal is sampled to form a discrete signal, we get the same frequency domain,but is periodic in the range [, ] or [0, 2] (or [0, ] for N-point DFT). You can consider an image as a signalwhich is sampled in two directions. So taking fourier transform in both X and Y directions gives you the frequencyrepresentation of image.More intuitively, for the sinusoidal signal, if the amplitude varies so fast in short time, you can say it is a highfrequency signal. If it varies slowly, it is a low frequency signal. You can extend the same idea to images. Where doesthe amplitude varies drastically in images ? At the edge points, or noises. So we can say, edges and noises are highfrequency contents in an image. If there is no much changes in amplitude, it is a low frequency component. ( Somelinksgrto bring it to center, you need to shift the result by 2 in both the directions. This is simply done by the function,np.fft.fftshift(). (It is more easier to analyze). Once you found the frequency transform, you can find the magnitudespectrum.import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)f = np.fft.fft2(img)fshift = np.fft.fftshift(f)magnitude_spectrum = 20*np.log(np.abs(fshift))
See, You can see more whiter region at the center showing low frequency content is more.So you found the frequency transform Now you can do some operations in frequency domain, like high pass filteringand reconstruct the image, ie find inverse DFT. For that you simply remove the low frequencies by masking with arectangular window of size 60x60. Then apply the inverse shift using np.fft.ifftshift() so that DC component againcome at the top-left corner. Then find inverse FFT using np.ifft2() function. The result, again, will be a complexnumber. You can take its absolute value.rows, cols = img.shapecrow,ccol = rows/2 , cols/2fshift[crow-30:crow+30, ccol-30:ccol+30] = 0f_ishift = np.fft.ifftshift(fshift)img_back = np.fft.ifft2(f_ishift)img_back = np.abs(img_back)
The result shows High Pass Filtering is an edge detection operation. This is what we have seen in Image Gradientschapter. This also shows that most of the image data is present in the Low frequency region of the spectrum. Anywaywe have seen how to find DFT, IDFT etc in Numpy. Now lets see how to do it in OpenCV.If you closely watch the result, especially the last image in JET color, you can see some artifacts (One instance Ihave marked in red arrow). It shows some ripple like structures there, and it is called ringing effects. It is caused bythe rectangular window we used for masking. This mask is converted to sinc shape which causes this problem. Sorectangular windows is not used for filtering. Better option is Gaussian Windows.
OpenCV provides the functions cv2.dft() and cv2.idft() for this. It returns the same result as previous, but with twochannels. First channel will have the real part of the result and second channel will have the imaginary part of theresult. The input image should be converted to np.float32 first. We will see how to do it.import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)
magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
Note: You can also use cv2.cartToPolar() which returns both magnitude and phase in a single shot
So, now we have to do inverse DFT. In previous session, we created a HPF, this time we will see how to remove highfrequency contents in the image, ie we apply LPF to image. It actually blurs the image. For this, we create a mask firstwith high value (1) at low frequencies, ie we pass the LF content, and 0 at HF region.rows, cols = img.shapecrow,ccol = rows/2 , cols/2
mask = np.zeros((rows,cols,2),np.uint8)mask[crow-30:crow+30, ccol-30:ccol+30] = 1
Note: As usual, OpenCV functions cv2.dft() and cv2.idft() are faster than Numpy counterparts. But Numpy functionsare more user-friendly. For more details about performance issues, see below section.
Performance of DFT calculation is better for some array size. It is fastest when array size is power of two. Thearrays whose size is a product of 2s, 3s, and 5s are also processed quite efficiently. So if you are worried about theperformance of your code, you can modify the size of the array to any optimal size (by padding zeros) before findingDFT. For OpenCV, you have to manually pad zeros. But for Numpy, you specify the new size of FFT calculation, andit will automatically pad zeros for you.So how do we find this optimal size ? OpenCV provides a function, cv2.getOptimalDFTSize() for this. It is applicableto both cv2.dft() and np.fft.fft2(). Lets check their performance using IPython magic command %timeit.In [16]: img = cv2.imread('messi5.jpg',0)In [17]: rows,cols = img.shapeIn [18]: print rows,cols342 548
See, the size (342,548) is modified to (360, 576). Now lets pad it with zeros (for OpenCV) and find their
DFT calculation performance. You can do it by creating a new big zero array and copy the data to it, or usecv2.copyMakeBorder().nimg = np.zeros((nrows,ncols))nimg[:rows,:cols] = img
OR:right = ncols - colsbottom = nrows - rowsbordertype = cv2.BORDER_CONSTANT #just to avoid line breakup in PDF filenimg = cv2.copyMakeBorder(img,0,bottom,0,right,bordertype, value = 0)
It shows a 4x speedup. Now we will try the same with OpenCV functions.In [24]: %timeit dft1= cv2.dft(np.float32(img),flags=cv2.DFT_COMPLEX_OUTPUT)100 loops, best of 3: 13.5 ms per loopIn [27]: %timeit dft2= cv2.dft(np.float32(nimg),flags=cv2.DFT_COMPLEX_OUTPUT)100 loops, best of 3: 3.11 ms per loop
It also shows a 4x speed-up. You can also see that OpenCV functions are around 3x faster than Numpy functions. Thiscanfor some higher size of FFT. Analyze it:import cv2import numpy as npfrom matplotlib import pyplot as plt
[0, 0, 0], [1, 2, 1]])# laplacianlaplacian=np.array([[0, 1, 0], [1,-4, 1], [0, 1, 0]])
for i in xrange(6): plt.subplot(2,3,i+1),plt.imshow(mag_spectrum[i],cmap = 'gray') plt.title(filter_name[i]), plt.xticks([]), plt.yticks([])
From image, you can see what frequency region each kernel blocks, and what region it passes. From that information,we can say why each kernel is a HPF or a LPF
Template Matching is a method for searching and finding the location of a template image in a larger image. OpenCVcomes with a function cv2.matchTemplate() for this purpose. It simply slides the template image over the inputimage (as in 2D convolution) and compares the template and patch of input image under the template image. Severalcomparisonit as the top-left corner of rectangle and take (w,h) as width and height of the rectangle. That rectangle is your regionof template.
Note: If you are using cv2.TM_SQDIFF as comparison method, minimum value gives the best match.
Here, as an example, we will search for Messis face in his photo. So I created a template as below:
We will try all the comparison methods so that we can see how their results look like:import cv2import numpy as npfrom matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)img2 = img.copy()template = cv2.imread('template.jpg',0)w, h = template.shape[::-1]
plt.subplot(121),plt.imshow(res,cmap = 'gray') plt.title('Matching Result'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(img,cmap = 'gray') plt.title('Detected Point'), plt.xticks([]), plt.yticks([]) plt.suptitle(meth)
plt.show()
cv2.TM_CCOEFF_NORMED
cv2.TM_CCORR
cv2.TM_CCORR_NORMED
cv2.TM_SQDIFF
cv2.TM_SQDIFF_NORMED
You can see that the result using cv2.TM_CCORR is not good as we expected.
In the previous section, we searched image for Messis face, which occurs only once in the image. Suppose you aresearching for an object which has multiple occurances, cv2.minMaxLoc() wont give you all the locations. In thatcase, we will use thresholding. So in this example, we will use a screenshot of the famous game Mario and we willfind the coins in it.import cv2import numpy as npfrom matplotlib import pyplot as plt
img_rgb = cv2.imread('mario.png')img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)template = cv2.imread('mario_coin.png',0)w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)threshold = 0.8
cv2.imwrite('res.png',img_rgb)
In this chapter, We will understand the concept of Hough Tranform. We will see how to use it detect lines in an image. We will see following functions: cv2.HoughLines(), cv2.HoughLinesP()
Hough Transform is a popular technique to detect any shape, if you can represent that shape in mathematical form. Itcan detect the shape even if it is broken or distorted a little bit. We will see how it works for a line.A line can be represented as = + or in parametric form, as = cos + sin where is the perpendiculardistance from origin to the line, and is the angle formed by this perpendicular line and horizontal axis measured incounter-clockwise ( That direction varies on how you represent the coordinate system. This representation is used inOpenCV). Check below image:
So if line is passing below the origin, it will have a positive rho and angle less than 180. If it is going above the origin,instead of taking angle greater than 180, angle is taken less than 180, and rho is taken negative. Any vertical line willhave 0 degree and horizontal lines will have 90 degree.Now lets see how Hough Transform works for lines. Any line can be represented in these two terms, (, ). So first itcreates a 2D array or accumulator (to hold values of two parameters) and it is set to 0 initially. Let rows denote the and columns denote the . Size of array depends on the accuracy you need. Suppose you want the accuracy of anglesto be 1 degree, you need 180 columns. For , the maximum distance possible is the diagonal length of the image. Sotaking one pixel accuracy, number of rows can be diagonal length of the image.Consider a 100x100 image with a horizontal line at the middle. Take the first point of the line. You know its (x,y)values. Now in the line equation, put the values = 0, 1, 2, ...., 180 and check the you get. For every (, ) pair, youincrement value by one in our accumulator in its corresponding (, ) cells. So now in accumulator, the cell (50,90) =1 along with some other cells.Now take the second point on the line. Do the same as above. Increment the the values in the cells corresponding to(, ) you got. This time, the cell (50,90) = 2. What you actually do is voting the (, ) values. You continue thisprocess for every point on the line. At each point, the cell (50,90) will be incremented or voted up, while other cellsmay or may not be voted up. This way, at the end, the cell (50,90) will have maximum votes. So if you search theaccumulator for maximum votes, you get the value (50,90) which says, there is a line in this image at distance 50 fromorigin and at angle 90 degrees. It is well shown in below animation (Image Courtesy: Amos Storkey )
This is how hough transform for lines works. It is simple, and may be you can implement it using Numpy on yourown. Below is an image which shows the accumulator. Bright spots at some locations denotes they are the parametersof possible lines in the image. (Image courtesy: Wikipedia )
Everything explained above is encapsulated in the OpenCV function, cv2.HoughLines(). It simply returns an arrayof (, ) values. is measured in pixels and is measured in radians. First parameter, Input image should be abinary image, so apply threshold or use canny edge detection before finding applying hough transform. Second andthird parameters are and accuracies respectively. Fourth argument is the threshold, which means minimum vote itshould get for it to be considered as a line. Remember, number of votes depend upon number of points on the line. Soit represents the minimum length of line that should be detected.import cv2import numpy as np
img = cv2.imread('dave.jpg')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)edges = cv2.Canny(gray,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,200(img,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imwrite('houghlines3.jpg',img)
In the hough transform, you can see that even for a line with two arguments, it takes a lot of computation. ProbabilisticHough Transform is an optimization of Hough Transform we saw. It doesnt take all the points into consideration,instead take only a random subset of points and that is sufficient for line detection. Just we have to decrease thethreshold. See below image which compare Hough Transform and Probabilistic Hough Transform in hough space.(Image Courtesy : Franck Bettingers home page
OpenCV implementation is based on Robust Detection of Lines Using the Progressive Probabilistic Hough Transform by Matas,
minLineLength - Minimum length of line. Line segments shorter than this are rejected. maxLineGap - Maximum allowed gap between line segments to treat them as single line.Best thing is that, it directly returns the two endpoints of lines. In previous case, you got only the parameters of lines,and you had to find all the points. Here, everything is direct and simple.
import cv2import numpy as np
img = cv2.imread('dave.jpg')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)edges = cv2.Canny(gray,50,150,apertureSize = 3)minLineLength = 100maxLineGap = 10lines =write('houghlines5.jpg',img)
In this chapter, We will learn to use Hough Transform to find circles in an image. We will see these functions: cv2.HoughCircles()
img = cv2.imread('opencv_logo.png'()
In this chapter, We will learn to use marker-based image segmentation using watershed algorithm We will see: cv2.watershed()
Any grayscale image can be viewed as a topographic surface where high intensity denotes peaks and hills while lowintensity denotes valleys. You start filling every isolated valleys (local minima) with different colored water (labels).As the water rises, depending on the peaks (gradients) nearby, water from different valleys, obviously with differentcolors will start to merge. To avoid that, you build barriers in the locations where water merges. You continue the workof filling water and building barriers until all the peaks are under water. Then the barriers you created gives you thesegmentation result. This is the philosophy behind the watershed. You can visit the CMM webpage on watershed tounderstand it with the help of some animations.But this approach gives you oversegmented result due to noise or any other irregularities in the image. So OpenCVimplemented a marker-based watershed algorithm where you specify which are all valley points are to be merged andwhich are not. It is an interactive image segmentation. What we do is to give different labels for our object we know.Label the region which we are sure of being the foreground or object with one color (or intensity), label the regionwhich we are sure of being background or non-object with another color and finally the region which we are not sureof anything, label it with 0. That is our marker. Then apply watershed algorithm. Then our marker will be updatedwith the labels we gave, and the boundaries of objects will have a value of -1.
Below we will see an example on how to use the Distance Transform along with watershed to segment mutuallytouching objects.Consider the coins image below, the coins are touching each other. Even if you threshold it, it will be touching eachother.
We start with finding an approximate estimate of the coins. For that, we can use the Otsus binarization.import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('coins.png')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
Now we need to remove any small white noises in the image. For that we can use morphological opening. To removeany small holes in the object, we can use morphological closing. So, now we know for sure that region near to centerof objects are foreground and region much away from the object are background. Only region we are not sure is theboundary region of coins.So we need to extract the area which we are sure they are coins. Erosion removes the boundary pixels. So whateverremaining, we can be sure it is coin. That would work if objects were not touching each other. But since they aretouching each other, another good option would be to find the distance transform and apply a proper threshold. Nextwe need to find the area which we are sure they are not coins. For that, we dilate the result. Dilation increases objectboundary to background. This way, we can make sure whatever region in background in result is really a background,since boundary region is removed. See the image below.
The remaining regions are those which we dont have any idea, whether it is coins or background. Watershed algorithmshould find it. These areas are normally around the boundaries of coins where foreground and background meet (Oreven two different coins meet). We call it border. It can be obtained from subtracting sure_fg area from sure_bg area.# noise removalkernel = np.ones((3,3),np.uint8)opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
See the result. In the thresholded image, we get some regions of coins which we are sure of coins and they are detachednow. (In some cases, you may be interested in only foreground segmentation, not in separating the mutually touchingobjects. In that case, you need not use distance transform, just erosion is sufficient. Erosion is just another method toextract sure foreground area, thats all.)
Now we know for sure which are region of coins, which are background and all. So we create marker (it is an array ofsame size as that of original image, but with int32 datatype) and label the regions inside it. The regions we know forsure (whether foreground or background) are labelled with any positive integers, but different integers, and the areawe dont know for sure are just left as zero. For this we use cv2.connectedComponents(). It labels background of theimage with 0, then other objects are labelled with integers starting from 1.But we know that if background is marked with 0, watershed will consider it as unknown area. So we want to mark itwith different integer. Instead, we will mark unknown region, defined by unknown, with 0.# Marker labellingret, markers = cv2.connectedComponents(sure_fg)
See the result shown in JET colormap. The dark blue region shows unknown region. Sure coins are colored withdifferent values. Remaining area which are sure background are shown in lighter blue compared to unknown region.
Now our marker is ready. It is time for final step, apply watershed. Then marker image will be modified. The boundaryregion will be marked with -1.markers = cv2.watershed(img,markers)img[markers == -1] = [255,0,0]
See the result below. For some coins, the region where they touch are segmented properly and for some, they are not.
1. OpenCV samples has an interactive sample on watershed segmentation, watershed.py. Run it, Enjoy it, then learn it.
In this chapter We will see GrabCut algorithm to extract foreground in images We will create an interactive application for this.
GrabCut algorithm was designed by Carsten Rother, Vladimir Kolmogorov & Andrew Blake from Microsoft ResearchCambridge, UK. in their paper, GrabCut: interactive foreground extraction using iterated graph cuts . An algorithmwas needed for foreground extraction with minimal user interaction, and the result was GrabCut.How it works from user point of view ? Initially user draws a rectangle around the foreground region (foregroundregion shoule be completely inside the rectangle). Then algorithm segments it iteratively to get the best result. Done.But in some cases, the segmentation wont be fine, like, it may have marked some foreground region as background
and vice versa. In that case, user need to do fine touch-ups. Just give some strokes on the images where some faultyresults are there. Strokes basically says Hey, this region should be foreground, you marked it background, correct itin next iteration or its opposite for background. Then in the next iteration, you get better results.See the image below. First player and football is enclosed in a blue rectangle. Then some final touchups with whitestrokes (denoting foreground) and black strokes (denoting background) is made. And we get a nice result.
Demo
Now we go for grabcut algorithm with OpenCV. OpenCV has the function, cv2.grabCut() for this. We will see itsarguments first: img - Input image mask - It is a mask image where we specify which areas are background, foreground or probable back- ground de- cides whether we are drawing rectangle or final touchup strokes.First lets see with rectangular mode. We load the image, create a similar mask image. We create fgdModel andbgdModel. We give the rectangle parameters. Its all straight-forward. Let the algorithm run for 5 iterations. Modeshould be cvput to 1(ie foreground pixels). Now our final mask is ready. Just multiply it with input image to get the segmentedimage.import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg')mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)fgdModel = np.zeros((1,65),np.float64)
rect = (50,50,450,290()
Oops, Messis hair is gone. Who likes Messi without his hair? We need to bring it back. So we will give there a finetouchup with 1-pixel (sure foreground). At the same time, Some part of ground has come to picture which we dontwant, and also some logo. We need to remove them. There we give some 0-pixel touchup (sure background). So wemodify our resulting mask in previous case as we told now.What I actually did is that, I opened input image in paint application and added another layer to the image. Usingbrush tool in the paint, I marked missed foreground (hair, shoes, ball etc) with white and unwanted background (likelogo, ground etc) with black on this new layer. Then filled remaining background with gray. Then loaded that maskimage in OpenCV, edited original mask image we got with corresponding values in newly added mask image. Checkthe code below:
mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')img = img*mask[:,:,np.newaxis]plt.imshow(img),plt.colorbar(),plt.show()
So thats it. Here instead of initializing in rect mode, you can directly go into mask mode. Just mark the rectanglearea in mask image with 2-pixel or 3-pixel (probable background/foreground). Then mark our sure_foreground with1-pixel as we did in second example. Then directly apply the grabCut function with mask mode.
1. OpenCV samples contain a sample grabcut.py which is an interactive tool using grabcut. Check it. Also watch this youtube video on how to use it. 2. Here, you can make this into a interactive sample with drawing rectangle and strokes with mouse, create trackbar to adjust stroke width etc.
Understanding Features
What are the main features in an image? How can finding those features be useful to us?
Harris corner detector is not good enough when scale of image changes. Lowe developed a breakthrough method to find scale-invariant features and it is called SIFT
SIFT is really good, but not fast enough, so people came up with a speeded- up version called SURF.
All the above feature detection methods are good in some way. But they are not fast enough to work in real-time applications like SLAM. There comes the FAST algorithm, which is really FAST.
SIFT uses a feature descriptor with 128 floating point numbers. Consider thousands of such features. It takes lots of memory and more time for matching. We can compress it to make it faster. But still we have to cal- culate it first. There comes BRIEF which gives the shortcut to find binary descriptors with less memory, faster matching, still higher recognition rate..
Feature Matching
Now we know about feature matching. Lets mix it up with calib3d module to find objects in a complex image.
In this chapter, we will just try to understand what are features, why are they important, why corners are important etc.
Explanation
Most of you will have played the jigsaw puzzle games. You get a lot of small pieces of a images, where you needto assemble them correctly to form a big real image. The question is, how you do it? What about the projectingthe same theory to a computer program so that computer can play jigsaw puzzles? If the computer can play jigsawpuzzles, why cant we give a lot of real-life images of a good natural scenery to computer and tell it to stitch all thoseimages to a big single image? If the computer can stitch several natural images to one, what about giving a lot ofpictures of a building or any structure and tell computer to create a 3D model out of it?Well, the questions and imaginations continue. But it all depends on the most basic question? How do you play jigsawpuzzles? How do you arrange lots of scrambled image pieces into a big single image? How can you stitch a lot ofnaturalimages, you can point out one. That is why, even small children can simply play these games. We search for thesefeatures in an image, we find them, we find the same features in other images, we align them. Thats it. (In jigsawpuzzle, we look more into continuity of different images). All these abilities are present in us inherently.So our one basic question expands to more in number, but becomes more specific. What are these features?. (Theanswer should be understandable to a computer also.)Well, it is difficult to say how humans find these features. It is already programmed in our brain. But if we lookdeep into some pictures and search for different patterns, we will find something interesting. For example, take belowimage:
Image is very simple. At the top of image, six small image patches are given. Question for you is to find the exactlocationlocation is still difficult. It is because, along the edge, it is same everywhere. Normal to the edge, it is different. Soedge is much more better feature compared to flat area, but not good enough (It is good in jigsaw puzzle for comparingcontinuity of edges).Finally, E and F are some corners of the building. And they can be easily found out. Because at corners, whereveryou move this patch, it will look different. So they can be considered as a good feature. So now we move into moresimpler (and widely used image) for better understanding.
Just like above, blue patch is flat area and difficult to find and track. Wherever you move the blue patch, it looks thesame. For black patch, it is an edge. If you move it in vertical direction (i.e. along the gradient) it changes. Put alongthe edge (parallel to edge), it looks the same. And for red patch, it is a corner. Wherever you move the patch, it looksdifferent, means it is unique. So basically, corners are considered to be good features in an image. (Not just corners,in some cases blobs are considered good features).So now we answered our question, what are these features?. But next question arises. How do we find them? Orhow do we find the corners?. That also we answered in an intuitive way, i.e., look for the regions in images which havemaximum variation when moved (by a small amount) in all regions around it. This would be projected into computerlanguage in coming chapters. So finding these image features is called Feature Detection.So we found the features in image (Assume you did it). Once you found it, you should find the same in the otherimages. What we do? We take a region around the feature, we explain it in our own words, like upper part is blue sky,lower part is building region, on that building there are some glasses etc and you search for the same area in otherimages. Basically, you are describing the feature. Similar way, computer also should describe the region around thefeature so that it can find it in other images. So called description is called Feature Description. Once you have thefeatures and its description, you can find same features in all images and align them, stitch them or do whatever youwant.So in this module, we are looking to different algorithms in OpenCV to find features, describe them, match them etc.
In this chapter, We will understand the concepts behind Harris Corner Detection. We will see the functions: cv2.cornerHarris(), cv2.cornerSubPix()
In last chapter, we saw that corners are regions in the image with large variation in intensity in all the directions. Oneearly attempt to find these corners was done by Chris Harris & Mike Stephens in their paper A Combined Cornerand Edge Detector in 1988, so now it is called Harris Corner Detector. He took this simple idea to a mathematicalform. It basically finds the difference in intensity for a displacement of (, ) in all directions. This is expressed asbelow: (, ) = (, ) [( + , + ) (, )]2 , window function shifted intensity intensity booksycan contain a corner or not.
= ( ) (( ))2
where ( ) = 1 2 ( ) = 1 + 2 1 and 2 are the eigen values of MSo the values of these eigen values decide whether a region is corner, edge or flat. When || is small, which happens when 1 and 2 are small, the region is flat. When < 0, which happens when 1 >> 2 or vice versa, the region is edge. When is large, which happens when 1 and 2 are large and 1 2 , the region is a corner.It can be represented in a nice picture as follows:
So the result of Harris Corner Detection is a grayscale image with these scores. Thresholding for a suitable give youthe corners in the image. We will do it with a simple image.
OpenCV has the function cv2.cornerHarris() for this purpose. Its arguments are :import numpy as np
filename = 'chessboard.jpg'img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)dst = cv2.cornerHarris(gray,2,3,0.04)
cv2.imshow('dst',img)if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()
Sometimes, you may need to find the corners with maximum accuracy. OpenCV comes with a functioncv2.cornerSubPix() which further refines the corners detected with sub-pixel accuracy. Below is an example. Asusual, we need to find the harris corners first. Then we pass the centroids of these corners (There may be a bunch ofpixels at a corner, we take their centroid) to refine them. Harris corners are marked in red pixels and refined cornersare marked in green pixels. For this function, we have to define the criteria when to stop the iteration. We stop it aftera specified number of iteration or a certain accuracy is achieved, whichever occurs first. We also need to define thesize of neighbourhood it would search for corners.import cv2import numpy as np
filename = 'chessboard2.jpg'img = cv2.imread(filename)gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# find centroidsret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
cv2.imwrite('subpixel5.png',img)
Below is the result, where some important locations are shown in zoomed window to visualize:
In this chapter, We will learn about the another corner detector: Shi-Tomasi Corner Detector We will see the function: cv2.goodFeaturesToTrack()
In last chapter, we saw Harris Corner Detector. Later in 1994, J. Shi and C. Tomasi made a small modification to itin their paper Good Features to Track which shows better results compared to Harris Corner Detector. The scoringfunction in Harris Corner Detector was given by:
= 1 2 (1 + 2 )2
= (1 , 2 )
If it is a greater than a threshold value, it is considered as a corner. If we plot it in 1 2 space as we did in HarrisCorner Detector, we get an image as below:
From the figure, you can see that only when 1 and 2 are above a minimum value, , it is conidered as acornernumber of corners you want to find. Then you specify the quality level, which is a value between 0-1, which denotesthe minimum quality of corner below which everyone is rejected. Then we provide the minimum euclidean distancebetween corners detected.With all these informations, the function finds corners in the image. All corners below quality level are rejected. Thenit sorts the remaining corners based on quality in the descending order. Then function takes first strongest corner,throws away all the nearby corners in the range of minimum distance and returns N strongest corners.In below example, we will try to find 25 best corners:import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('simple.jpg')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray,25,0.01,10)corners = np.int0(corners)
for i in corners: x,y = i.ravel() cv2.circle(img,(x,y),3,255,-1)
plt.imshow(img),plt.show()
This function is more appropriate for tracking. We will see that when its time comes.
In this chapter, We will learn about the concepts of SIFT algorithm We will learn to find SIFT Keypoints and Descriptors.
In last couple of chapters, we saw some corner detectors like Harris etc. They are rotation-invariant, which means,even if the image is rotated, we can find the same corners. It is obvious because corners remain corners in rotatedimage also. But what about scaling? A corner may not be a corner if the image is scaled. For example, check a simpleimage below. A corner in a small image within a small window is flat when it is zoomed in the same window. SoHarris corner is not scale invariant.
So, in 2004, D.Lowe, University of British Columbia, came up with a new algorithm, Scale Invariant Feature Trans-form (SIFT) in his paper, Distinctive Image Features from Scale-Invariant Keypoints, which extract keypoints andcompute its descriptors. (This paper is easy to understand and considered to be best material available on SIFT. Sothis explanation is just a short summary of this paper).There are mainly four steps involved in SIFT algorithm. We will see them one-by-one.
From the image above, it is obvious that we cant use the same window to detect keypoints with different scale. Itis OK with small corner. But to detect larger corners we need larger windows. For this, scale-space filtering is used.In it, Laplacian of Gaussian is found for the image with various values. LoG acts as a blob detector which detectsblobs in various sizes due to change in . In short, acts as a scaling parameter. For eg, in the above image, gaussiankernel with low gives high value for small corner while guassian kernel with high fits well for larger corner. So,we can find the local maxima across the scale and space which gives us a list of (, , ) values which means there isacomparedempirical data which can be summarized as, number of octaves= 4, number of scale levels = 5, initial = 1.6, = 2 etc as optimal values.
2. Keypoint Localization
Once potential keypoints locations are found, they have to be refined to get more accurate results. They used Taylorseries expansion of scale space to get more accurate location of extrema, and if the intensity at this extrema is less thana threshold value (0.03 as per the paper), it is rejected. This threshold is called contrastThreshold in OpenCVDoG has higher response for edges, so edges also need to be removed. For this, a concept similar to Harris cornerdetector is used. They used a 2x2 Hessian matrix (H) to compute the pricipal curvature. We know from Harris cornerdetector that for edges, one eigen value is larger than the other. So here they used a simple function,If this ratio is greater than a threshold, called edgeThreshold in OpenCV, that keypoint is discarded. It is given as 10in paper.So it eliminates any low-contrast keypoints and edge keypoints and what remains is strong interest points.
3. Orientation Assignment
Now an orientation is assigned to each keypoint to achieve invariance to image rotation. A neigbourhood is takenaround the keypoint location depending on the scale, and the gradient magnitude and direction is calculated in thatregion. An orientation histogram with 36 bins covering 360 degrees is created. (It is weighted by gradient magnitudeand gaussian-weighted circular window with equal to 1.5 times the scale of keypoint. The highest peak in thehistogram is taken and any peak above 80% of it is also considered to calculate the orientation. It creates keypointswith same location and scale, but different directions. It contribute to stability of matching.
4. Keypoint Descriptor
Now keypoint descriptor is created. A 16x16 neighbourhood around the keypoint is taken. It is devided into 16sub-blocks of 4x4 size. For each sub-block, 8 bin orientation histogram is created. So a total of 128 bin values areavailable. It is represented as a vector to form keypoint descriptor. In addition to this, several measures are taken toachieve robustness against illumination changes, rotation etc.
5. Keypoint Matching
Keypoints between two images are matched by identifying their nearest neighbours. But in some cases, the secondclosest-match may be very near to the first. It may happen due to noise or some other reasons. In that case, ratio ofclosest-distance to second-closest distance is taken. If it is greater than 0.8, they are rejected. It eliminaters around90% of false matches while discards only 5% correct matches, as per the paper.So this is a summary of SIFT algorithm. For more details and understanding, reading the original paper is highlyrecommended. Remember one thing, this algorithm is patented. So this algorithm is included in Non-free module inOpenCV.
SIFT in OpenCV
So now lets see SIFT functionalities available in OpenCV. Lets start with keypoint detection and draw them. First wehave to construct a SIFT object. We can pass different parameters to it which are optional and they are well explainedin docs.import cv2importimage. Each keypoint is a special structure which has many attributes like its (x,y) coordinates, size of the meaningfulneighbourhood, angle which specifies its orientation, response that specifies strength of keypoints etc.OpenCV also provides cv2.drawKeyPoints() function which draws the small circles on the locations of keypoints. Ifyou pass a flag, cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS to it, it will draw a circle with sizeof keypoint and it will even show its orientation. See below example.img=cv2.drawKeypoints(gray,kp,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)cv2.imwrite('sift_keypoints.jpg',img)
sift = cv2.SIFT()kp, des = sift.detectAndCompute(gray,None)
Here kp will be a list of keypoints and des is a numpy array of shape _ _ 128.So we got keypoints, descriptors etc. Now we want to see how to match keypoints in different images. That we willlearn in coming chapters.
In this chapter, We will see the basics of SURF We will see SURF functionalities in OpenCV
In last chapter, we saw SIFT for keypoint detection and description. But it was comparatively slow and people neededmore speeded-up version. In 2006, three people, Bay, H., Tuytelaars, T. and Van Gool, L, published another paper,SURF: Speeded Up Robust Features which introduced a new algorithm called SURF. As name suggests, it is aspeeded-up version of SIFT.In SIFT, Lowe approximated Laplacian of Gaussian with Difference of Gaussian for finding scale-space. SURF goesa little further and approximates LoG with Box Filter. Below image shows a demonstration of such an approximation.One big advantage of this approximation is that, convolution with box filter can be easily calculated with the help ofintegral images. And it can be done in parallel for different scales. Also the SURF rely on determinant of Hessianmatrix for both scale and location.
For orientation assignment, SURF uses wavelet responses in horizontal and vertical direction for a neighbourhood ofsize 6s. Adequate guassian weights are also applied to it. Then they are plotted in a space as given in below image.The dominant orientation is estimated by calculating the sum of all responses within a sliding orientation window ofangle 60 degrees. Interesting thing is that, wavelet response can be found out using integral images very easily at anyscale. For many applications, rotation invariance is not required, so no need of finding this orientation, which speedsup the process. SURF provides such a functionality called Upright-SURF or U-SURF. It improves speed and is robustupto 15 . OpenCV supports both, depending upon the flag, upright. If it is 0, orientation is calculated. If it is 1,orientation is not calculated and it is more faster.
For feature description, SURF uses Wavelet responses in horizontal and vertical direction (again, use of integral imagesmakes things easier). A neighbourhood of size 20sX20s is taken around the keypoint where s is the size. It is dividedinto 4x4 subregions. Foreach subregion, horizontal and vertical wavelet responses are taken and a vector is formed likethis, = ( , , | |, | |). This when represented as a vector gives SURF feature descriptor with total64 dimensions. Lower the dimension, higher the speed of computation and matching, but provide better distinctivenessof features.For more distinctiveness, SURF feature descriptor has an extended 128 dimension version. The sums of and | |are computed separately for < 0 and 0. Similarly, the sums of and | | are split up according to the signof , thereby doubling the number of features. It doesnt add much computation complexity. OpenCV supports bothby setting the value of flag extended with 0 and 1 for 64-dim and 128-dim respectively (default is 128-dim)Another important improvement is the use of sign of Laplacian (trace of Hessian Matrix) for underlying interest point.It adds no computation cost since it is already computed during detection. The sign of the Laplacian distinguishesbright blobs on dark backgrounds from the reverse situation. In the matching stage, we only compare features if theyhave the same type of contrast (as shown in image below). This minimal information allows for faster matching,without reducing the descriptors performance.
In short, SURF adds a lot of features to improve the speed in every step. Analysis shows it is 3 times faster than SIFTwhile performance is comparable to SIFT. SURF is good at handling images with blurring and rotation, but not goodat handling viewpoint change and illumination change.
SURF in OpenCV
OpenCV provides SURF functionalities just like SIFT. You initiate a SURF object with some optional conditions like64in Python terminal since it is just same as SIFT only.>>> img = cv2.imread('fly.png',0)
>>> len(kp) 699
1199 keypoints is too much to show in a picture. We reduce it to some 50 to draw it on an image. While matching, wemay need all those features, but not now. So we increase the Hessian Threshold.# Check present Hessian threshold>>> print surf.hessianThreshold400.0
>>> plt.imshow(img2),plt.show()
See the result below. You can see that SURF is more like a blob detector. It detects the white blobs on wings ofbutterfly. You can test it with other images.
See the results below. All the orientations are shown in same direction. It is more faster than previous. If you areworking on cases where orientation is not a problem (like panorama stitching) etc, this is more better.
Finally we check the descriptor size and change it to 128 if it is only 64-dim.# Find size of descriptor>>> print surf.descriptorSize()64
(47, 128)
In this chapter, We will understand the basics of FAST algorithm We will find corners using OpenCV functionalities for FAST algorithm.
We saw several feature detectors and many of them are really good. But when looking from a real-time applicationpoint of view, they are not fast enough. One best example would be SLAM (Simultaneous Localization and Mapping)mobile robot which have limited computational resources.As a solution to this, FAST (Features from Accelerated Segment Test) algorithm was proposed by Edward Rosten andTom Drummond in their paper Machine learning for high-speed corner detection in 2006 (Later revised it in 2010).A basic summary of the algorithm is presented below. Refer original paper for more details (All the images are takenfrom original paper).
1. Select a pixel in the image which is to be identified as an interest point or not. Let its intensity be . 2. Select appropriate threshold value . 3. Consider a circle of 16 pixels around the pixel under test. (See the image below)
4. Now the pixel is a corner if there exists a set of contiguous pixels in the circle (of 16 pixels) which are all brighter than + , or all darker than . (Shown as white dash lines in the above image). was chosen to be 12. 5. A high-speed test was proposed to exclude a large number of non-corners. This test examines only the four pixels at 1, 9, 5 and 13 (First 1 and 9 are tested if they are too brighter or darker. If so, then checks 5 and 13). If is a corner, then at least three of these must all be brighter than + or darker than . If neither of these is the case, then cannot be a corner. The full segment test criterion can then be applied to the passed candidates by examining all pixels in the circle. This detector in itself exhibits high performance, but there are several weaknesses: It does not reject as many candidates for n < 12. The choice of pixels is not optimal because its efficiency depends on ordering of the questions and distri- bution of corner appearances. Results of high-speed tests are thrown away. Multiple features are detected adjacent to one another.First 3 points are addressed with a machine learning approach. Last one is addressed using non-maximal suppression.
1. Select a set of images for training (preferably from the target application domain) 2. Run FAST algorithm in every images to find feature points. 3. For every feature point, store the 16 pixels around it as a vector. Do it for all the images to get feature vector . 4. Each pixel (say ) in these 16 pixels can have one of the following three states:
Non-maximal Suppression
Detecting multiple interest points in adjacent locations is another problem. It is solved by using Non-maximumSuppression.
1. Compute a score function, for all the detected feature points. is the sum of absolute difference between and 16 surrounding pixels values. 2. Consider two adjacent keypoints and compute their values. 3. Discard the one with lower value.
Summary
It is called as any other feature detector in OpenCV. If you want, you can specify the threshold, whether non-maximumsuppression.import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('simple.jpg',0)
cv2.imwrite('fast_true.png',img2)
# Disable nonmaxSuppressionfast.setBool('nonmaxSuppression',0)kp = fast.detect(img,None)
cv2.imwrite('fast_false.png',img3)
See the results. First image shows FAST with nonmaxSuppression and second one without nonmaxSuppression:
1. Edward Rosten and Tom Drummond, Machine learning for high speed corner detection in 9th European Conference on Computer Vision, vol. 1, 2006, pp. 430443. 2. Edward Rosten, Reid Porter, and Tom Drummond, Faster and better: a machine learning approach to corner detection in IEEE Trans. Pattern Analysis and Machine Intelligence, 2010, vol 32, pp. 105-119.
In this chapter We will see the basics of BRIEF algorithm
We know SIFT uses 128-dim vector for descriptors. Since it is using floating point numbers, it takes basically 512bytes. Similarly SURF also takes minimum of 256 bytes (for 64-dim). Creating such a vector for thousands offeatures takes a lot of memory which are not feasible for resouce-constraint applications especially for embeddedsystems. Larger the memory, longer the time it takes for matching.But all these dimensions may not be needed for actual matching. We can compress it using several methods likePCA, LDA etc. Even other methods like hashing using LSH (Locality Sensitive Hashing) is used to convert theseSIFT descriptors in floating point numbers to binary strings. These binary strings are used to match features usingHamming distance. This provides better speed-up because finding hamming distance is just applying XOR and bitcount, which are very fast in modern CPUs with SSE instructions. But here, we need to find the descriptors first, thenonly we can apply hashing, which doesnt solve our initial problem on memory.BRIEF comes into picture at this moment. It provides a shortcut to find the binary strings directly without findingdescriptors. It takes smoothened image patch and selects a set of (x,y) location pairs in an unique way (explained inpaper). Then some pixel intensity comparisons are done on these location pairs. For eg, let first location pairs be and. If () < (), then its result is 1, else it is 0. This is applied for all the location pairs to get a -dimensionalbitstring.
This can be 128, 256 or 512. OpenCV supports all of these, but by default, it would be 256 (OpenCV represents itin bytes. So the values will be 16, 32 and 64). So once you get this, you can use Hamming Distance to match thesedescriptors.One important point is that BRIEF is a feature descriptor, it doesnt provide any method to find the features. So youwill have to use any other feature detectors like SIFT, SURF etc. The paper recommends to use CenSurE which is afast detector and BRIEF works even slightly better for CenSurE points than for SURF points.In short, BRIEF is a faster method feature descriptor calculation and matching. It also provides high recognition rateunless there is large in-plane rotation.
BRIEF in OpenCV
Below code shows the computation of BRIEF descriptors with the help of CenSurE detector. (CenSurE detector iscalled STAR detector in OpenCV)import numpy as npimport cv2from matplotlib import pyplot as plt
print brief.getInt('bytes')print des.shape
The function brief.getInt(bytes) gives the size used in bytes. By default it is 32. Next one is matching,which will be done in another chapter.
1. Michael Calonder, Vincent Lepetit, Christoph Strecha, and Pascal Fua, BRIEF: Binary Robust Independent Elementary Features, 11th European Conference on Computer Vision (ECCV), Heraklion, Crete. LNCS Springer, September 2010. 2. LSH (Locality Sensitive Hasing) at wikipedia.
In this chapter, We will see the basics of ORB
As an OpenCV enthusiast, the most important thing about the ORB is that it came from OpenCV Labs. Thisalgorithmin computation cost, matching performance and mainly the patents. Yes, SIFT and SURF are patented and you aresupposed to pay them for its use. But ORB is not !!!ORB is basically a fusion of FAST keypoint detector and BRIEF descriptor with many modifications to enhance theperformance. First it use FAST to find keypoints, then apply Harris corner measure to find top N points among them.It also use pyramid to produce multiscale-features. But one problem is that, FAST doesnt compute the orientation.So what about rotation invariance? Authors came up with following modification.It computes the intensity weighted centroid of the patch with located corner at center. The direction of the vector fromthis corner point to centroid gives the orientation. To improve the rotation invariance, moments are computed with xand y which should be in a circular region of radius , where is the size of the patch.Now for descriptors, ORB use BRIEF descriptors. But we have already seen that BRIEF performs poorly with rotation.So what ORB does is to steer BRIEF according to the orientation of keypoints. For any feature set of binary testsat location ( , ), define a 2 matrix, which contains the coordinates of these pixels. Then using the orientationof patch, , its rotation matrix is found and rotates the to get steered(rotated) version .ORB discretize the angle to increments of 2/30 (12 degrees), and construct a lookup table of precomputed BRIEFpatterns. As long as the keypoint orientation is consistent across views, the correct set of points will be used tocompute its descriptor.BRIEF has an important property that each bit feature has a large variance and a mean near 0.5. But once it is orientedalong keypoint direction, it loses this property and become more distributed. High variance makes a feature morediscriminative, since it responds differentially to inputs. Another desirable property is to have the tests uncorrelated,since then each test will contribute to the result. To resolve all these, ORB runs a greedy search among all possiblebinary tests to find the ones that have both high variance and means close to 0.5, as well as being uncorrelated. Theresult is called rBRIEF.For descriptor matching, multi-probe LSH which improves on the traditional LSH, is used. The paper says ORB ismuch faster than SURF and SIFT and ORB descriptor works better than SURF. ORB is a good choice in low-powerdevices for panorama stitching etc.
ORB in OpenCV
As usual, we have to create an ORB object with the function, cv2.ORB() or using feature2d common interface. Ithas a number of optional parameters. Most useful ones are nFeatures which denotes maximum number of featuresto be retained (by default 500), scoreType which denotes whether Harris score or FAST score to rank the features(by default, Harris score) etc. Another parameter, WTA_K decides number of points that produce each element ofthe oriented BRIEF descriptor. By default it is two, ie selects two points at a time. In that case, for matching,NORM_HAMMING distance is used. If WTA_K is 3 or 4, which takes 3 or 4 points to produce BRIEF descriptor, thenmatching distance is defined by NORM_HAMMING2.Below is a simple code which shows the use of ORB.import numpy as npimport cv2from matplotlib import pyplot as plt
1. Ethan Rublee, Vincent Rabaud, Kurt Konolige, Gary R. Bradski: ORB: An efficient alternative to SIFT or SURF. ICCV 2011: 2564-2571.
In this chapter We will see how to match features in one image with others. We will use the Brute-Force matcher and FLANN Matcher in OpenCV
Brute-Force matcher is simple. It takes the descriptor of one feature in first set and is matched with all other featuresin second set using some distance calculation. And the closest one is returned.For BF matcher, first we have to create the BFMatcher object using cv2.BFMatcher(). It takes two optional params.First one is normType. It specifies the distance measurement to be used. By default, it is cv2.NORM_L2. It is goodfor SIFT, SURF etc (cv2.NORM_L1 is also there). For binary string based descriptors like ORB, BRIEF, BRISK etc,cv2.NORM_HAMMING should be used, which used Hamming distance as measurement. If ORB is using VTA_K ==3 or 4, cv2.NORM_HAMMING2 should be used.Second param is boolean variable, crossCheck which is false by default. If it is true, Matcher returns only thosematches with value (i,j) such that i-th descriptor in set A has j-th descriptor in set B as the best match and vice-versa.That is, the two features in both sets should match each other. It provides consistant result, and is a good alternative toratio test proposed by D.Lowe in SIFT paper.Once it is created, two important methods are BFMatcher.match() and BFMatcher.knnMatch(). First one returns thebest match. Second method returns k best matches where k is specified by the user. It may be useful when we need todo additional work on that.Like we used cv2.drawKeypoints() to draw keypoints, cv2.drawMatches() helps us to draw the matches. It stackstwo images horizontally and draw lines from first image to second image showing best matches. There is alsocv2.drawMatchesKnn which draws all the k best matches. If k=2, it will draw two match-lines for each keypoint. Sowe have to pass a mask if we want to selectively draw it.Lets see one example for each of SURF and ORB (Both use different distance measurements).
Here, we will see a simple example on how to match features between two images. In this case, I have a queryIm-age and a trainImage. We will try to find the queryImage in trainImage using feature matching. ( The images are/samples/c/box.png and /samples/c/box_in_scene.png)We are using SIFT descriptors to match features. So lets start with loading images, finding descriptors etc.import numpy as npimport cv2from matplotlib import pyplot as plt
Next we create a BFMatcher object with distance measurement cv2.NORM_HAMMING (since we are using ORB) andcrossCheck is switched on for better results. Then we use Matcher.match() method to get the best matches in twoimages. We sort them in ascending order of their distances so that best matches (with low distance) come to front.Then we draw only first 10 matches (Just for sake of visibility. You can increase it as you like)# create BFMatcher objectbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Match descriptors.matches = bf.match(des1,des2)
plt.imshow(img3),plt.show()
The result of matches = bf.match(des1,des2) line is a list of DMatch objects. This DMatch object hasfollowing attributes: DMatch.distance - Distance between descriptors. The lower, the better it is.
This time, we will use BFMatcher.knnMatch() to get k best matches. In this example, we will take k=2 so thatwe can apply ratio test explained by D.Lowe in his paper.import numpy as npimport cv2from matplotlib import pyplot as plt
FLANN stands for Fast Library for Approximate Nearest Neighbors. It contains a collection of algorithms optimizedfor fast nearest neighbor search in large datasets and for high dimensional features. It works more faster than BF-Matcher for large datasets. We will see the second example with FLANN based matcher.For FLANN based matcher, we need to pass two dictionaries which specifies the algorithm to be used, its relatedparameters etc. First one is IndexParams. For various algorithms, the information to be passed is explained in FLANNdocs. As a summary, for algorithms like SIFT, SURF etc. you can pass following:index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
While using ORB, you can pass the following. The commented values are recommended as per the docs, but it didntprovide required results in some cases. Other values worked fine.:index_params= dict(algorithm = FLANN_INDEX_LSH, table_number = 6, # 12 key_size = 12, # 20 multi_probe_level = 1) #2
Second dictionary is the SearchParams. It specifies the number of times the trees in the index should be recursivelytraversed. Higher values gives better precision, but also takes more time. If you want to change the value, passsearch_params = dict(checks=100).With these informations, we are good to go.import numpy as npimport cv2from matplotlib import pyplot as plt
# FLANN parametersFLANN_INDEX_KDTREE = 0index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)search_params = dict(checks=50) # or pass empty dictionary
flann = cv2.FlannBasedMatcher(index_params,search_params)
matches = flann.knnMatch(des1,des2,k=2)
img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,**draw_params)
plt.imshow(img3,),plt.show()
In this chapter, We will mix up the feature matching and findHomography from calib3d module to find known objects in a complex image.
Basics
So what we did in last session? We used a queryImage, found some feature points in it, we took another trainImage,found the features in that image too and we found the best matches among them. In short, we found locations of someparts of an object in another cluttered image. This information is sufficient to find the object exactly on the trainImage.For that, we can use a function from calib3d module, ie cv2.findHomography(). If we pass the set of points from boththe images, it will find the perpective transformation of that object. Then we can use cv2.perspectiveTransform() tofindcorrect estimation are called inliers and remaining are called outliers. cv2.findHomography() returns a mask whichspecifies the inlier and outlier points.So lets do it !!!
First, as usual, lets find SIFT features in images and apply the ratio test to find the best matches.import numpy as npimport cv2from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
FLANN_INDEX_KDTREE = 0index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)search_params = dict(checks = 50)find the perpective transformation. Once we get this 3x3 transformation matrix, we use it to transform the corners ofqueryImage to corresponding points in trainImage. Then we draw)
h,w = img1.shape pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2) dst = cv2.perspectiveTransform(pts,M)
else: print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT) matchesMask = None
Finally we()
See the result below. Object is marked in white color in cluttered image:
Optical Flow
Background Subtraction
In this chapter, We will learn about Meanshift and Camshift algorithms to find and track objects in videos.
Meanshift
The intuition behind the meanshift is simple. Consider you have a set of points. (It can be a pixel distribution likehistogram backprojection). You are given a small window ( may be a circle) and you have to move that window to thearea of maximum pixel density (or maximum number of points). It is illustrated in the simple image given below:
The initial window is shown in blue circle with the name C1. Its original center is marked in blue rectangle, namedC1_o. But if you find the centroid of the points inside that window, you will get the point C1_r (marked in smallblue circle) which is the real centroid of window. Surely they dont match. So move your window such that circleof the new window matches with previous centroid. Again find the new centroid. Most probably, it wont match. Somove it again, and continue the iterations such that center of window and its centroid falls on the same location (orwith a small desired error). So finally what you obtain is a window with maximum pixel distribution. It is markedwith green circle, named C2. As you can see in image, it has maximum number of points. The whole process isdemonstrated on a static image below:
So we normally pass the histogram backprojected image and initial target location. When the object moves, obviouslythe movement is reflected in histogram backprojected image. As a result, meanshift algorithm moves our window tothe new location with maximum density.
Meanshift in OpenCV
To use meanshift in OpenCV, first we need to setup the target, find its histogram so that we can backproject the targeton each frame for calculation of meanshift. We also need to provide initial location of window. For histogram, onlyHue is considered here. Also, to avoid false values due to low light, low light values are discarded using cv2.inRange()function.import numpy as npimport cv2
cap = cv2.VideoCapture('slow.flv')
while(1): ret ,frame = cap.read()
if ret == True: hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# Draw it on image x,y,w,h = track_window img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2) cv2.imshow('img2',img2)
else: break
cv2.destroyAllWindows()cap.release()
Camshift
Did you closely watch the last result? There is a problem. Our window always has the same size when car is fartheraway and it is very close to camera. That is not good. We need to adapt the window size with size and rotation ofthe target. Once again, the solution came from OpenCV Labs and it is called CAMshift (Continuously AdaptiveMeanshift) published by Gary Bradsky in his paper Computer Vision Face Tracking for Use in a Perceptual UserInterface in 1988. It applies meanshift first. Once meanshift converges, it updates the size of the window as, = 2 256 . It also 00
calculates the orientation of best fitting ellipse to it. Again it applies the meanshift with new scaled search windowand previous window location. The process is continued until required accuracy is met.
Camshift in OpenCV
It is almost same as meanshift, but it returns a rotated rectangle (that is our result) and box parameters (used to bepassed as search window in next iteration). See the code below:import numpy as npimport cv2
# Draw it on image pts = cv2.boxPoints(ret) pts = np.int0(pts) img2 = cv2.polylines(frame,[pts],True, 255,2) cv2.imshow('img2',img2)
else: break
1. French Wikipedia page on Camshift. (The two animations are taken from here) 2. Bradski, G.R., Real time face and object tracking as a component of a perceptual user interface, Applications of Computer Vision, 1998. WACV 98. Proceedings., Fourth IEEE Workshop on , vol., no., pp.214,219, 19-21 Oct 1998
1. OpenCV comes with a Python sample on interactive demo of camshift. Use it, hack it, understand it.
In this chapter, We will understand the concepts of optical flow and its estimation using Lucas-Kanade method. We will use functions like cv2.calcOpticalFlowPyrLK() to track feature points in a video.
Optical Flow
Optical flow is the pattern of apparent motion of image objects between two consecutive frames caused by the move-mement of object or camera. It is 2D vector field where each vector is a displacement vector showing the movementof points from first frame to second. Consider the image below (Image Courtesy: Wikipedia article on Optical Flow).
It shows a ball moving in 5 consecutive frames. The arrow shows its displacement vector. Optical flow has manyapplications in areas like : Structure from Motion Video Compression Video Stabilization ...Optical flow works on several assumptions: 1. The pixel intensities of an object do not change between consecutive frames.
(, , ) = ( + , + , + )
Then take taylor series approximation of right-hand side, remove common terms and divide by to get the followingequation:
+ + = 0
where: = ; = = ; = Above equation is called Optical Flow equation. In it, we can find and , they are image gradients. Similarly is the gradient along time. But (, ) is unknown. We cannot solve this one equation with two unknown variables. Soseveral methods are provided to solve this problem and one of them is Lucas-Kanade.
Lucas-Kanade method
We have seen an assumption before, that all the neighbouring pixels will have similar motion. Lucas-Kanade methodtakes a 3x3 patch around the point. So all the 9 points have the same motion. We can find ( , , ) for these 9points. So now our problem becomes solving 9 equations with two unknown variables which is over-determined. Abetter solution is obtained with least square fit method. Below is the final solution which is two equation-two unknownproblem and solve to get the solution. ]1 [ 2 [ ] [ ] = 2
( Check similarity of inverse matrix with Harris corner detector. It denotes that corners are better points to be tracked.)So from user point of view, idea is simple, we give some points to track, we receive the optical flow vectors of thosepoints. But again there are some problems. Until now, we were dealing with small motions. So it fails when thereis large motion. So again we go for pyramids. When we go up in the pyramid, small motions are removed and largemotions becomes small motions. So applying Lucas-Kanade there, we get optical flow along with the scale.
OpenCV provides all these in a single function, cv2.calcOpticalFlowPyrLK(). Here, we create a simple applicationwhich tracks some points in a video. To decide the points, we use cv2.goodFeaturesToTrack(). We take the firstframe, detect some Shi-Tomasi corner points in it, then we iteratively track those points using Lucas-Kanade opticalflow. For the function cv2.calcOpticalFlowPyrLK() we pass the previous frame, previous points and next frame.It returns next points along with some status numbers which has a value of 1 if next point is found, else zero. Weiteratively pass these next points as previous points in next step. See the code below:import numpy as npimport cv2
while(1): ret,frame = cap.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',img) k = cv2.waitKey(30) & 0xff if k == 27: break
(This code doesnt check how correct are the next keypoints. So even if any feature point disappears in image, thereis a chance that optical flow finds the next point which may look close to it. So actually for a robust tracking, cornerpoints should be detected in particular intervals. OpenCV samples comes up with such a sample which finds thefeature points at every 5 frames. It also run a backward-check of the optical flow points got to select only good ones.Check samples/python2/lk_track.py).
Lucas-Kanade method computes optical flow for a sparse feature set (in our example, corners detected using Shi-Tomasi algorithm). OpenCV provides another algorithm to find the dense optical flow. It computes the optical flowfor all the points in the frame. It is based on Gunner Farnebacks algorithm which is explained in Two-Frame MotionEstimation Based on Polynomial Expansion by Gunner Farneback in 2003.Below sample shows how to find the dense optical flow using above algorithm. We get a 2-channel array with opticalflow vectors, (, ). We find their magnitude and direction. We color code the result for better visualization. Directioncorresponds to Hue value of the image. Magnitude corresponds to Value plane. See the code below:import cv2import numpy as npcap = cv2.VideoCapture("vtest.avi")
while(1): ret, frame2 = cap.read() next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
cv2.imshow('frame2',rgb) k = cv2.waitKey(30) & 0xff if k == 27: break elif k == ord('s'): cv2.imwrite('opticalfb.png',frame2) cv2.imwrite('opticalhsv.png',rgb) prvs = next
OpenCV comes with a more advanced sample on dense optical flow, please seesamples/python2/opt_flow.py.
In this chapter, We will familiarize with the background subtraction methods available in OpenCV.
Background subtraction is a major preprocessing steps in many vision based applications. For example, consider thecases like visitor counter where a static camera takes the number of visitors entering or leaving the room, or a trafficcamera extracting information about the vehicles etc. In all these cases, first you need to extract the person or vehiclesalone. Technically, you need to extract the moving foreground from static background.If you have an image of background alone, like image of the room without visitors, image of the road without vehiclesetc, it is an easy job. Just subtract the new image from the background. You get the foreground objects alone. Butin most of the cases, you may not have such an image, so we need to extract the background from whatever imageswe have. It become more complicated when there is shadow of the vehicles. Since shadow is also moving, simplesubtraction will mark that also as foreground. It complicates things.Several algorithms were introduced for this purpose. OpenCV has implemented three such algorithms which is veryeasy to use. We will see them one-by-one.
BackgroundSubtractorMOG
fgbg = cv2.createBackgroundSubtractorMOG()
fgmask = fgbg.apply(frame)
cv2.imshow('frame',fgmask) k = cv2.waitKey(30) & 0xff if k == 27: break
BackgroundSubtractorMOG2
fgbg = cv2.createBackgroundSubtractorMOG2()
while(1): ret, frame = cap.read()
BackgroundSubtractorGMG
This algorithm combines statistical background image estimation and per-pixel Bayesian segmentation. It was in-troduced by Andrew B. Godbehere, Akihiro Matsukawa, Ken Goldberg in their paper Visual Tracking of HumanVisitors under Variable-Lighting Conditions for a Responsive Audio Art Installation in 2012. As per the paper, the
system ran a successful interactive audio art installation called Are We There Yet? from March 31 - July 31 2011 atthe Contemporary Jewish Museum in San Francisco, California.It uses first few (120 by default) frames for background modelling. It employs probabilistic foreground segmentationalgorithm that identifies possible foreground objects using Bayesian inference. The estimates are adaptive; newerobservations are more heavily weighted than old observations to accommodate variable illumination. Several morpho-logical filtering operations like closing and opening are done to remove unwanted noise. You will get a black windowduring first few frames.It would be better to apply morphological opening to the result to remove the noises.import numpy as npimport cv2
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))fgbg = cv2.createBackgroundSubtractorGMG()
fgmask = fgbg.apply(frame) fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
cv2.imshow('frame',fgmask) k = cv2.waitKey(30) & 0xff if k == 27: break
Results
Original FrameBelow image shows the 200th frame of a video
Result of BackgroundSubtractorMOG
Result of BackgroundSubtractorMOG2Gray color region shows shadow region.
Result of BackgroundSubtractorGMGNoise is removed with morphological opening.
Camera Calibration
Lets find how good is our camera. Is there any distortion in images taken with it? If so how to correct it?
Pose Estimation
This is a small section which will help you to create some cool 3D effects with calib module.
Epipolar Geometry
In this section, We will learn about distortions in camera, intrinsic and extrinsic parameters of camera etc. We will learn to find these parameters, undistort images etc.
Todays cheap pinhole cameras introduces a lot of distortion to images. Two major distortions are radial distortion andtangential distortion.Due to radial distortion, straight lines will appear curved. Its effect is more as we move away from the center of image.For example, one image is shown below, where two edges of a chess board are marked with red lines. But you cansee that border is not a straight line and doesnt match with the red line. All the expected straight lines are bulged out.Visit Distortion (optics) for more details.
Similarly, another distortion is the tangential distortion which occurs because image taking lense is not aligned per-fectly parallel to the imaging plane. So some areas in image may look nearer than expected. It is solved as below:
= + [21 + 2 (2 + 22 )] = + [1 (2 + 2 2 ) + 22 ]
In short, we need to find five parameters, known as distortion coefficients given by:
= (1 2 1 2 3 )
In addition to this, we need to find a few more information, like intrinsic and extrinsic parameters of a camera. Intrinsicparameters are specific to a camera. It includes information like focal length ( , ), optical centers ( , ) etc. It is
also called camera matrix. It depends on the camera only, so once calculated, it can be stored for future purposes. It isexpressed as a 3x3 matrix: 0 = 0 0 0 1
Extrinsic parameters corresponds to rotation and translation vectors which translates a coordinates of a 3D point to acoordinate system.For stereo applications, these distortions need to be corrected first. To find all these parameters, what we have to do isto provide some sample images of a well defined pattern (eg, chess board). We find some specific points in it ( squarecorners in chess board). We know its coordinates in real world space and we know its coordinates in image. Withthese data, some mathematical problem is solved in background to get the distortion coefficients. That is the summaryof the whole story. For better results, we need atleast 10 test patterns.
As mentioned above, we need atleast 10 test patterns for camera calibration. OpenCV comes with some images ofchess board (see samples/cpp/left01.jpg -- left14.jpg), so we will utilize it. For sake of understand-ing, consider just one image of a chess board. Important input datas needed for camera calibration is a set of 3Dreal world points and its corresponding 2D image points. 2D image points are OK which we can easily find from theimage. (These image points are locations where two black squares touch each other in chess boards)What about the 3D points from real world space? Those images are taken from a static camera and chess boards areplaced at different locations and orientations. So we need to know (, , ) values. But for simplicity, we can saychess board was kept stationary at XY plane, (so Z=0 always) and camera was moved accordingly. This considerationhelps us to find only X,Y values. Now for X,Y values, we can simply pass the points as (0,0), (1,0), (2,0), ... whichdenotes the location of points. In this case, the results we get will be in the scale of size of chess board square. But ifwe know the square size, (say 30 mm), and we can pass the values as (0,0),(30,0),(60,0),..., we get the results in mm.(In this case, we dont know square size since we didnt take those images, so we pass in terms of square size).3D points are called object points and 2D image points are called image points.
Setup
So to find pattern in chess board, we use the function, cv2.findChessboardCorners(). We also need to pass what kindof pattern we are looking, like 8x8 grid, 5x5 grid etc. In this example, we use 7x6 grid. (Normally a chess board has8x8 squares and 7x7 internal corners). It returns the corner points and retval which will be True if pattern is obtained.These corners will be placed in an order (from left-to-right, top-to-bottom)See also:This function may not be able to find the required pattern in all the images. So one good option is to write the codesuch that, it starts the camera and check each frame for required pattern. Once pattern is obtained, find the cornersand store it in a list. Also provides some interval before reading next frame so that we can adjust our chess board indifferent direction. Continue this process until required number of good patterns are obtained. Even in the exampleprovided here, we are not sure out of 14 images given, how many are good. So we read all the images and take thegood ones.See also:Instead of chess board, we can use some circular grid, but then use the function cv2.findCirclesGrid() to find thepattern. It is said that less number of images are enough when using circular grid.Once we find the corners, we can increase their accuracy using cv2.cornerSubPix(). We can also draw the patternusing cv2.drawChessboardCorners(). All these steps are included in below code:
import numpy as npimport cv2import glob
# termination criteriacriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Arrays to store object points and image points from all the images.objpoints = [] # 3d point in real world spaceimgpoints = [] # 2d points in image plane.
images = glob.glob('*.jpg')
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) imgpoints.append(corners2)
Calibration
So now we have our object points and image points we are ready to go for calibration. For that we use the function,cv2.calibrateCamera(). It returns the camera matrix, distortion coefficients, rotation and translation vectors etc.ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
Undistortion
We have got what we were trying. Now we can take an image and undistort it. OpenCV comes with two meth-ods, we will see both. But before that, we can refine the camera matrix based on a free scaling parameter usingcv2.getOptimalNewCameraMatrix(). If the scaling parameter alpha=0, it returns undistorted image with mini-mum)img = cv2.imread('left12.jpg')h, w = img.shape[:2]newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
1. Using cv2.undistort() This is the shortest path. Just call the function and use ROI obtained above to crop theresult.# undistortdst = cv2.undistort(img, mtx, dist, None, newcameramtx)
2. Using remapping This is curved path. First find a mapping function from distorted image to undistorted image.Then use the remap function.# undistortmapx,mapy = cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5)dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR)
Both the methods give the same result. See the result below:
You can see in the result that all the edges are straight.Now you can store the camera matrix and distortion coefficients using write functions in Numpy (np.savez, np.savetxtetc) for future uses.
Re-projection Error
Re-projection error gives a good estimation of just how exact is the found parameters. This should be as close to zero aspossible. Given the intrinsic, distortion, rotation and translation matrices, we first transform the object point to imagepoint using cv2.projectPoints(). Then we calculate the absolute norm between what we got with our transformationand the corner finding algorithm. To find the average error we calculate the arithmetical mean of the errors calculatefor all the calibration images.mean_error = 0for i in xrange(len(objpoints)): imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist) error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2) tot_error += error
In this section, We will learn to exploit calib3d module to create some 3D effects in images.
This is going to be a small section. During the last session on camera calibration, you have found the camera matrix,distortion coefficients etc. Given a pattern image, we can utilize the above information to calculate its pose, or howthe object is situated in space, like how it is rotated, how it is displaced etc. For a planar object, we can assume Z=0,such that, the problem now becomes how camera is placed in space to see our pattern image. So, if we know how theobject lies in the space, we can draw some 2D diagrams in it to simulate the 3D effect. Lets see how to do it.Our problem is, we want to draw our 3D coordinate axis (X, Y, Z axes) on our chessboards first corner. X axis inblue color, Y axis in green color and Z axis in red color. So in-effect, Z axis should feel like it is perpendicular to ourchessboard plane.First, lets load the camera matrix and distortion coefficients from the previous calibration result.import cv2import numpy as npimport glob
Now lets create a function, draw which takes the corners in the chessboard (obtained usingcv2.findChessboardCorners()) and axis points to draw a 3D axis.def draw(img, corners, imgpts): corner = tuple(corners[0].ravel()) img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5) img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5) img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5) return img
Then as in previous case, we create termination criteria, object points (3D points of corners in chessboard) and axispoints. Axis points are points in 3D space for drawing the axis. We draw axis of length 3 (units will be in terms ofchess square size since we calibrated based on that size). So our X axis is drawn from (0,0,0) to (3,0,0), so for Y axis.For Z axis, it is drawn from (0,0,0) to (0,0,-3). Negative denotes it is drawn towards the camera.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)objp = np.zeros((6*7,3), np.float32)objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
Now, as usual, we load each image. Search for 7x6 grid. If found, we refine it with subcorner pixels. Then to calculatethe rotation and translation, we use the function, cv2.solvePnPRansac(). Once we those transformation matrices,we use them to project our axis points to the image plane. In simple words, we find the points on image planecorresponding to each of (3,0,0),(0,3,0),(0,0,3) in 3D space. Once we get them, we draw lines from the first corner toeach of these points using our draw() function. Done !!!
if ret == True: corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
img = draw(img,corners2,imgpts) cv2.imshow('img',img) k = cv2.waitKey(0) & 0xff if k == 's': cv2.imwrite(fname[:6]+'.png', img)
See some results below. Notice that each axis is 3 squares long.:
Render a Cube
If you want to draw a cube, modify the draw() function and axis points as follows.Modified draw() function:def draw(img, corners, imgpts): imgpts = np.int32(imgpts).reshape(-1,2)
return img
If you are interested in graphics, augmented reality etc, you can use OpenGL to render more complicated figures.
In this section, We will learn about the basics of multiview geometry We will see what is epipole, epipolar lines, epipolar constraint etc.
Basic Concepts
When we take an image using pin-hole camera, we loose an important information, ie depth of the image. Or how faris each point in the image from the camera because it is a 3D-to-2D conversion. So it is an important question whetherwe can find the depth information using these cameras. And the answer is to use more than one camera. Our eyesworks in similar way where we use two cameras (two eyes) which is called stereo vision. So lets see what OpenCVprovides in this field.(Learning OpenCV by Gary Bradsky has a lot of information in this field.)
Before going to depth images, lets first understand some basic concepts in multiview geometry. In this section wewill deal with epipolar geometry. See the image below which shows a basic setup with two cameras taking the imageof same scene.
If we are using only the left camera, we cant find the 3D point corresponding to the point in image because everypoint on the line projects to the same point on the image plane. But consider the right image also. Now differentpoints on the line projects to different points ( ) in right plane. So with these two images, we can triangulate thecorrect 3D point. This is the whole idea.The projection of the different points on form a line on right plane (line ). We call it epiline corresponding tothe point . It means, to find the point on the right image, search along this epiline. It should be somewhere on thisline (Think of it this way, to find the matching point in other image, you need not search the whole image, just searchalong the epiline. So it provides better performance and accuracy). This is called Epipolar Constraint. Similarly allpoints will have its corresponding epilines in the other image. The plane is called Epipolar Plane. and are the camera centers. From the setup given above, you can see that projection of right camera is seenon the left image at the point, . It is called the epipole. Epipole is the point of intersection of line through cameracenters and the image planes. Similarly is the epipole of the left camera. In some cases, you wont be able to locatethe epipole in the image, they may be outside the image (which means, one camera doesnt see the other).All the epilines pass through its epipole. So to find the location of epipole, we can find many epilines and find theirintersection point.So in this session, we focus on finding epipolar lines and epipoles. But to find them, we need two more ingredients,Fundamental Matrix (F) and Essential Matrix (E). Essential Matrix contains the information about translation androtation, which describe the location of the second camera relative to the first in global coordinates. See the imagebelow (Image courtesy: Learning OpenCV by Gary Bradsky):
But we prefer measurements to be done in pixel coordinates, right? Fundamental Matrix contains the same informationas Essential Matrix in addition to the information about the intrinsics of both cameras so that we can relate the twocameras in pixel coordinates. (If we are using rectified images and normalize the point by dividing by the focal lengths, = ). In simple words, Fundamental Matrix F, maps a point in one image to a line (epiline) in the other image.This is calculated from matching points from both the images. A minimum of 8 such points are required to find thefundamental matrix (while using 8-point algorithm). More points are preferred and use RANSAC to get a more robustresult.
So first we need to find as many possible matches between two images to find the fundamental matrix. For this, weuse SIFT descriptors with FLANN based matcher and ratio test.import cv2import numpy as npfrom matplotlib import pyplot as plt
sift = cv2.SIFT()
# FLANN parametersFLANN_INDEX_KDTREE = 0index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params,search_params)matches = flann.knnMatch(des1,des2,k=2)
good = []pts1 = []
pts2 = []
Now we have the list of best matches from both the images. Lets find the Fundamental Matrix.pts1 = np.int32(pts1)pts2 = np.int32(pts2)F, mask = cv2.findFundamentalMat(pts1,pts2,cv2.FM_LMEDS)
Next we find the epilines. Epilines corresponding to the points in first image is drawn on second image. So mentioningof correct images are important here. We get an array of lines. So we define a new function to draw these lines on theimages.def drawlines(img1,img2,lines,pts1,pts2): ''' img1 - image on which we draw the epilines for the points in img2 lines - corresponding epilines ''' r,c = img1.shape img1 = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR) img2 = cv2.cvtColor(img2,cv2.COLOR_GRAY2BGR) for r,pt1,pt2 in zip(lines,pts1,pts2): color = tuple(np.random.randint(0,255,3).tolist()) x0,y0 = map(int, [0, -r[2]/r[1] ]) x1,y1 = map(int, [c, -(r[2]+r[0]*c)/r[1] ]) img1 = cv2.line(img1, (x0,y0), (x1,y1), color,1) img1 = cv2.circle(img1,tuple(pt1),5,color,-1) img2 = cv2.circle(img2,tuple(pt2),5,color,-1) return img1,img2
Now we find the epilines in both the images and draw them.# Find epilines corresponding to points in right image (second image) and# drawing its lines on left imagelines1 = cv2.computeCorrespondEpilines(pts2.reshape(-1,1,2), 2,F)lines1 = lines1.reshape(-1,3)img5,img6 = drawlines(img1,img2,lines1,pts1,pts2)
plt.subplot(121),plt.imshow(img5)plt.subplot(122),plt.imshow(img3)plt.show()
You can see in the left image that all epilines are converging at a point outside the image at right side. That meeting
1. One important topic is the forward movement of camera. Then epipoles will be seen at the same locations in both with epilines emerging from a fixed point. See this discussion. 2. Fundamental Matrix estimation is sensitive to quality of matches, outliers etc. It becomes worse when all selected matches lie on the same plane. Check this discussion.
In this session, We will learn to create depth map from stereo images.
In last session, we saw basic concepts like epipolar constraints and other related terms. We also saw that if we havetwo images of same scene, we can get depth information from that in an intuitive way. Below is an image and somesimple mathematical formulas which proves that intuition. (Image Courtesy :
The above diagram contains equivalent triangles. Writing their equivalent equations will yield us following result:
= = and are the distance between points in image plane corresponding to the scene point 3D and their camera center. is the distance between two cameras (which we know) and is the focal length of camera (already known). So inshort, above equation says that the depth of a point in a scene is inversely proportional to the difference in distance ofcorresponding image points and their camera centers. So with this information, we can derive the depth of all pixelsin an image.So it finds corresponding matches between two images. We have already seen how epiline constraint make thisoperation faster and accurate. Once it finds matches, it finds the disparity. Lets see how we can do it with OpenCV.
imgL = cv2.imread('tsukuba_l.png',0)imgR = cv2.imread('tsukuba_r.png',0)
Below image contains the original image (left) and its disparity map (right). As you can see, result is contaminatedwith high degree of noise. By adjusting the values of numDisparities and blockSize, you can get better results.
1. OpenCV samples contain an example of generating disparity map and its 3D reconstruction. Check stereo_match.py in OpenCV-Python samples.
K-Nearest Neighbour
Learn to use kNN for classification Plus learn about handwritten digit recog- nition using kNN
K-Means Clustering
In this chapter, we will understand the concepts of k-Nearest Neighbour (kNN) algorithm.
kNN is one of the simplest of classification algorithms available for supervised learning. The idea is to search forclosest match of the test data in feature space. We will look into it with below image.
In the image, there are two families, Blue Squares and Red Triangles. We call each family as Class. Their houses areshown in their town map which we call feature space. (You can consider a feature space as a space where all datasare projected. For example, consider a 2D coordinate space. Each data has two features, x and y coordinates. You canrepresenttoalso added into Red Triangle. This method is called simply Nearest Neighbour, because classification depends onlyon the nearest neighbour.But there is a problem with that. Red Triangle may be the nearest. But what if there are lot of Blue Squares nearto him? Then Blue Squares have more strength in that locality than Red Triangle. So just checking nearest one isnot sufficient. Instead we check some k nearest families. Then whoever is majority in them, the new guy belongs tothat family. In our image, lets take k=3, ie 3 nearest families. He has two Red and one Blue (there are two Bluesequidistant, but since k=3, we take only one of them), so again he should be added to Red family. But what if wetake k=7? Then he has 5 Blue families and 2 Red families. Great!! Now he should be added to Blue family. So itall changes with value of k. More funny thing is, what if k = 4? He has 2 Red and 2 Blue neighbours. It is a tie !!!So better take k as an odd number. So this method is called k-Nearest Neighbour since classification depends on knearest givesome weights to each family depending on their distance to the new-comer. For those who are near to him get higherweights while those are far away get lower weights. Then we add total weights of each family separately. Whoevergets.Now lets see it in OpenCV.
kNN in OpenCV
We will do a simple example here, with two families (classes), just like above. Then in the next chapter, we will domuch more better example.So here, we label the Red family as Class-0 (so denoted by 0) and Blue family as Class-1 (denoted by 1). We create25 families or 25 training data, and label them either Class-0 or Class-1. We do all these with the help of RandomNumber Generator in Numpy.Then we plot it with the help of Matplotlib. Red families are shown as Red Triangles and Blue families are shown asBlue Squares.import cv2import numpy as npimport matplotlib.pyplot as plt
You will get something similar to our first image. Since you are using random number generator, you will be gettingdifferentkNN, we need to know something on our test data (data of new comers). Our data should be a floating point arraywith size . Then we find the nearest neighbours of new-comer. We canspecify how many neighbours we want. It returns: 1. The label given to new-comer depending upon the kNN theory we saw earlier. If you want Nearest Neighbour algorithm, just specify k=1 where k is the number of neighbours.
knn = cv2.KNearest()knn.train(trainData,responses)ret, results, neighbours ,dist = knn.find_nearest(newcomer, 3)
It says our new-comer got 3 neighbours, all from Blue family. Therefore, he is labelled as Blue family. It is obviousfrom plot below:
If you have large number of data, you can just pass it as array. Corresponding results are also obtained as arrays.
# 10 new comersnewcomers = np.random.randint(0,100,(10,2)).astype(np.float32)ret, results,neighbours,dist = knn.find_nearest(newcomer, 3)# The results also will contain 10 labels.
In this chapter We will use our knowledge on kNN to build a basic OCR application. We will try with Digits and Alphabets data available that comes with OpenCV.
Our goal is to build an application which can read the handwritten digits. For this we need some train_data andtest_data. OpenCV comes with an image digits.png (in the folder opencv/samples/python2/data/) whichhas 5000 handwritten digits (500 for each digit). Each digit is a 20x20 image. So our first step is to split this imageinto 5000 different digits. For each digit, we flatten it into a single row with 400 pixels. That is our feature set, ieintensity values of all pixels. It is the simplest feature set we can create. We use first 250 samples of each digit astrain_data, and next 250 samples as test_data. So lets prepare them first.import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('digits.png')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Initiate kNN, train the data, then test it with test data for k=1knn = cv2.KNearest()
knn.train(train,train_labels)ret,result,neighbours,dist = knn.find_nearest(test,k=5)
So our basic OCR app is ready. This particular example gave me an accuracy of 91%. One option improve accuracyis to add more data for training, especially the wrong ones. So instead of finding this training data everytime I startapplication, I better save it, so that next time, I directly read this data from a file and start classification. You can do itwith the help of some Numpy functions like np.savetxt, np.savez, np.load etc. Please check their docs for more details.# save the datanp.savez('knn_data.npz',train=train, train_labels=train_labels)
In my system, it takes around 4.4 MB of memory. Since we are using intensity values (uint8 data) as features, it wouldbe better to convert the data to np.uint8 first and then save it. It takes only 1.1 MB in this case. Then while loading,you can convert back into float32.
Next we will do the same for English alphabets, but there is a slight change in data and feature set. Here, instead ofimages, OpenCV comes with a data file, letter-recognition.data in opencv/samples/cpp/ folder. Ifyou open it, you will see 20000 lines which may, on first sight, look like garbage. Actually, in each row, first columnis an alphabet which is our label. Next 16 numbers following it are its different features. These features are obtainedfrom UCI Machine Learning Repository. You can find the details of these features in this page.There are 20000 samples available, so we take first 10000 data as training samples and remaining 10000 as testsamples. We should change the alphabets to ascii characters because we cant work with alphabets directly.import cv2import numpy as npimport matplotlib.pyplot as plt
# split the data to two, 10000 each for train and testtrain, test = np.vsplit(data,2)
It gives me an accuracy of 93.22%. Again, if you want to increase accuracy, you can iteratively add error data in eachlevel.
Understanding SVM
Understanding SVM
In this chapter We will see an intuitive understanding of SVM
Linearly Separable Data Consider the image below which has two types of data, red and blue. In kNN, for a testdata, we used to measure its distance to all the training samples and take the one with minimum distance. It takesplenty of time to measure all the distances and plenty of memory to store all the training-samples. But considering thedata given in image, should we need that much?
Consider another idea. We find a line, () = 1 + 2 + which divides both the data to two regions. When weget a new test_data , just substitute it in (). If () > 0, it belongs to blue group, else it belongs to red group.We can call this line as Decision Boundary. It is very simple and memory-efficient. Such data which can be dividedinto two with a straight line (or hyperplanes in higher dimensions) is called Linear Separable.So in above image, you can see plenty of such lines are possible. Which one we will take? Very intuitively we cansay that the line should be passing as far as possible from all the points. Why? Because there can be noise in theincoming data. This data should not affect the classification accuracy. So taking a farthest line will provide moreimmunity against noise. So what SVM does is to find a straight line (or hyperplane) with largest minimum distance tothe training samples. See the bold line in below image passing through the center.
So to find this Decision Boundary, you need training data. Do you need all? NO. Just the ones which are close to theopposite group are sufficient. In our image, they are the one blue filled circle and two red filled squares. We can callthem Support Vectors and the lines passing through them are called Support Planes. They are adequate for findingour decision boundary. We need not worry about all the data. It helps in data reduction.What happened is, first two hyperplanes are found which best represents the data. For eg, blue data is represented by + 0 > 1 while red data is represented by + 0 < 1 where is weight vector ( = [1 , 2 , ..., ]) and is the feature vector ( = [1 , 2 , ..., ]). 0 is the bias. Weight vector decides the orientation of decision boundarywhile bias point decides its location. Now decision boundary is defined to be midway between these hyperplanes,so expressed as + 0 = 0. The minimum distance from support vector to the decision boundary is given by, 1 = |||| . Margin is twice this distance, and we need to maximize this margin. i.e. we need tominimize a new function (, 0 ) with some constraints which can expressed below: 1 min (, 0 ) = ||||2 subject to ( + 0 ) 1 ,0 2where is the label of each class, [1, 1].
Non-Linearly Separable Data Consider some data which cant be divided into two with a straight line. For exam-ple, consider an one-dimensional data where X is at -3 & +3 and O is at -1 & +1. Clearly it is not linearly separable.But there are methods to solve these kinds of problems. If we can map this data set with a function, () = 2 , weget X at 9 and O at 1 which are linear separable.Otherwise we can convert this one-dimensional to two-dimensional data. We can use () = (, 2 ) function tomap this data. Then X becomes (-3,9) and (3,9) while O becomes (-1,1) and (1,1). This is also linear separable.In short, chance is more for a non-linear separable data in lower-dimensional space to become linear separable inhigher-dimensional space.In general, it is possible to map points in a d-dimensional space to some D-dimensional space ( > ) to check thepossibility of linear separability. There is an idea which helps to compute the dot product in the high-dimensional (ker-nel) space by performing computations in the low-dimensional input (feature) space. We can illustrate with followingexample.Consider two points in two-dimensional space, = (1 , 2 ) and = (1 , 2 ). Let be a mapping function whichmaps a two-dimensional point to three-dimensional space as follows: () = (21 , 22 , 21 2 )() = (12 , 22 , 21 2 )
Let us define a kernel function (, ) which does a dot product between two points, shown below:
(, ) = ().() = () , () = (21 , 22 , 21 2 ).(12 , 22 , 21 2 ) = 21 12 + 22 22 + 21 1 2 2 = (1 1 + 2 2 )2 ().() = (.)2
It means, a dot product in three-dimensional space can be achieved using squared dot product in two-dimensionalspace. This can be applied to higher dimensional space. So we can calculate higher dimensional features from lowerdimensions itself. Once we map them, we get a higher dimensional space.In addition to all these concepts, there comes the problem of misclassification. So just finding decision boundary withmaximum margin is not sufficient. We need to consider the problem of misclassification errors also. Sometimes, itmay be possible to find a decision boundary with less margin, but with reduced misclassification. Anyway we need tomodify our model such that it should find decision boundary with maximum margin, but with less misclassification.The minimization criteria is modified as:
||||2 + ( )
Below image shows this concept. For each sample of the training data a new parameter is defined. It is the distancefrom its corresponding training sample to their correct decision region. For those who are not misclassified, they fallon their corresponding support planes, so their distance is zero.
How should the parameter C be chosen? It is obvious that the answer to this question depends on how the trainingdata is distributed. Although there is no general answer, it is useful to take into account these rules: Large values of C give solutions with less misclassification errors but a smaller margin. Consider that in this case it is expensive to make misclassification errors. Since the aim of the optimization is to minimize the argument, few misclassifications errors are allowed. Small values of C give solutions with bigger margin and more classification errors. In this case the minimization does not consider that much the term of the sum so it focuses more on finding a hyperplane with big margin.
In this chapter We will revisit the hand-written data OCR, but, with SVM instead of kNN.
In kNN, we directly used pixel intensity as the feature vector. This time we will use Histogram of Oriented Gradients(HOG) as feature vectors.
Here, before finding the HOG, we deskew the image using its second order moments. So we first define a functiondeskew() which takes a digit image and deskew it. Below is the deskew() function
Below image shows above deskew function applied to an image of zero. Left image is the original image and rightimage is the deskewed image.
Next we have to find the HOG Descriptor of each cell. For that, we find Sobel derivatives of each cell in X and Ydirection. Then find their magnitude and direction of gradient at each pixel. This gradient is quantized to 16 integervalues. Divide this image to four sub-squares. For each sub-square, calculate the histogram of direction (16 bins)weighted with their magnitude. So each sub-square gives you a vector containing 16 values. Four such vectors (offour sub-squares) together gives us a feature vector containing 64 values. This is the feature vector we use to train ourdata.def hog(img): gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy)
# Divide to 4 sub-squares) return hist
Finally, as in the previous case, we start by splitting our big dataset into individual cells. For every digit, 250 cells arereserved for training data and remaining 250 data is reserved for testing. Full code is given below:import cv2import numpy as np
SZ=20bin_n = 16 # Number of bins
affine_flags = cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR
def hog(img): gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)) # hist is a 64 bit vector return hist
img = cv2.imread('digits.png',0)
svm = cv2.SVM()svm.train(trainData,responses, params=svm_params)svm.save('svm_data.dat')
result = svm.predict_all(testData)
This particular technique gave me nearly 94% accuracy. You can try different values for various parameters of SVMto check if higher accuracy is possible. Or you can read technical papers on this area and try to implement them.
1. OpenCV samples contain digits.py which applies a slight improvement of the above method to get improved result. It also contains the reference. Check it and understand it.
In this chapter, we will understand the concepts of K-Means Clustering, how it works etc.
T-shirt size problem Consider a company, which is going to release a new model of T-shirt to market. Obviouslythey will have to manufacture models in different sizes to satisfy people of all sizes. So the company make a data ofpeoples height and weight, and plot them on to a graph, as below:
Company cant create t-shirts with all the sizes. Instead, they divide people to Small, Medium and Large, and manu-facture only these 3 models which will fit into all the people. This grouping of people into three groups can be doneby k-means clustering, and algorithm provides us best 3 sizes, which will satisfy all the people. And if it doesnt,company can divide people to more groups, may be five, and so on. Check image below :
How does it work ?, 1 and 2 (sometimes, any two data are taken as the centroids).Step : 2 - It calculates the distance from each point to both centroids. If a test data is more closer to 1, then that datais labelled with 0. If it is closer to 2, then labelled as 1 (If more centroids are there, labelled as 2,3 etc).
In our case, we will color all 0 labelled with red, and 1 labelled with blue. So we get following image after aboveoperations.
Step : 3 - Next we calculate the average of all blue points and red points separately and that will be our new centroids.That is 1 and 2 shift to newly calculated centroids. (Remember, the images shown are not true values and not totrue scale, it is just for demonstration only).And again, perform step 2 with new centroids and label data to 0 and 1.So we get result as below :
Now Step - 2 and Step - 3 are iterated until both centroids are converged to fixed points. (Or it may be stoppeddepending on the criteria we provide, like maximum number of iterations, or a specific accuracy is reached etc.)These points are such that sum of distances between test data and their corresponding centroids are minimum.Or simply, sum of distances between 1 _ and 2 _ is minimum. [ ] = (1, _ ) + (2, _ ) _
So this is just an intuitive understanding of K-Means Clustering. For more details and mathematical explanation,please read any standard machine learning textbooks or check links in additional resources. It is just a top layer ofK-Means clustering. There are a lot of modifications to this algorithm like, how to choose the initial centroids, how tospeed up the iteration process etc.
1. Machine Learning Course, Video lectures by Prof. Andrew Ng (Some of the images are taken from this)
Understanding Parameters
Input parameters 1. samples : It should be of np.float32 data type, and each feature should be put in a single column. 2. nclusters(K) : Number of clusters required at end
3. criteria [It is the iteration termination criteria. When this criteria is satisfied, algorithm iteration stops. Actually, it should be a tuple of 3 parameters. They are ( type, max_iter, epsilon ):] 3.a - type of termination criteria [It has 3 flags as below:] cv2.TERM_CRITERIA_EPS - stop the algorithm iteration if specified accuracy, epsilon, is reached. cv2.TERM_CRITERIA_MAX_ITER - stop the algorithm after the specified number of iterations, max_iter. cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER - stop the iteration when any of the above condition is met. 3.b - max_iter - An integer specifying maximum number of iterations. 3.c - epsilon - Required accuracy 4. attempts : Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness. This compactness is returned as output. 5. flags : This flag is used to specify how initial centers are taken. Normally two flags are used for this : cv2.KMEANS_PP_CENTERS and cv2.KMEANS_RANDOM_CENTERS.
Output parameters 1. compactness : It is the sum of squared distance from each point to their corresponding centers. 2. labels : This is the label array (same as code in previous article) where each element marked 0, 1..... 3. centers : This is array of centers of clusters.Now we will see how to apply K-Means algorithm with three examples.
Consider, you have a set of data with only one feature, ie one-dimensional. For eg, we can take our t-shirt problemwhere you use only height of people to decide the size of t-shirt.So we start by creating data and plot it in Matplotlibimport numpy as npimport cv2from matplotlib import pyplot as plt
x = np.random.randint(25,100,25)y = np.random.randint(175,255,25)z = np.hstack((x,y))z = z.reshape((50,1))z = np.float32(z)plt.hist(z,256,[0,256]),plt.show()
So we have z which is an array of size 50, and values ranging from 0 to 255. I have reshaped z to a column vector.It will be more useful when more than one features are present. Then I made data of np.float32 type.We get following image :
Now we apply the KMeans function. Before that we need to specify the criteria. My criteria is such that, whenever10 iterations of algorithm is ran, or an accuracy of epsilon = 1.0 is reached, stop the algorithm and return theanswer.# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Apply KMeanscompactness,labels,centers = cv2.kmeans(z,2,None,criteria,10,flags)
This gives us the compactness, labels and centers. In this case, I got centers as 60 and 207. Labels will have the samesize as that of test data where each data will be labelled as 0,1,2 etc. depending on their centroids. Now we splitthe data to different clusters depending on their labels.A = z[labels==0]B = z[labels==1]
Now we plot A in Red color and B in Blue color and their centroids in Yellow color.# Now plot 'A' in red, 'B' in blue, 'centers' in yellowplt.hist(A,256,[0,256],color = 'r')plt.hist(B,256,[0,256],color = 'b')plt.hist(centers,32,[0,256],color = 'y')plt.show()
In previous example, we took only height for t-shirt problem. Here, we will take both height and weight, ie twofeatures.Remember, in previous case, we made our data to a single column vector. Each feature is arranged in a column, whileeach row corresponds to an input test sample.For example, in this case, we set a test data of size 50x2, which are heights and weights of 50 people. First columncorresponds to height of all the 50 people and second column corresponds to their weights. First row contains twoelements where first one is the height of first person and second one his weight. Similarly remaining rows correspondsto heights and weights of other people. Check image below:
X = np.random.randint(25,50,(25,2))Y = np.random.randint(60,85,(25,2))Z = np.vstack((X,Y))
# convert to np.float32Z = np.float32(Z)
3. Color Quantization
Color Quantization is the process of reducing number of colors in an image. One reason to do so is to reduce thememory. Sometimes, some devices may have limitation such that it can produce only limited number of colors. Inthose cases also, color quantization is performed. Here we use k-means clustering for color quantization.There is nothing new to be explained here. There are 3 features, say, R,G,B. So we need to reshape the image to anarray of Mx3 size (M is number of pixels in image). And after the clustering, we apply centroid values (it is alsoR,G,B) to all pixels, such that resulting image will have specified number of colors. And again we need to reshape itback to the shape of original image. Below is the code:import numpy as npimport cv2
img = cv2.imread('home.jpg')Z = img.reshape((-1,3))
cv2.imshow('res2',res2)cv2.waitKey(0)cv2.destroyAllWindows()
Here you will learn different OpenCV functionalities related to Computational Photography like image denoising etc. Image Denoising
Image Inpainting
Do you have a old degraded photo with many black spots and strokes on it? Take it. Lets try to restore them with a technique called image inpainting.
In this chapter, You will learn about Non-local Means Denoising algorithm to remove noise in the image. You will see different functions like cv2.fastNlMeansDenoising(), cv2.fastNlMeansDenoisingColored() etc.
In earlier chapters, we have seen many image smoothing techniques like Gaussian Blurring, Median Blurring etcand they were good to some extent in removing small quantities of noise. In those techniques, we took a smallneighbourhood around a pixel and did some operations like gaussian weighted average, median of the values etc toreplace the central element. In short, noise removal at a pixel was local to its neighbourhood.There is a property of noise. Noise is generally considered to be a random variable with zero mean. Consider a noisypixel, = 0 + where 0 is the true value of pixel and is the noise in that pixel. You can take large number ofsame pixels (say ) from different images and computes their average. Ideally, you should get = 0 since mean ofnoise is zero.You can verify it yourself by a simple setup. Hold a static camera to a certain location for a couple of seconds. Thiswill give you plenty of frames, or a lot of images of the same scene. Then write a piece of code to find the average ofall the frames in the video (This should be too simple for you now ). Compare the final result and first frame. You cansee reduction in noise. Unfortunately this simple method is not robust to camera and scene motions. Also often thereis only one noisy image available.So idea is simple, we need a set of similar images to average out the noise. Consider a small window (say 5x5window) in the image. Chance is large that the same patch may be somewhere else in the image. Sometimes in a smallneigbourhood around it. What about using these similar patches together and find their average? For that particularwindow, that is fine. See an example image below:
The blue patches in the image looks the similar. Green patches looks similar. So we take a pixel, take small windowaround it, search for similar windows in the image, average all the windows and replace the pixel with the result wegot..
1. cv2.fastNlMeansDenoisingColored()
As mentioned above it is used to remove noise from color images. (Noise is expected to be gaussian). See the examplebelow:import numpy as npimport cv2from matplotlib import pyplot as plt
img = cv2.imread('die.png')
dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)
plt.subplot(121),plt.imshow(img)plt.subplot(122),plt.imshow(dst)plt.show()
Below is a zoomed version of result. My input image has a gaussian noise of = 25. See the result:
2. cv2.fastNlMeansDenoisingMulti()
Now we will apply the same method to a video. The first argument is the list of noisy frames. Second argumentimgToDenoiseIndex specifies which frame we need to denoise, for that we pass the index of frame in our input list.Third is the temporalWindowSize which specifies the number of nearby frames to be used for denoising. It should beodd. In that case, a total of temporalWindowSize frames are used where central frame is the frame to be denoised.For example, you passed a list of 5 frames as input. Let imgToDenoiseIndex = 2 and temporalWindowSize = 3. Thenframe-1, frame-2 and frame-3 are used to denoise frame-2. Lets see an example.import numpy as npimport cv2from matplotlib import pyplot as plt
plt.subplot(131),plt.imshow(gray[2],'gray')plt.subplot(132),plt.imshow(noisy[2],'gray')plt.subplot(133),plt.imshow(dst,'gray')plt.show()
It takes considerable amount of time for computation. In the result, first image is the original frame, second is thenoisy one, third is the denoised image.
1. (It has the details, online demo etc. Highly recommended to visit. Our test image is generated from this link) 2. Online course at coursera (First image taken from here)
In this chapter, We will learn how to remove small noises, strokes etc in old photographs by a method called inpainting We will see inpainting functionalities in OpenCV.
Most of you will have some old degraded photos at your home with some black spots, some strokes etc on it. Haveyou ever thought of restoring it back? We cant simply erase them in a paint tool because it is will simply replaceblacksame function, cv2.inpaint()First algorithm is based on the paper An Image Inpainting Technique Based on the Fast Marching Method byAlexandru Telea in 2004. It is based on Fast Marching Method. Consider a region in the image to be inpainted. Al-gorithm starts from the boundary of this region and goes inside the region gradually filling everything in the boundaryfirst. It takes a small neighbourhood around the pixel on the neigbourhood to be inpainted. This pixel is replaced bynormalized weighted sum of all the known pixels in the neigbourhood. Selection of the weights is an important matter.More weightage is given to those pixels lying near to the point, near to the normal of the boundary and those lying ontheBertalmio, Marcelo, Andrea L. Bertozzi, and Guillermo Sapiro in 2001. This algorithm is based on fluid dynamics andutilizes partial differential equations. Basic principle is heurisitic. It first travels along the edges from known regionsto unknown regions (because edges are meant to be continuous). It continues isophotes (lines joining points with sameintensity, just like contours joins points with same elevation) while matching gradient vectors at the boundary of theinpainting region. For this, some methods from fluid dynamics are used. Once they are obtained, color is filled toreduce minimum variance in that area. This algorithm is enabled by using the flag, cv2.INPAINT_NS.
We need to create a mask of same size as that of input image, where non-zero pixels corresponds to the area whichis to be inpainted. Everything else is simple. My image is degraded with some black strokes (I added manually). Icreated a corresponding strokes with Paint tool.import numpy as npimport cv2
img = cv2.imread('messi_2.jpg')mask = cv2.imread('mask2.png',0)
dst = cv2.inpaint(img,mask,3,cv2.INPAINT_TELEA)
See the result below. First image shows degraded input. Second image is the mask. Third image is the result of firstalgorithm and last image is the result of second algorithm.
1. Bertalmio, Marcelo, Andrea L. Bertozzi, and Guillermo Sapiro. Navier-stokes, fluid dynamics, and image and video inpainting. In Computer Vision and Pattern Recognition, 2001. CVPR 2001. Proceedings of the 2001 IEEE Computer Society Conference on, vol. 1, pp. I-355. IEEE, 2001. 2. Telea, Alexandru. An image inpainting technique based on the fast marching method. Journal of graphics tools 9.1 (2004): 23-34.
In this session, We will see the basics of face detection using Haar Feature-based Cascade Classifiers We will extend the same for eye detection etc.
Object Detection using Haar feature-based cascade classifiers is an effective object detection method proposed byPaul Viola and Michael Jones in their paper, Rapid Object Detection using a Boosted Cascade of Simple Features in2001. It is a machine learning based approach where a cascade function is trained from a lot of positive and negativeimages. It is then used to detect objects in other images.Here we will work with face detection. Initially, the algorithm needs a lot of positive images (images of faces) andnegative images (images without faces) to train the classifier. Then we need to extract features from it. For this, haarfeatures shown in below image are used. They are just like our convolutional kernel. Each feature is a single valueobtained by subtracting sum of pixels under white rectangle from sum of pixels under black rectangle.
Now all possible sizes and locations of each kernel is used to calculate plenty of features. (Just imagine how muchcomputation it needs? Even a 24x24 window results over 160000 features). For each feature calculation, we need tofind sum of pixels under white and black rectangles. To solve this, they introduced the integral images. It simplifiescalculation of sum of pixels, how large may be the number of pixels, to an operation involving just four pixels. Nice,isnt it? It makes things super-fast.But among all these features we calculated, most of them are irrelevant. For example, consider the image below. Toprow shows two good features. The first feature selected seems to focus on the property that the region of the eyes isoften darker than the region of the nose and cheeks. The second feature selected relies on the property that the eyes
are darker than the bridge of the nose. But the same windows applying on cheeks or any other place is irrelevant. Sohow do we select the best features out of 160000+ features? It is achieved by Adaboost.
For this, we apply each and every feature on all the training images. For each feature, it finds the best threshold whichwill classify the faces to positive and negative. But obviously, there will be errors or misclassifications. We select thefeatures with. Alsonew weights. The process is continued until required accuracy or error rate is achieved or required number of featuresare found).Final classifier is a weighted sum of these weak classifiers. It is called weak because it alone cant..Wow.. Isnt it a little inefficient and time consuming? Yes, it is. Authors have a good solution for that.In an image, most of the image region is non-face region. So it is a better idea to have a simple method to check ifa window is not a face region. If it is not, discard it in a single shot. Dont process it again. Instead focus on regionwhere there can be a face. This way, we can find more time to check a possible face region.For this they introduced the concept of Cascade of Classifiers. Instead of applying all the 6000 features on a window,group the features into different stages of classifiers and apply one-by-one. (Normally first few stages will containvery less number of features). If a window fails the first stage, discard it. We dont consider remaining features on it.If it passes, apply the second stage of features and continue the process. The window which passes all stages is a faceregion. How is the plan !!!Authors detector had 6000+ features with 38 stages with 1, 10, 25, 25 and 50 features in first five stages. (Two features checkout the references in Additional Resources section.
OpenCV comes with a trainer as well as detector. If you want to train your own classifier for any object like car, planesetc. you can use OpenCV to create one. Its full details are given here: Cascade Classifier Training.Here we will deal with detection. OpenCV already contains many pre-trained classifiers for face, eyes, smile etc.Those XML files are stored in opencv/data/haarcascades/ folder. Lets create face and eye detector withOpenCV.First we need to load the required XML classifiers. Then load our input image (or video) in grayscale mode.import numpy as npimport)
Now we find the faces in the image. If faces are found, it returns the positions of detected faces as Rect(x,y,w,h). Oncewe get these locations, we can create a ROI for the face and apply eye detection on this ROI (since eyes are always onthe face !!! ).faces = face_cascade.detectMultiScale(gray, 1.3, 5)for (x,y,w,h) in faces: img =)
Learn: How OpenCV-Python bindings are generated? How to extend new OpenCV modules to Python?
In OpenCV, all algorithms are implemented in C++. But these algorithms can be used from different languages likePython, Java etc. This is made possible by the bindings generators. These generators create a bridge between C++and Python which enables users to call C++ functions from Python. To get a complete picture of what is happeningin background, a good knowledge of Python/C API is required. A simple example on extending C++ functions toPython can be found in official Python documentation[1]. So extending all functions in OpenCV to Python by writingtheir wrapper functions manually is a time-consuming task. So OpenCV does it in a more intelligent way. OpenCVgenerates these wrapper functions automatically from the C++ headers using some Python scripts which are locatedin modules/python/src2. We will look into what they do.First, modules/python/CMakeFiles.txt is a CMake script which checks the modules to be extended toPython. It will automatically check all the modules to be extended and grab their header files. These header filescontain list of all classes, functions, constants etc. for that particular modules.Second, these header files are passed to a Python script, modules/python/src2/gen2.py. This is the Pythonbindings generator script. It calls another Python script modules/python/src2/hdr_parser.py. This is theheader parser script. This header parser splits the complete header file into small Python lists. So these lists containall details about a particular function, class etc. For example, a function will be parsed to get a list containing functionname, return type, input arguments, argument types etc. Final list contains details of all the functions, structs, classesetc. in that header file.But header parser doesnt parse all the functions/classes in the header file. The developer has to specify which functionsshould be exported to Python. For that, there are certain macros added to the beginning of these declarations whichenables the header parser to identify functions to be parsed. These macros are added by the developer who programsthe particular function. In short, the developer decides which functions should be extended to Python and which arenot. Details of those macros will be given in next session.So header parser returns a final big list of parsed functions. Our generator script (gen2.py) will create wrapper functionsfor all the functions/classes/enums/structs parsed by header parser (You can find these header files during compilationin the build/modules/python/ folder as pyopencv_generated_*.h files). But there may be some basicOpenCV datatypes like Mat, Vec4i, Size. They need to be extended manually. For example, a Mat type should beextended to Numpy array, Size should be extended to a tuple of two integers etc. Similarly, there may be some complexstructs/classes/functions etc. which need to be extended manually. All such manual wrapper functions are placed inmodules/python/src2/pycv2.hpp.So now only thing left is the compilation of these wrapper files which gives us cv2 module. So when you call a func-tion, say res = equalizeHist(img1,img2) in Python, you pass two numpy arrays and you expect anothernumpy array as the output. So these numpy arrays are converted to cv::Mat and then calls the equalizeHist()function in C++. Final result, res will be converted back into a Numpy array. So in short, almost all operations aredone in C++ which gives us almost same speed as that of C++.So this is the basic version of how OpenCV-Python bindings are generated.
Header parser parse the header files based on some wrapper macros added to function declaration. Enumerationconstants dont need any wrapper macros. They are automatically wrapped. But remaining functions, classes etc.need wrapper macros.Functions are extended using CV_EXPORTS_W macro. An example is shown below.CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );
Header parser can understand the input and output arguments from keywords like InputArray, OutputArrayetc.used for class fields.class CV_EXPORTS_W CLAHE : public Algorithm{public: CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0;
Overloaded functions can be extended using CV_EXPORTS_AS. But we need to pass a new name so that each functionwill be called by that name in Python. Take the case of integral function below. Three functions are available, so eachone is named with a suffix in Python. Similarly CV_WRAP_AS can be used to wrap overloaded methods.//! computes the integral imageCV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth = -1 );
//! computes the integral image and integral for the squared imageCV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum, OutputArray sqsum, int sdepth = -1, int sqdepth = -1 );
//! computes the integral image, integral for the squared image and the tilted integral imageCV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, int sdepth = -1, int sqdepth = -1 );
Small classes/structs are extended using CV_EXPORTS_W_SIMPLE. These structs are passed by value to C++ func-tions. Examples are KeyPoint, Match etc. Their methods are extended by CV_WRAP and fields are extended byCV);
Some other small classes/structs can be exported using CV_EXPORTS_W_MAP where it is exported to a Python nativedictionary.;};
So these are the major extension macros available in OpenCV. Typically, a developer has to put proper macros intheir appropriate positions. Rest is done by generator scripts. Sometimes, there may be an exceptional cases wheregenerator scripts cannot create the wrappers. Such functions need to be handled manually. But most of the time, acode written according to OpenCV coding guidelines will be automatically wrapped by generator scripts.
genindex modindex search
269 | https://ru.scribd.com/document/340141276/Opencv-Python-Tutroals | CC-MAIN-2019-39 | refinedweb | 38,722 | 59.5 |
Is there any way to customize the colours for individual bars in a bar plot? I would like one bar in a bar plot to be a different colour than the rest of the bars.
Customize colors on bar plots
Hi blockhart!
There are a few ways you could do this, depending upon what makes that bar special. Here’s a simple example based on value-- if you literally want only one specific bar to be a different color, maybe you want to go by index position?
from bokeh.plotting import figure, show x = ['a', 'b', 'c', 'd', 'e', 'f'] num_list = [4, 3, 5, 4, 9, 4] # construct a list of colors based on characteristics of the values in num_list. color_list = [] for i in num_list: if i > 7: color_list.append('orange') else: color_list.append('blue') p = figure(x_range=x, plot_height=350, title="vbar color demo", toolbar_location=None, tools="") p.vbar(x=x, top=num_list, color=color_list, width=.9) show(p)
Thanks for the answer! I should have said I’m using the VBar function not vbar, similar to this example. Any recommendations on how to accomplish your above solution with VBar or must I switch to vbar.
Since it looks like VBar takes only a single value as color, any workarounds I’m thinking of would probably be ungainly and cause maintenance issues-- like splitting your data source into two data sources, and then having two different colored glyphs. That would either break or multiply some other things like hover tools, though, and it doesn’t feel like the right way to go.
If it were me, I’d rework to use vbar, unless there’s some other advantage to VBar. I’d love to hear from others in case there’s an approach I’m not thinking of, though.
The glyph methods (e.g.
vbar) are a convenience API built on top of the low-level glyph classes (e.g.
VBar) There’s nothing you can do with one that you can’t do with the other, but using the low-level classes will be more work and more verbose, which is why I generally recommend folks to use the glyph methods on
figure unless there is a specific reason not to.
To use the
VBar, you need to:
- Create a
ColumnDataSourcewith the data columns you want (x, y, colors, etc)
- Configure the a
VBarinstance to refer to those column names
- Explicity add the glyph and the data source together to a plot with
add_glyph(...)
There are lots of examples of these steps in the scripts in the
examples/models directory. | https://discourse.bokeh.org/t/customize-colors-on-bar-plots/4022 | CC-MAIN-2019-43 | refinedweb | 432 | 70.02 |
One of the main priorities for the Toptal engineering team is migration toward a service-based architecture. A crucial element of the initiative was Billing Extraction, a project in which we isolated billing functionality from the Toptal platform to deploy it as a separate service.
Over the past few months, we extracted the first part of the functionality. To integrate billing with other services, we used both an asynchronous API (Kafka-based) and a synchronous API (HTTP-based).
This article is a record of our efforts toward optimizing and stabilizing the synchronous API.
Incremental Approach
This was the first stage of our initiative. On our journey to full billing extraction, we strive to work in an incremental manner delivering small and safe changes to production. (See slides from an excellent talk about another aspect of this project: incremental extraction of an engine from a Rails app.)
The starting point was the Toptal platform, a monolithic Ruby on Rails application. We started by identifying the seams between billing and the Toptal platform at the data level. The first approach was to replace Active Record (AR) relations with regular method calls. Next, we needed to implement a REST call to the billing service fetching data returned by the method.
We deployed a small billing service accessing the same database as the platform. We were able to query billing either using HTTP API or with direct calls to the database. This approach allowed us to implement a safe fallback; in case the HTTP request failed for any reason (incorrect implementation, performance issue, deployment problems), we used a direct call and returned the correct result to the caller.
To make the transitions safe and seamless, we used a feature flag to switch between HTTP and direct calls. Unfortunately, the first attempt implemented with REST proved to be unacceptably slow. Simply replacing AR relations with remote requests caused crashes when HTTP was enabled. Even though we enabled it only for a relatively small percentage of calls, the problem persisted.
We knew we needed a radically different approach.
The Billing Internal API (aka B2B)
We decided to replace REST with GraphQL (GQL) to get more flexibility on the client side. We wanted to make data-driven decisions during this transition to be able to predict outcomes this time.
To do that, we instrumented every request from the Toptal platform (monolith) to billing and logged detailed information: response time, parameters, errors, and even stack trace on them (to understand which parts of the platform use billing). This allowed us to detect hotspots — places in the code that send many requests or those that cause slow responses. Then, with stacktrace and parameters, we could reproduce issues locally and have a short feedback loop for many fixes.
To avoid nasty surprises on production, we added another level of feature flags. We had one flag per method in the API to move from REST to GraphQL. We were enabling HTTP gradually and watching if “something bad” appeared in the logs.
In most cases, “something bad” was either a long (multi-second) response time,
429 Too Many Requests, or
502 Bad Gateway. We employed several patterns to fix these problems: preloading and caching data, limiting data fetched from the server, adding jitter, and rate-limiting.
Preloading and Caching
The first issue we noticed was a flood of requests sent from a single class/view, similar to the N+1 problem in SQL.
Active Record preloading didn’t work over the service border and, as a result, we had a single page sending ~1,000 requests to billing with every reload. A thousand requests from a single page! The situation in some background jobs wasn’t much better. We preferred to make dozens of requests rather than thousands.
One of the background jobs was fetching job data (let’s call this model
Product) and checking if a product should be marked as inactive based on billing data (for this example, we’ll call the model
BillingRecord). Even though products were fetched in batches, the billing data was requested every time it was needed. Every product needed billing records, so processing every single product caused a request to the billing service to fetch them. That meant one request per product and resulted in about 1,000 requests sent from a single job execution.
To fix that, we added batch preloading of billing records. For every batch of products fetched from the database, we requested billing records once and then assigned them to respective products:
# fetch all required billing records and assign them to respective products def cache_billing_records(products) # array of billing records billing_records = Billing::QueryService .billing_records_for_products(*products) indexed_records = billing_records.group_by(&:product_gid) products.each do |p| e.cache_billing_records!(indexed_records[p.gid].to_a) } end end
With batches of 100 and a single request to the billing service per batch, we went from ~1,000 requests per job to ~10.
Client-side Joins
Batching requests and caching billing records worked well when we had a collection of products and we needed their billing records. But what about the other way around: if we fetched billing records and then tried to use their respective products, fetched from the platform database?
As expected, this caused another N+1 problem, this time on the platform side. When we were using products to collect N billing records, we were performing N database queries.
The solution was to fetch all needed products at once, store them as a hash indexed by ID, and then assign them to their respective billing records. A simplified implementation is:
def product_billing_records(products) products_by_gid = products.index_by(&:gid) product_gids = products_by_gid.keys.compact return [] if product_gids.blank? billing_records = fetch_billing_records(product_gids: product_gids) billing_records.each do |billing_record| billing_record.preload_product!( products_by_gid[billing_record.product_gid] ) end end
If you think that it’s similar to a hash join, you’re not alone.
Server-side Filtering and Underfetching
We fought off the worst spikes of requests and N+1 issues on the platform side. We still had slow responses, though. We identified that they were caused by loading too much data to the platform and filtering it there (client-side filtering). Loading data to memory, serializing it, sending it over the network, and deserializing just to drop most of it was a colossal waste. It was convenient during implementation because we had generic and reusable endpoints. During operations, it proved unusable. We needed something more specific.
We addressed the issue by adding filtering arguments to GraphQL. Our approach was similar to a well-known optimization that consists of moving filtering from the app level to the DB query (
find_all vs.
where in Rails). In the database world, this approach is obvious and available as
WHERE in the
SELECT query. In this case, it required us to implement query handling by ourselves (in Billing).
We deployed the filters and waited to see a performance improvement. Instead, we saw 502 errors on the platform (and our users also saw them too). Not good. Not good at all!
Why did that happen? That change should have improved response time, not break the service. We had introduced a subtle bug inadvertently. We retained both versions of the API (GQL and REST) on the client side. We switched gradually with a feature flag. The first, unfortunate version we deployed introduced a regression in the legacy REST branch. We focused our testing on the GQL branch, so we missed the performance issue in REST. Lesson learned: If search parameters are missing, return an empty collection, not everything you have in your database.
Take a look at the
NewRelic data for Billing. We deployed the changes with server-side filtering during a lull in traffic (we switched off billing traffic after encountering platform issues). You can see that responses are faster and more predictable after deployment.
It wasn’t too hard to add filters to a GQL schema. The situations in which GraphQL really shined through were the cases in which we fetched too many fields, not too many objects. With REST, we were sending all the data that was possibly needed. Creating a generic endpoint forced us to pack it with all the data and associations used on the platform.
With GQL, we were able to pick the fields. Instead of fetching 20+ fields that required loading several database tables, we selected just the three to five fields that were needed. That allowed us to remove sudden spikes of billing usage during platform deployments because some of those queries were used by elastic search reindexing jobs run during the deploy. As a positive side effect, it made deployments faster and more reliable.
The Fastest Request Is the One You Don’t Make
We limited the number of fetched objects and the amount of data packed into every object. What else could we do? Maybe not fetch the data at all?
We noticed another area with room for improvement: We were using a creation date of the last billing record in the platform frequently and every time, we were calling billing to fetch it. We decided that instead of fetching it synchronously every time it was needed, we could cache it based on events sent from billing.
We planned ahead, prepared tasks (four to five of them), and started working to have it done as soon as possible, as those requests were generating a significant load. We had two weeks of work ahead of us.
Fortunately, not long after we started, we took a second look at the problem and realized that we could use data that was already on the platform but in a different form. Instead of adding new tables to cache data from Kafka, we spent a couple days comparing data from the billing and the platform. We also consulted domain experts as to whether we could use platform data.
Finally, we replaced the remote call with a DB query. That was a massive win from both performance and workload standpoints. We also saved more than a week of development time.
Distributing the Load
We were implementing and deploying those optimizations one by one, yet there were still cases when billing responded with
429 Too Many Requests. We could have increased the request limit on Nginx but we wanted to understand the issue better, as it was a hint that the communication is not behaving as expected. As you may recall, we could afford to have those errors on production, as they were not visible to end-users (because of the fallback to a direct call).
The error occurred every Sunday, when the platform schedules reminders for talent network members regarding overdue timesheets. To send out the reminders, a job fetches billing data for relevant products, which includes thousands of records. The first thing we did to optimize it was batching and preloading billing data, and fetching only the required fields. Both are well-known tricks, so we won’t go into detail here.
We deployed and waited for the following Sunday. We were confident that we’d fixed the problem. However, on Sunday, the error resurfaced.
The billing service was called not only during scheduling but also when a reminder was sent to a network member. The reminders are sent in separate background jobs (using Sidekiq), so preloading was out of the question. Initially, we had assumed it would not be a problem because not every product needed a reminder and because reminders are all sent at once. The reminders are scheduled for 5 PM in the time zone of the network member. We missed an important detail, though: Our members are not distributed across time zones uniformly.
We were scheduling reminders to thousands of network members, about 25% of which live in one time zone. About 15% live in the second-most-populous time zone. As the clock ticked 5 PM in those time zones, we had to send hundreds of reminders at once. That meant a burst of hundreds of requests to the billing service, which was more than the service could handle.
It wasn’t possible to preload billing data because reminders are scheduled in independent jobs. We couldn’t fetch fewer fields from billing, as we had already optimized that number. Moving network members to less-populous time zones was out of the question, as well. So what did we do? We moved the reminders, just a little bit.
We added jitter to the time when reminders were scheduled to avoid a situation in which all reminders would be sent at the exact same time. Instead of scheduling at 5 PM sharp, we scheduled them within a range of two minutes, between 5:59 PM and 6:01 PM.
We deployed the service and waited for following Sunday, confident that we’d finally fixed the problem. Unfortunately, on Sunday, the error appeared again.
We were puzzled. According to our calculations, the requests should have been spread over a two-minute period, which meant we’d have, at most, two requests per second. That wasn’t something the service couldn’t handle. We analyzed the logs and timings of billing requests and we realized that our jitter implementation didn’t work, so the requests were still appearing in a tight group.
What caused that behavior? It was the way Sidekiq implements scheduling. It polls redis every 10–15 seconds and because of that, it can’t deliver one-second resolution. To achieve a uniform distribution of requests, we used
Sidekiq::Limiter – a class provided by Sidekiq Enterprise. We employed the window limiter that allowed eight requests for a moving one-second window. We chose that value because we had an Nginx limit of 10 requests per second on billing. We kept the jitter code because it provided coarse-grained request dispersion: it distributed Sidekiq jobs over a period of two minutes. Then Sidekiq Limiter was used to ensure that each group of jobs was processed without breaking the defined threshold.
Once again, we deployed it and waited for Sunday. We were confident that we’d finally fixed the problem — and we did. The error vanished.
API Optimization: Nihil Novi Sub Sole
I believe you weren’t surprised by the solutions we employed. Batching, server-side filtering, sending only required fields, and rate-limiting aren’t novel techniques. Experienced software engineers have undoubtedly used them in different contexts.
Preloading to avoid N+1? We have it in every ORM. Hash joins? Even MySQL has them now. Underfetching?
SELECT * vs.
SELECT field is a known trick. Spreading the load? It is not a new concept either.
So why did I write this article? Why didn’t we do it right from the beginning? As usual, the context is key. Many of those techniques looked familiar only after we implemented them or only when we noticed a production problem that needed to be solved, not when we stared at the code.
There were several possible explanations for that. Most of the time, we were trying to do the simplest thing that could work to avoid over-engineering. We started with a boring REST solution and only then moved to GQL. We deployed changes behind a feature flag, monitored how everything behaved with a fraction of the traffic, and applied improvements based on real-world data.
One of our discoveries was that performance degradation is easy to overlook when refactoring (and extraction can be treated as a significant refactoring). Adding a strict boundary meant we cut the ties that were added to optimize the code. It wasn’t apparent, though, until we measured performance. Lastly, in some cases, we couldn’t reproduce production traffic in the development environment.
We strived to have a small surface of a universal HTTP API of the billing service. As a result, we got a bunch of universal endpoints/queries that were carrying data needed in different use cases. And that meant that in many use cases, most of the data was useless. It’s a bit of a tradeoff between DRY and YAGNI: With DRY, we have only one endpoint/query returning billing records while with YAGNI, we end up with unused data in the endpoint that only harms performance.
We also noticed another tradeoff when discussing jitter with the billing team. From the client (platform) point of view, every request should get a response when the platform needs it. Performance issues and server overload should be hidden behind the abstraction of the billing service. From the billing service point of view, we need to find ways to make clients aware of server performance characteristics to withstand the load.
Again, nothing here is novel or groundbreaking. It’s about identifying known patterns in different contexts and understanding the trade-offs introduced by the changes. We’ve learned that the hard way and we hope that we’ve spared you from repeating our mistakes. Instead of repeating our mistakes, you will no doubt make mistakes of your own and learn from them.
Special thanks to my colleagues and teammates who participated in our efforts:
Understanding the basics
An external API is a client- or UI-facing API. An internal API is used for communication between services.
GraphQL allows the implementation of a flexible API layer. It supports scoping and grouping data so that the client fetches only the data that is needed and can retrieve it in a single request to the server.
They have different usage patterns and cannot be compared directly. In our case, GraphQL proved to be more suitable but your mileage may vary.
It depends on the API. Preloading and caching data, limiting data fetched from the server, adding jitter, and rate-limiting can be used to optimize the internal API. | https://www.toptal.com/graphql/graphql-internal-api-optimization | CC-MAIN-2022-27 | refinedweb | 2,942 | 64.41 |
Using the New Extension Methods Feature in C# 3.0
Extension Method Invocations
Table 1 shows how the method invocations are modified when the code is compiled.
Table 1. Method Invocation Modifications at Compile Time
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 42 (0x2a) .maxstack 1 .locals init ([0] string s, [1] int32 i, [2] int32 j) IL_0000: nop IL_0001: ldstr "9" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call int32 ExtensionMethods.EMClass:: ToInt32Ext(string) IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: call void [mscorlib]System.Console::WriteLine(int32) IL_0014: nop IL_0015: ldloc.0 IL_0016: call int32 ExtensionMethods.EMClass:: ToInt32Static(string) IL_001b: stloc.2 IL_001c: ldloc.2 IL_001d: call void [mscorlib]System.Console::WriteLine(int32) IL_0022: nop IL_0023: call string [mscorlib]System.Console::ReadLine() IL_0028: pop IL_0029: ret } // end of method Program::Main
The code marked in red indicates that the above method conversion (expr . identifier ( ) <--> identifier (expr) ) occurred.
So, when you call int i = s.ToInt32Ext();, the compiler internals convert it to int i = EMClass.ToInt32Ext(s);. Then, the rewritten form is processed as a static method invocation.
The identifier is resolved in the following order:
- The closest enclosing namespace declaration
- Each subsequent enclosing namespace declaration
- The containing compilation unit
The following is the order of precedence for methods in descending order:
- Instance methods
- Extension methods within the same namespace
- Extension methods outside the current namespace
Why Use Extension Methods?
You may be asking, "Why should I use extension methods when I have the regular static and instance methods?" Well, the answer simply is utter convenience. Let me explain with an example. Suppose you developed a library of functions over a period of years. Now, when someone wants to use that function library, the consumer must know the class name that defines the desired static method. Something like the following, for example:
a = MyLibraryClass.
At this point, IntelliSense will pop in and give you the names of the available functions. You just have to pick the one you need.
You then type your desired methods and pass the necessary argument:
a = MyLibraryClass.DesiredFunction(strName)
With this approach, you need to know beforehand which library contains your desired function and its name. With extension methods, it is more natural—something like the following:
a = strName.
At this point, IntelliSense pops up and shows which extension methods are available. You simply type the extension method you want:
a = strName.DesiredFunction()
No arguments are needed to identity the data type on which this method needs to work.
Invoke Static Methods on Object Instances
Extension methods provide a new mechanism for invoking static methods on object instances. But, as per C# 3.0 language specifications, extension methods are less discoverable and more limited in functionality than instance methods. Therefore, you should use extension methods sparingly, only where instance methods are not feasible.
Also, C# 3.0 is not yet an official release, so its specifications are not finalized. Therefore, the syntax is liable to change.
References
-
- Eric Lippert, Microsoft Developer, Visual C# Team.
Download the Code
You download the source code for this article here.<< | https://www.developer.com/net/csharp/article.php/10918_3592216_2/Using-the-New-Extension-Methods-Feature-in-C-30.htm | CC-MAIN-2018-26 | refinedweb | 518 | 52.36 |
Building web chat with ReactJS and Firebase
Previously, I had an article showing how to make a chat app with Flutter at here.
Today, I’ll do the same things, but with ReactJS to build a web chat, then we can send messages between app and web to see interest things.
This web also has the following features:
- Chat one to one with other users (send text, image, and sticker).
- Update profile and avatar.
Video demo
I also deployed this project for testing at here:
flutterchatdemo.firebaseapp.com
Let’s get started
1. Creating the project on Firebase
After creating the project, at Project Overview, click Add app and select web platform.
Start the Cloud Firestore and Storage
Then enable sign-in method with Google
Now you’re done this step, don’t need to add or init any data manually at Firebase.
Rules at Storage:
Rules at Database:
2. Installing plugins
Run
npm install --save firebase to install firebase package, it helps us use login, database, and storage service.
Also install
moment,
react-loading,
react-toastify and
react-router-dom to handle date time, show loading, toast and navigate (check out my
package.json for more).
3. Configuring firebase and define web app flow
Create a file
MyFirebase.js to config and use some firebase services
The web app will have 3 screens, all of them are inside
root.js then we can use
react-router-dom to navigate between these screens.
- Login screen (auth by google).
- Main screen (includes 3 components, list user, welcome board and chat board).
- Profile screen.
4. Rendering root screen with navigation
We’ll use
import { BrowserRouter, Switch, Route } from 'react-router-dom' to navigate between screens.
Not like React Native (just call show() is enough), toast at ReactJS need a component (ToastContainer) inside render function, so we should render it at root, then all child screens can use it and catch the case show toast at this screen, but immediately navigate to next screen (eg: toast login success).
5. Rendering login screen
If authenticate success, the variable result giving some info like displayName, email, photoURL,… and after that, we should check if this user is new? if true, we write to the database. The last thing to do is save to localStorage (no matter new or not) for easier to use later.
Notice that we should always check login at this screen since the user re-access this page, auto navigate them to the main screen instead require login.
6. Rendering main screen
Notice in this screen, we have 3 components, list user at the left, and welcome board/chat board at the right. When a user navigates to this screen at first, since they’re not chatting with any user, we should show welcome board, and when they choose another user to start the conversation, we should render chat board with loading that conversation’s history.
This screen also needs to check login to prevent invalid navigate since the user can type exact path URL to browser’s address bar.
Rendering list user
If logged in, we load list user and render them. A thing interesting at here is ReactJS doesn’t have listview built-in or something similar (I worked with RN before and quite surprise with it). So we need to loop an array (list users) and render each item by ourselves, then add all item views to an array view (viewListUser) and return it, so we just call this function at render is fine.
Rendering history messages
The welcome board is just simple UI, so I’ll ignore it to keep a short article, check out my source code at
WelcomeBoard.js.
When the user chooses other people, let’s load the history and render them at initial. Notice that
onSnapshot at here will load all child node first like the docs said, so we don’t need to separate load history and listener into 2 parts..
So at user A or B, they both read and write data at the same Firebase node.
The variable
this.removeListener be called to remove listening new data added at the current node when the current user leave this screen or switching to chat with other users.
About rendering list messages, it’s just some check left and right message with CSS style, please refer
Chatboard.js for more details.
Handling input form
The object we can send is image, sticker, and text. Notice that we need a field like a type to detect it is the normal message, image or sticker to render appropriately.
With image, first we upload it (it has a callback with return URL after upload success), so the message content should be the URL. Then just using
<img/> to render it.
Filter file type to only accepting image, but we need to check the prefix file type too since
accept="image/*" only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented.
With sticker, the message content should be the file name (we stored local these stickers) and when render it, check if file name match? If true, use
<img/> to show this sticker.
Sending messages
When the user clicks an icon or hit enter to send a message, image or sticker, we need to check if the content is not empty, if true, write new data to the node appropriately. When add data success,
onSnapshot will catch the event and render to the list.
Handling logout
Nothing special here except remember clear the localStorage to prevent user use exactly path URL to go main screen without logged in (I use local data to check user logged in or not).
7. Rendering profile screen
You can add more field if you would like, but in this demo scope, I just use name, description, and avatar for quickly.
First, we need to check login like the main screen to prevent the user goes to this screen directly by path without login.
When the user chooses a file from their computer, we assign this file to a variable name
this.newAvatar since we don’t know user update their info with or without a new avatar, if they update avatar too, first we need upload this file, then get URL and add to user node this info.
After updating info success, we should save it to local for easier to use later.
Cloud Firestore structure
I can’t public my firebase server, so just giving a little information to help you imagine the structure.
Congratulations
Now we are done 👏
If you guys have any questions. Please feedback so we can discuss and improve each other.
My source code is available at
duytq94/reactjs-chat-demo
This is the demo for web chat by ReactJS. Contribute to duytq94/reactjs-chat-demo development by creating an account on…
github.com
Would like to pack this website to a desktop app, please read
Bundling your React web to a desktop app with Electron
A few days ago, I had a chance to build a small desktop app in my job. The goal is how to implement it in a simple and…
medium.com
Goodbye and see you again 👋 | https://medium.com/@duytq94/building-web-chat-with-reactjs-and-firebase-e7f9654b661?source=post_page-----9eaa7f41782e---------------------- | CC-MAIN-2019-35 | refinedweb | 1,208 | 68.7 |
This post is to provide some tips for people who may or may not have been using the .NET Framework SDK. Most of these tips apply to the .NET Framework SDK v2.0 Beta, but some will also work with previous versions.
1. Most people do not know this, but the SDK is included with Visual Studio. Look at your start menu you will see a Microsoft .NET Framework SDK program group.
2. Whidbey Tip: We have added a SDK command prompt that will set all of the environment variables you need to build basic .NET Framework applications. Once you start using the command line to do you work you will learn that you can't live without it.
3. Debugger: The SDK includes a lightweight graphical debugger called DbgCLR. There is a shortcut to this in the SDK v2.0 Start menu. If you ever need to debug something, but don't want to install VS this is the way to go. Just install the SDK tools only and you have everything you need.
4. C++ compilers. The .NET Framework SDK includes cl.exe, link.exe, and vcbuild so that you can build C++ applications.
5. Mage.exe and PermCalc.exe. These are new tools that you can use to generate click once manifest files. Mage has a GUI that is pretty easy to use and will help you create the manifest files that click once needs. PermCalc.exe is a little bit hard to find. It's in the VS directory. Just type PermCalc in the SDK command prompt and you will get the details on it.
6. ILDasm.exe. I had built .NET Framework applications before coming to work for Microsoft and never user Ildasm, but since someone on my team introduced me to this tool I have found it extremely useful. Run Ildasm and open up a managed assembly of exe. You can then browse through all of the namespaces, classes, properties, methods, etc. It is extremely helpful when you are dealing with poorly documented software.
If you are an avid SDK user let me know. I'm looking for customers to gather feedback from, invite into beta programs, and recognize as MVP's. | http://blogs.msdn.com/jbower/archive/2004/07/22/191631.aspx | crawl-002 | refinedweb | 368 | 76.72 |
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?
At the moment I do:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
You can't get any better than that.
After all, any solution will have to read the entire file, figure out how many
\n you have, and return that result.
Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't use unnecessary memory, but it looks like you have that covered. | https://codedump.io/share/Tqb8bdVbO67o/1/how-to-get-line-count-cheaply-in-python | CC-MAIN-2017-09 | refinedweb | 128 | 76.56 |
Details
Description
There should be the option of using container-based autnetication.
Here are some ideas from an old post in the mailing list:
Been thinking a lot about container based authentication - primarily,
because of my interest in the CAS integration which is necessary for
an OFBiz integration (search for OFBizCasAuthenticationHandler.java
class for details)
Here a few thoughts.
in J2EE, the way to get the user is via the following code:
java.security.Principal principal = request.getUserPrincipal();
if(principal != null)
If we used the UserPwdAuthModule in UserAuth.scala as a basis, we
could use the following code combined with the code above to get the
user:
user <- UserAuth.find(By(UserAuth.authKey, name),
By(UserAuth.authType,
moduleName)).flatMap(_.user.obj) or
User.find(By(User.nickname, name))
We could take use the S object in lift to get the request and then get
the UserPrincipal. Probably with "S.request"
The only I don't know is how to make this Container-based authmodule
be the default that works without a UI that implicitly calls it.
One idea is to remove the following lines from Boot.scala
UserAuth.register(UserPwdAuthModule)
UserAuth.register(OpenIDAuthModule)
and replace them with
UserAuth.register(ContaionerAuthModule)
---------------
object ContainerAuthModule extends AuthModule {
def moduleName: String = "upw"
def performInit(): Unit = {
LiftRules.dispatch.append {
case Req("authentication" :: "login" :: Nil, _, PostRequest) =>
val from = S.referer openOr "/"
(for {
java.security.Principal principal = S.Request.getUserPrincipal();
if(principal != null)
Activity
Moving to release 1.2 (tentative)
It's possible to use BASIC(DIGEST) or FORM type of container-managed authentication. I have some questions:
1. Is it ok if container-managed authentication will be associated with specific URL, for example 'cm/login'? It then will be specified in web.xml as a secured resource. When user is directed to this URL, container-managed authentication will first take place. After that, we will be able to get user credentials and store user information in session in a new AuthModule an according with example from Lift Wiki above.
2. What user-related information should be stored in ESME database? Usually container-managed authentication retreives user data from some external source such an LDAP. I think it will also be possible to get role (group) information via Lift LDAP API when it will be available.
Regarding 1) This is fine to hook the container-based authentication to a particular URL. A first test could be to use MemoryRealm in Tomcat.
Regarding 2) LDAP integration would be ideal to get roles and / or provide authentication. I looked at the LDAP support in Lift but it is tightly linked to the MegaProtoUser and I didn't know how to separate them.
I've implemented very simple variant of container-managed authentication using an example from Lift Wiki. When user access URL, it's redirected to login form (sorry, I've added primitive JSP containing only login/password fields) by container. After user fills and submits this form, credentials are checked by container and in case successful authentication and authorization it's possible to save user info to/retreive user info from DB in new AuthModule. Right now only username (nickname) is saved. Of course role list and additional user's attributes should be retreived from external source (LDAP).
I used org.mortbay.jetty.security.HashUserRealm (it is configured in maven-jetty-plugin) which reads username/password/role mappings from plaintext file: jetty-login.properties, it should be placed into the root dir of server module. Primitive login/error JSP page cm_login.jsp should be placed into webapp dir. Other modified files are web.xml, Boot.scala and UserAuth.scala where module is registered and defined. I've attached all these files to current issue.
It would be great if someone of our more experienced developers checks this auth module - it might have been implemented completly wrong.
What things can we apply in a patch and what things would go into documentation.
I assume that cm_log.jsp, web.xml, jetty-login.properties go into documentation
Boot.scala + UserAuth.scala go into a patch
Have you tried using Tomcat?
It's OK from my point of view. One note: pom.xml and ESMEProject.scala should include servlet-api compile-time dependency.
Haven't tried with Tomcat yet. Next thing I want to try - net.liftweb.ldap.LDAPVendor and whether it's possible to retreive groups/attributes with it.
Integrated in ESME #546 (See)
Initial implementation for
ESME-214: Add container-based authentication.
Tested on Tomcat 6 with user-password-role mapping in tomcat-users.xml file and MemoryRealm in server.xml config file. I've been able to successfully login, but user home page has been broken.
I've modified new auth module, in case authentication performed by container via LDAP server, it's possible now to retreive additional user attributes from LDAP server (if ldap integration is enabled in ESMELdap.properties file, otherwise authentication performed by container via plain text (see jetty-login.properties and pom.xml for Jetty) or xml file (see server_plain.xml and tomcat-users.xml) ). I tested LDAP integration of ESME app (delpoyed on Tomcat 6) with both 389 Directory Server (Red Hat Directory Server) and MS Active Directory (I've included sample Tomcat's server.xml conf files for 389 and AD as well as sample ESMELdap.properties for both directory servers).
You are welcome to review code and test it in your environment.
This would be cool if we could use the apache ldap....
If you wish, I can test it on Apache Directory Server as well.
That would be cool
> >you've got to start blogging about this stuff ;>
How about setting up a separate Apache-only instance on our test VM?
Good idea: ESME-Tomcat -Apache-Directory, etc
I've deployed Apache Directory Server on local machine and tested it. Since server.xml and ESMELdap.properties files are essentially the same for all directory server, I've left my files only for ADS as an example. Hopefully, I'll write blog entry on this weekend.
Integrated in ESME #551 (See)
ESME-214: set 'default' flag to false for container-managed authentication module. Renamed key in ldap property file.
Here are details how to do this: | https://issues.apache.org/jira/browse/ESME-214?focusedCommentId=13003398&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-11 | refinedweb | 1,036 | 51.85 |
Fight the global warming: compile your C# apps ahead of time
Ahead of time compilation (AOT) has been part of .NET ever since v1 of .NET framework came out. .NET framework had a technology called NGEN that allowed pre-generating native code and data structures at the time of installing a .NET program into the global assembly cache. NGEN created a cache of code and data structures the runtime would require to run the installed program. The cache was not complete — the runtime would fall back to doing just in time (JIT) compilation and loading when needed, but a great chunk of typical apps could be compiled ahead of time this way.
The Mono runtime (synonym for Xamarin for many) then stretched this caching approach further, making it possible to run without any just in time code generation at runtime. Mono achieved this by making more investments into pre-generating code for generics and various stubs that NGEN left out.
While this can be called ahead of time compilation in a way, it is quite different from how C, Go, Swift, or Rust are compiled ahead of time. The implementation of AOT compilation in the mainstream .NET runtimes leaves a lot of the AOT benefits on the table. This article will explore those benefits.
JIT vs AOT
A common misconception is that the only difference between just-in-time and ahead-of-time runtimes is in the timing of native code generation. A JIT-compiling runtime will generate native code on demand — when your app is deployed and running in the target environment. An AOT-compiling runtime pre-generates native code as part of the app build.
The source of this misconception lies in how the mainstream runtimes implemented ahead of time compilation in the past: add native code to a .NET assembly and call it good. An AOT compiler can do more than that.
Before we dig into the details, let’s look at the life of a C# app.
.NET application lifecycle
When the C# compiler compiles your source code, it generates IL assemblies. An IL assembly is an EXE or DLL file whose contents is split in two categories: code of your app in CIL (machine code for an abstract processor), and metadata about your code (names of types, their base class, interfaces, methods, fields, etc.).
The metadata looks very much like a set of database tables with information about the types, fields and methods defined within the module, but also references to types, fields and methods defined in other IL modules. Following schematic captures the gist of it:
The advantages of the IL format are twofold:
- It’s independent of the hardware or OS the code will run on, and
- It has great version resiliency
The version resiliency comes from the fact that CIL is a pretty high level intermediate language — it has instructions such as “load field X on type Y”, or “call method U on type V”. The details of what these instructions perform is encoded in the metadata.
The richness of the metadata also means that a type can declare it derives from a type named “List” in namespace “System.Collections” in assembly “System.Collections” and the resolution of what that means will happen at runtime, by looking up the name in the “System.Collections” assembly. The definition of the base type can change (e.g. new methods and fields can be added), without requiring recompilation of an assembly that defines a type deriving from it.
The IL format captures your program at a very high level. If you ever used a tool like ILSpy, you probably saw that it can generate a near-perfect C# source code out of IL assemblies. IL format is close to being just a binary encoding of the source file.
What’s missing in an IL assembly
It’s also interesting to have a look at what an IL assembly does not have. You will not find these things in an IL assembly generated by the C# compiler:
- Machine code for a specific CPU architecture: the IL instructions cannot be directly executed on any processor. They have to be interpreted or compiled.
- Data structures that would allow efficient execution of the program.
The second point might require a bit of explanation. While knowing the list of fields and their names on a type is nice, when we want to e.g. allocate a new instance of this type on the GC heap (using the “new” keyword in C#), we need to know the size of the type in bytes. This can be calculated by going over the list of fields, computing the sizes of the field’s types (potentially recursively), and doing the same for the base classes. This is a lot of work — a lot of it involves looking up names of things across many assemblies.
A just-in-time compiled .NET runtime will typically have a step called “type loading” where it builds an alternative representation of each type into a runtime allocated data structure. At that stage it will compute the information necessary to effectively execute the program: besides the size of the type, it will include information such as the list of offsets within instances of the given type that contain GC pointers (needed for the GC), or a table of virtual methods implemented by the type (needed for virtual calls). The runtime allocated data structure will also have a pointer back to the IL metadata to access some rarely used things.
Not all AOT is equal
From this, it’s quite clear that it’s not just the code, but also the representation of metadata in an IL assembly that is different from what we need at runtime. The file format of the IL assembly is not what we would come up with if AOT compilation was our objective. None of the traditionally AOT compiled languages represent their data structures this way.
The fact that the mainstream .NET runtimes use the IL format metadata even in AOT mode makes sense from an evolutionary perspective: these runtimes are built around the concepts represented in the IL metadata because they started as just-in-time runtimes. Building a cache for the most expensive thing (code) is a logical evolutionary step that doesn’t require a major overhaul of the runtime.
Keeping the IL format comes with costs though. The IL file formats are built for hardware independency and version resilience. By pre-generating code ahead of time, we’re giving up on these aspects, so why are we keeping the existing formats?
When the .NET runtime team started looking in this direction some 11 years ago for the Redhawk project, it was clear that evolving the existing CLR runtime into a form that is optimized for AOT would be prohibitively expensive. A new runtime optimized for AOT was born.
A .NET Runtime for AOT
Redhawk project picked up reusable parts of the CLR (such as the garbage collector — see references to FEATURE_REDHAWK in the CoreCLR’s GC source code) and built a minimal runtime around it. This minimal runtime built for the Redhawk project later became the basis of .NET Native and CoreRT. You can still find references to Redhawk in the CoreRT source tree on GitHub.
When .NET Native was announced, it brought 60% gains in startup time over NGEN. These startup time improvements were made possible by using a runtime and file formats optimized for ahead of time compilation.
Remember the schematic for how programs are represented in an IL assembly? This is how they look like in CoreRT after ahead of time compilation:
You’ll notice that things like the list of methods on a type and names of types no longer exist in this format. This is because they’re not actually needed when the program is compiled ahead of time. The real (non-abstract) CPUs only care about code — they don’t care what type a method belongs to. They also don’t care how many fields a type has — they just access a piece of memory at a particular offset.
The minimal data structures in the schematic — such as the EEType structure describing the System.String type, contain the minimal amount of data required to run a .NET program. E.g. the RelatedType field on the EEType makes it possible to cast an instance of System.String to System.Object. Vtable slots support virtual method calls. BaseSize supports object allocation and garbage collection.
Decompiling a program in this representation into its source form poses the same level of complexity as e.g. decompiling C++.
The data structures that this minimal .NET runtime operates on are in fact very similar to the data structures a C++ runtime library would operate on — and so is the size of the runtime. In the minimal configuration, CoreRT can compile to a ~400 kB self-contained executable that includes the full runtime and garbage collector (the size data is for x64 — the 32bit targets can actually be smaller than that). The GC used in this configuration is still the same GC that handles gigabyte workloads in Azure.
Startup time
The main performance benefit of ahead of time compilation comes in the form of startup time. A just-in-time runtime (or an AOT runtime built around IL format) will spend considerable amount of time doing things that support running your program, but not actually running your code. The startup path will look something like this:
The 60% startup time improvement that was observed for Universal Windows Apps with .NET Native translates to other workload types as well. Here is how startup times look like for ASP.NET with a benchmark the CoreCLR performance team uses:
Now, startup time doesn’t matter much if your process is long-running — like a web server. It starts to matter when end users are exposed to the delay: startup time is the time when users stare at the hourglass cursor in a desktop app, app load splash screen in a mobile app, or empty webpage in a web app.
Time to first user instruction
An interesting metric is how long it takes from the process creation time until the first line of your Main() executes. A lot of things need to happen before a runtime can execute the first line of your code. This is actually quite simple to measure if you only need a ballpark number — place a call to the times (on Linux) or GetProcessTimes (on Windows) API as the first line of your Main().
This API gives you information about how much work the framework did before it got around to executing the first line of your program. For languages like C, this number will typically be 0 — the first line of your program will run before the OS gets the chance to update the statistics. If you’re building command line apps you’ll want this number to be 0. These numbers add up.
Here’s how time to first instruction looks like for various .NET runtimes:
The number for CoreRT is zero. Your app starts as fast as an app written in C.
Compilation output sizes
Big difference between JIT and AOT runtimes is in sizes of the self-contained deployments. CoreRT benefits from the fact that most of what is considered “the runtime” in other .NET runtimes (and gets written in C/C++), is actually written in C# on CoreRT. Managed code can be linked away if the app doesn’t use it. For traditional runtimes, the runtime part represents fixed cost that cannot be tailored for each app. Thanks to this setup, AOT deployments can be significantly smaller:
What about reflection?
Things get interesting with reflection. While the CPU doesn’t care how you name your methods and an AOT compiler is free not to emit this information, the reflection APIs make it possible to locate any type, method or field by name, and provide access to extra information about these entities, such as the signature of the method, or names of the method parameters.
The CoreRT compiler solves this problem by storing reflection information on the side — the information is not necessary to run the program, and the emission of it is optional. We can call this extra data “reflection tax”. An AOT compiler can let you avoid paying it if you’re not using it.
Without the reflection data, the reflection experience becomes limited: one can still use typeof, call Object.GetType(), inspect base types and implemented interfaces (because the runtime still needs it to make casting work), but list of methods and fields, or the type names become invisible.
Reflection tax is an unexplored territory in .NET: since neither CoreCLR nor Mono can operate without IL metadata, omitting the metadata is not an option for mainstream runtimes. But this might be the door to sub-megabyte deployment sizes that is especially important for targets like WebAssembly.
Traditionally ahead of time compiled languages don’t have the unrestricted reflection that .NET provides and they prove that you can get work done without making everything available for reflection. A lot of things that people use reflection for these days (like serialization and deserialization) can be done without reflection — in a build task, at compile time. Doing this in a build task actually provides benefits for just-in-time runtimes too because reflection is slow.
How about dynamic code?
.NET provides several facilities that let you generate new code at runtime. Be it Reflection.Emit, Assembly.LoadFrom, or even something as simple as MakeGenericType and MakeGenericMethod. This poses a challenge for an AOT runtime because these things cannot be done ahead of time by definition (or at least cannot be done for all programs).
This is where the AOT runtime is forced to do just-in-time loading as well. The important things is that in an AOT-first runtime, one only needs to pay the just-in-time costs if they explicitly use the dynamic features: don’t call the dynamic APIs, and there’s no runtime overhead.
CoreRT currently has a prototype interpreter and a prototype JIT showing that dynamic code is not a limiting factor for a runtime designed for AOT.
So what is CoreRT anyway?
CoreRT is an experimental cross-platform open source .NET runtime specialized for AOT compilation. While CoreRT (as a whole) has an “experimental” label, many of the parts of CoreRT are shipping in supported products. CoreRT takes parts of .NET Native and parts of CoreCLR and puts them together. The rough percentage of things CoreRT shares with CoreCLR and .NET Native are in the picture to the left.
Thanks to this setup, CoreRT gets improved every time someone improves CoreLib in CoreCLR, or implements a new optimization in RyuJIT.
If you would like to give CoreRT a try, you can publish your .NET Core app with CoreRT by simply adding a new NuGet package reference. Instructions for that are here.
JIT is to AOT as gasoline engine is to an electric engine
The performance characteristics of ahead of time compiled and just in time compiled runtimes can be compared to the characteristics of an electric and gasoline engine in a car.
- Electric motors generate motion, not heat. A just-in-time compiled .NET app will spend considerable amount of resources doing things that support running your code, but not actually running your code.
- At lower speed, electric motors deliver more torque than gasoline engines. This makes them much better at acceleration. In an AOT compiled app, peak throughput is available immediately and your app is running at full speed right away. Gasoline engine will outperform an electric engine eventually, and so will a high-octane, just-in-time compiled runtime.
- Electric motors are simpler. If one looks at a high-octane, just-in-time compiled runtime with dynamic recompilation, tiered JITting, and on stack replacement, lots of complexities start to show up. These complexities make things harder for the developer of the runtime, but also for the user of the runtime. The flavor of the native code running in production depends on the dynamic tuning the runtime performed based on the past characteristics of the program.
Both gasoline and electric engines have their use and place. It’s nice to have options available and it’s good that .NET has them. | https://medium.com/@MStrehovsky/fight-the-global-warming-compile-your-c-apps-ahead-of-time-9997e953645b?__scribleNoAutoLoadToolbar=true | CC-MAIN-2019-22 | refinedweb | 2,729 | 62.17 |
Pythonic in-memory MapReduce.
Experimental Pythonic MapReduce inspired by Spotify’s luigi framework.
Currently there are two MapReduce implementations, one that includes sorting and one that does not. The example below would not benefit from sorting so we can take advantage of the inherent optimization of not sorting. The API is the same but tinymr.memory.MRSerial() sorts after partitioning and again between the reducer() and final_reducer().
import json import re import sys from tinymr.memory import MRSerial class WordCount(MRSerial): def __init__(self): self.pattern = re.compile('[\W_]+') def mapper(self, item): for word in item.split(): word = self.pattern.sub('', word) if word: yield word.lower(), 1 def reducer(self, key, values): yield key, sum(values) def final_reducer(self, pairs): return {k: tuple(v)[0] for k, v in pairs} wc = WordCount() with open('LICENSE.txt') as f: out = wc(f) print(json.dumps(out, indent=4, sort_keys=True))
Truncated output:
{ "a": 1, "above": 2, "advised": 1, "all": 1, "and": 8, "andor": 1 }
$ git clone $ cd tinymr $ pip install -e .\[dev\] $ py.test tests --cov tinymr --cov-report term-missing
See LICENSE.txt
See CHANGES.md
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/tinymr/ | CC-MAIN-2017-30 | refinedweb | 207 | 53.27 |
?
I just sent you an email!
Can't wait for the release version!
Bluetooth support sounds awesome!
- wradcliffe
I have a couple of interesting Bluetooth LE peripherals in hand right now.
A general purpose Arduino based microcontroller.
Part of the big Internet of Things development push. Would be cool to be able to access it from Pythonista.
MIDI interface
I could test accessing these things using your module if that would help. I was just about to ask you if you would consider adding simple support for Core MIDI using this ...
I know that Apple just added official support for Bluetooth LE wireless MIDI in IOS8 so accessing this type of peripheral via CoreMIDI may still be the best approach.
- wradcliffe
Curious to know what the Bluetooth LE support is for. I have a couple of very interesting peripherals that each require a speciall app to be installed on iOS in order to function. One is for MIDI and the other is a general purpose Arduino style computer.
How does testflight work ... Does the overwrite existing pythonista install? Or it creates a special version?
Presumably this rewuire ios8? Iirc testflight only works with 8+?
J
- LawAbidingCactus
- LawAbidingCactus
@JonB, to my knowledge, it simply installs a provisioning profile separate from the official Pythonista install.
I've just sent out invites to everyone who's asked so far, and I have plenty of slots left.
@JonB When you install the beta, it overwrites the App Store version, but it should keep your data, just like a regular update.
just reading the release notes is awesome. I immediately tried some of the stuff and just have to say WOW. Just one question about the beta testing: Open comments about the the beta here or where to sent my remarks?
Tom
As long as you make it clear that a thread is beta-related, it's totally fine with me to discuss it here.
I've just submitted a new build with a few fixes – most importantly, the
dialogsmodule should actually work now. It'll be available in a few hours (it takes a while for iTunes Connect to process new uploads).
There's also a new
requestsor
urllib), if you want more control.
Bug: passing variables into
console.login_alertdoesn't work and causes the command to hang (was working in stable).
@hyshai Thanks, I'll look into that. So far, I can't reproduce the hanging, but it definitely doesn't work correctly (it always behaves as if it was cancelled).
Just started playing with it, truly great. Also noticed that sheet view doesn't have a fixed width and height now, and it responds to the views set size. Wasn't in the release notes so I'm not sure if this was meant to be there.
@omz I narrowed it down. It has nothing to do with a variable. Multiple prompts are the issue e.g.
import console, keychain keychain.get_password('test', 'test') #requires keychain.master_password which has a prompt console.login_alert('hello') # this will never be called and the script hangs
another example
import console console.login_alert('hello') console.login_alert('goodbye') # this will never be called but the script exits silently
Is this possibly related to the bug of not showing the keyboard automatically when there's an input prompt (specifically the
keychain.master_passwordprompt)?
This sounds interesting, looking forward to the update. Sent you an e-mail.
Does TestFlight require iOS 8? I have an oldish iPhone that can only run iOS 7 that I might be able to test with as well.
I think TestFlight requires iOS 8.
How do you get the text entered into a text dialog?
It's the return value of the
text_dialogfunction.
Just mailed you my apple id. Would love to test out BTLE.
I assume the appex module you teased on Twitter is not integrated/activated in this Beta? Anyway, it's pretty cool you're doing this and I am happy to test the Twitter integration :) | https://forum.omz-software.com/topic/1946/pythonista-1-6-beta | CC-MAIN-2020-10 | refinedweb | 664 | 68.06 |
Felipe Lessa wrote: > apfelmus wrote: >> The type of contPromptM is even more general than that: >> >> casePromptOf' :: (r -> f b) >> -> (forall a,b. p a -> (a -> f b) -> f b) >> -> Prompt p r -> f b >> casePromptOf' done cont (PromptDone r) = done r >> casePromptOf' done cont (Prompt p c ) = cont p (casePromptOf' done cont . c) > > (I guess the forall b inside 'cont' is a typo?) No, it's intentional and not less general than > casePromptOf :: (r -> b) > -> (forall a. p a -> (a -> b) -> b) > -> Prompt p r -> b > casePromptOf done cont (PromptDone r) = done r > casePromptOf done cont (Prompt p c ) = cont p (casePromptOf done cont . c) since we can use data Const c b = Const { unConst :: c } and set f = (Const b) yielding casePromptOf :: forall p,c. (r -> c) -> (forall a. p a -> (a -> c) -> c) -> Prompt p r -> c casePromptOf return bind = unConst . casePromptOf' (Const . return) bind' where bind' :: forall a,b. p a -> (a -> Const c b) -> Const c b bind' p c = Const $ bind p (unConst . c) In other words, casePromptOf can be defined with casePromptOf' and a clever choice of f . > And, just for the record, > > runPromptAgain :: Monad m => (forall a. p a -> m a) -> Prompt p r -> m r > runPromptAgain f = casePromptOf return ((>>=) . f) I thought that casePromptOf would not be general enough to write this very definition runPromptAgain' f = casePromptOf' return ((>>=) . f) that's why I used a type constructor f b instead, with f = m the monad in mind. The difference is basically that the (>>=) in runPromptAgain' is expected to be polymorphic (>>=) :: forall b. m a -> (a -> m b) -> m b whereas the (>>=) in runPromptAgain is specialized to the final type m r of runPromptAgain , i.e. (>>=) :: m a -> (a -> m r) -> m r Unfortunately, I failed to realize that casePromptOf is in turn not less general than casePromptOf' rendering my approach pretty useless :) I mean, if the second argument in casePromptOf' :: (r -> f c) -> (forall a,b. p a -> (a -> f b) -> f b) -> Prompt p r -> f c is polymorphic, we can certainly plug it into casePromptOf :: (r -> f c) -> (forall a. p a -> (a -> f c) -> f c) -> Prompt p r -> f c and thus define casePromptOf' in terms of casePromptOf : casePromptOf' return bind = casePromptOf return bind The above equivalence of a type constructor f and a simple type c in certain cases applies to the continuation monad, too. I mean that ContT r m a is equivalent to Cont (m r) a and even ContT' m a is equivalent to forall r. Cont (m r) a for the more type safe version data ContT' m a = ContT' (forall r. (a -> m r) -> m r) So, it's pretty clear that ContT isn't really a monad transformer since m doesn't need to be a monad at all. Put differently, the Control.Monad.Cont module needs some cleanup since type synonyms type ContT r m a = Cont (m r) a type ContT' m a = forall r. Cont (m r) a (or newtypes for type classery) are enough. Regards, apfelmus | http://www.haskell.org/pipermail/haskell-cafe/2008-January/038203.html | CC-MAIN-2014-41 | refinedweb | 509 | 77.47 |
Important: Please read the Qt Code of Conduct -
Resizing of QQuickView very slow and flickering
Hi,
I'm facing a problem when trying to resize Qml windows. It's very slow and flickering, which creates a very bad feedback for the user. Even with the most simple qml file (just a blue rectangle), I face the issue. Slow, flickering, with some black background showing up. A standard QWidget window doesn't have this issue.
I tried many things I've read on the internets, but none of these worked.
Cpp
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource(QUrl("qrc:/main.qml")); view.show(); return app.exec(); }
QML
import QtQuick 2.6 Rectangle { visible: true color: "blue" }
I'm using Qt 5.9 MSVC2017 64bit, on Windows 10 with a Geforce GTX 1060 6Gb.
I guess there is nothing to do and it's related to the way Qml is rendered. But I find it very surprising that nobody seems to be concerned by this problem. How is it possible to make a "professional" application with this kind of behavior?
Is there at least some workaround to repaint the widget only when we drop the cursor after a resize?
Thanks for any help
I've found some solution that is not perfect but muche better than default behavior
QSurfaceFormat format; format.setSwapInterval(0); format.setRenderableType(QSurfaceFormat::OpenGL); view.setFormat(format);
@penpen Do you have any theory about why that works better? (Would love to see some video of it to compare with your original post).
I used to worry about this sort of stuff (years ago now) quite a bit with the C++ widgets... problem was that window styling used to assume white-background apps, and if your app was anything else you'd have the same sort of horrid problems you show with resizing. I seem to remember that situation there could be improved by some tweaking of QStyle, but that was a widgets thing and would never help with new-world QQuickView apps. In any case the situation with OpenGL (at least on Windows and X11) always used to be pretty appalling, with resizing typically showing hideously scrambled former frames' content.
@penpen said in Resizing of QQuickView very slow and flickering:
I've found some solution that is not perfect but muche better than default behavior
QSurfaceFormat format; format.setSwapInterval(0); format.setRenderableType(QSurfaceFormat::OpenGL); view.setFormat(format);
Ho, i have the same problem and the same GPU: 1060 6gb. Some solution? | https://forum.qt.io/topic/81785/resizing-of-qquickview-very-slow-and-flickering/4 | CC-MAIN-2021-25 | refinedweb | 424 | 63.7 |
ChibiOS provides a variety of debug functions that can be enabled or disabled using preprocessor definitions.
When debugging ARM-based microcontrollers like the STM32, it can be useful to hardcode
This post provides a simple method of improving the definition of
chDbgAssert() in
chdebug.h so that a breakpoint is enforced in case of assertion failures. By using the ARM
BKPT instruction, the overhead is only a single assembler instruction.
Note that we use GCC inline assembler syntax here. When using other compilers, you’ll need to port the syntax correspondingly.
Original ChibiOS 2.6.6 code:
#if !defined(chDbgAssert) #define chDbgAssert(c, m, r) { \ if (!(c)) \ chDbgPanic(m); \ } #endif /* !defined(chDbgAssert) */
Modified code:
#if !defined(chDbgAssert) #define chDbgAssert(c, m, r) { \ if (!(c)) { \ __asm volatile("BKPT #0\n"); \ chDbgPanic(m); \ } \ } #endif /* !defined(chDbgAssert) */
Note that the inline assembler is also available as CMSIS function:
__BKPT. In the default configuration, ChibiOS 2.6.6 does not allow using CMSIS in
chdebug.h without additional
#include statements.
Note that this code snippet & the corresponding patch is licensed under the same license as ChibiOS.
Update 2014-10-23:
It is also occasionally useful to add the
BKPT statement into the implementation of
chDbgPanic in
chdebug.c:
void chDbgPanic(const char *msg) { __asm volatile("BKPT #0\n"); dbg_panic_msg = msg; chSysHalt(); }
Update 2014-11-01:
By default, ChibiOS 2.6.6 uses
chSysHalt() as handler for
LWIP_PLATFORM_ASSERT. In other words, the method described above will not catch LWIP assertions by default.
In order to fix this, open
os/various/lwip_bindings/arch/cc.h and replace
#define LWIP_PLATFORM_ASSERT(x) { \ chSysHalt(); \ }
by
#define LWIP_PLATFORM_ASSERT(x) { \ chDbgPanic(x); \ } | https://techoverflow.net/2014/09/28/enforcing-debugger-breakpoints-in-chibios-chdbgassert/ | CC-MAIN-2019-30 | refinedweb | 271 | 53.07 |
Opened 6 years ago
Closed 5 years ago
#16208 closed Bug (invalid)
natural key YAML deserialization using non-list natural keys broken (with fixing patch)
Description
I'm using Django 1.2.5. I had trouble loading data from a fixture using the natural keys feature. I tracked this down to what seems to be a bug in the deserialization code for YAML data. If the field used as a natural key is a tuple, (has an iter method in the yaml reader) the get_by_natural_key() method is called, but if it's a singleton, the same code is called that would be if no get_by_natural_key() method were defined.
I made a patch that I believe fixes this bug (attached). It fixes the issue for me. I don't have a full working copy of Django set up, so I just generated this with POSIX diff; sorry if that's inconvenient.
Attachments (2)
Change History (8)
Changed 6 years ago by
Changed 6 years ago by
comment:1 Changed 6 years ago by
I just attached a patch in the proper format, identical to the first one otherwise.
Jeff, could you provide an example of your problem? That would really help us reproduce it, and write a test case.
comment:2 Changed 6 years ago by
Here's an example. This is modeled on the natural key use case in the docs. The important difference is that the natural key is a singleton field (name), not a list of fields (first_name, last_name)
from django.db import models class AuthorManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Author(models.Model): objects = AuthorManager() name = models.CharField(max_length=100, unique=True) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author)
Here's the YAML data which fails to import into the resulting db
- {model: appname.author, pk: 1, fields: {name: Hemingway}} - {model: appname.book, pk: 1, fields: {title: "For Whom the Bell Tolls", author: Hemingway}}
The incorrect behavior is to reject this data, complaning that "Hemingway" isn't an integer (which foreign keys need to be), because when the serialized data being loaded is a singleton, the get_by_natural_key() method is not employed to implement the mapping to the key value. I think the bug was just confusion about if/else indentation. It's kind of hairy in there.
comment:3 Changed 6 years ago by
The current patch does not pass the django unit tests. Seems that when field_value is an integer, it executes
obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(field_value)
But requires a 2 parameters instead of one.
comment:4 Changed 6 years ago by
Dear Agustin,
Have you considered that the deserialization field "Hemingway" is not correct? If you check the django docs you can see that is necessary for the serialization of the naturals keys to return a tuple.
So, in that case, I would consider you to return (self.name,)
class AuthorManager(models.Manager): def get_by_natural_key(self, name): return (self.get(name=name),)
And see if it fails again.
comment:5 Changed 5 years ago by
comment:6 Changed 5 years ago by
I think that the issue here is due to the natural key not being tuple/list, which is wrong, AFAIK. Reopen if you can provide a valid test case.
fixes deserialization bug | https://code.djangoproject.com/ticket/16208 | CC-MAIN-2017-13 | refinedweb | 556 | 57.77 |
Andras Belokosztolszki
In SQL Server 2000 the primary database objects were tables, stored procedures, views and functions. In 2005 we have XML schema collections, message types, CLR objects (encapsulated .NET code), partition schemes, and more. The number of object types has more than doubled, and the dependency relations between them have become more complex. In SQL Compare 5.x we support all these new object types and allow their comparison and synchronization.
One of the most complex features of SQL Server 2005 is its support for CLR data types. You can now write stored procedures, functions, triggers using any .NET compliant language, such as C#.The CLR assemblies are stored directly in the database, so stored procedures and data types that depend on a CLR assembly do not depend on anything other than the database, and are persisted completely in a database backup. Restoring such a backup on a different server will make the CLR objects available in the restored database.
The problem arises when you want to modify one of these CLR objects. T-SQL offers the ALTER ASSEMBLY command but it does have some shortcomings. Perhaps the most important restriction is all method signatures must remain the same in the modified assembly. If just a single method signature has changed, then the ALTER ASSEMBLY command will fail. So how can you upgrade an assembly? Simple: you just need to drop all dependent CLR objects (stored procedures, functions, DDL and DML triggers), drop the assembly, re-create the assembly using the new DLL, and then recreate all the CLR objects. Sounds tedious, right? It is, but unfortunately that is still not the end of the story. CLR assemblies may contain user defined types. Rebuilding (i.e. dropping and creating) an assembly requires that such user defined types are dropped before the assembly is dropped. But this is not possible if there are tables that use the user defined data type.
ALTER ASSEMBLY
So, what you are left with is a CLR UDT upgrade path that looks something like this:
If the data in your tables is not important, then this might be a viable route for you. This is rarely the case though.
What SQL Compare 5.x does is analyze the CLR assemblies in the two databases that are compared. It intelligently decides whether a simple ALTER ASSEMBLY statement can be used to modify the assembly, or whether the assembly needs to be rebuilt. In the latter case, SQL Compare unbinds the data from tables that depend on a CLR UDT by migrating the data into a set of temporary tables. These temporary tables use the string representation of the UDT. Having done this all the relevant CLR objects are dropped, the CLR assembly rebuilt and, the above CLR objects are rebuilt based on the new CLR assembly. Finally, the data in the temporary tables is converted back to use the new CLR user defined type. By default we assume that the string representation of a CLR UDT is the same in the two versions. This assumption holds in the majority of the cases. However, in the cases where the string representation changes between the different CLR assembly versions, an extra conversion function can be added manually to the migration script.
The nice thing is that all of this is done automatically in SQL Compare 5.x, so if you are using this tool, upgrading to a new version of CLR assembly no longer requires potentially dropping all dependent CLR objects by hand and risking data loss.
There are many other changes and additions to SQL Server 2005 that SQL Compare 5 handles smoothly. XML Schema collections and partition schemes are similar to CLR assemblies from the modification point of view. Once again, SQL Compare can migrate changes by rebuilding all the dependent objects. While defaults in SQL Server 2000 were partially parsed by SQL Server, and ended up in the database in a similar form as they were entered, in 2005 the database management system can completely rewrite defaults, and thus SQL Compare 5 has to compare them at a semantic level.
By David Connell
While working on the SQL Data Compare 5 command line it became apparent that the command line version would have to be able to run comparisons in exactly the same way as the GUI. I have always found in the past that "n" implementations of a given algorithm will, for the same input, result in "n" different answers. James Moore was currently re-writing the SQL Data Compare GUI. He had already abstracted most of the logic dealing with the SQL Data Compare engine into a set of classes. He had tested and verified that this code worked within his environment. It soon became apparent that I could reuse his code and as a result get ahead of the game. The only issue we had to agree was whether we should distribute this code as an assembly, share the source code between us, or copy the source code. We decided to share the source code using our version control software. As a result we decided to implement a three tiered architecture:
This new business logic layer encapsulates logic that is specific neither to the SQL Data Compare's engine, nor to its GUI. For example, it encapsulated such common SQL Data Compare Engine tasks as:
From the end user's perspective, these tasks tend to get linked together and then run in one step. The command line may run all these tasks in one go whereas the GUI could run the first four tasks in one step and then subsequent steps individually. These tasks tend to take a significant period of time and so were implemented within Red-Gate's own ICancellable operation and run using our own ProgressDialog box.
ICancellable
ProgressDialog
NOTE: For some basic examples on how to compare databases please refer to the C#/VB code snippets which are by default installed at C:\Program Files\Red Gate\SQL Bundle 5\Toolkit Sample Files\Automating SQL Data Compare. Also check out the SQL Bundle Help.
Ideally, this business logic would have been extracted and turned into a reusable component (assembly) and made publicly available via our Toolkit API. However, it would have required significant time – time we did not really have –to make this assembly code fully robust (check all the parameters, and so on). This extra effort was not factored into the original timescale of the project and the only way to include it would have been at the expense of other features – hence the decision to internally document this logic and share it at source code level.
So if the end user can't access this logic, what does this new architecture really mean to them? Well, for one the same base code is used to carry out all communication with the Data Engine so it guarantees that the command line and the GUI generate the same results for a given project. However, it does also have an interesting impact on testing.
We use nunit extensively to test our code and for the SQL Data Compare Engine we have hundreds of test scenarios that we use as part of our regression tests. As Helen Joyce explains in her recent Relentless Testing article, there is a lot of manual labor involved in writing these tests and, generally, any test code has to be rewritten to work with any new version of a tool API. For the SQL Data Compare API, this would have normally taken several weeks. However the testers, rather than implementing their own logic to drive the SQL Data Compare engine (which would need to be tested and debugged), were able to reuse our business logic. This saved a significant amount of time and enabled the testers to spend more time testing production code and writing more test cases. So, what you have with SQL Bundle 5 is our most thoroughly and exhaustively tested – and therefore (hopefully) our most reliable and stable – set of tools yet.
By Tom Harris
We began thinking about SQL Bundle 5 almost a year ago now. Although by that time SQL Compare 3 had become the industry standard tool for comparing and synchronizing SQL Server database schema, we felt that there was a whole lot more that we could with it.
Our first step was to take a long hard look at usability of the product. Although we already had some top level technical requirements, we really wanted to meet some of our real users and capture their input. There is nothing more compelling than seeing a real user struggle with your application. We ended up visiting about half a dozen local companies; some were existing users whilst others had never used the products before.
All the usability feedback plus numerous emails and forum posts were fed into the melting pot of the new design. We played around with several prototypes, both in-house and with customers. Here are the motivations behind some parts of the new design
By Richard Mitchell
For SQL Data Compare version 5 we decided to address a number of issues that people have been having with our previous versions of the product. One of the earliest decisions we took was to make the data comparison engine rely on our SQL Compare engine to retrieve all of the schema information. This should help our SQL Toolkit users because the skills they have learned for SQL Compare are easily transferable to SQL Data Compare.
Another interesting change is the inclusion of an entirely new way to map the schema of two databases together to work out which tables are comparable. This new mapping system is far more flexible than the old method and can be used to compare and synchronize differently named tables; tables in different schemas or even different tables in the same database. You now don't even have to have a unique or primary key set on the tables; you can select the columns you want to use to compare the tables and we'll use those columns instead.
We have also refactored the entire results store API to cope with a new view of the data required by the UI. This has seen several benefits including all of the results store classes now being included in their own namespace. Also the filtering and sorting support has been improved to allow multiple layers of filters and/or sorts to be applied.
Before the data even gets into the results store you can apply a WHERE clause to the database so if you know you only want to compare and synchronize data after a certain timestamp you can do that.
WHERE
Other important features to take note of are the improved SQL Variant support and complete collation support.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here | https://www.codeproject.com/Articles/17084/SQL-Bundle-a-technical-perspective | CC-MAIN-2018-05 | refinedweb | 1,848 | 58.92 |
Looking for an overview? Watch this recorded example (~20 min) that uses our tools to process public domain gravity data from the Bushveld Complex in South Africa.
No time for a video? You can also just browse the code in the Jupyter notebook used in the example.
New to Python? Checkout these links to excellent free resources for starting your Scientific Python journey.
Used Fatiando for research? Please cite us in your publications.
Recording of a talk about using Fatiando for gravimetry with a live demo of the software. Source code for the demonstration: leouieda/2021-06-22-gfz
Verde offers spatial data processing and interpolation (gridding) with a sprinkling of machine learning.
Stable and ready for use
Code: fatiando/verde
doi: 10.21105/joss.00957
Pooch is the easiest way to download data files to your computer. It is used to manage sample data downloads not only by our own tools but also other popular Scientific Python libraries: scikit-image, SciPy, MetPy, xarray, SHTOOLS, satpy, icepack, histolab, yt, napari, and more.
Stable and ready for use
Code: fatiando/pooch
doi: 10.21105/joss.01943
import pooch import xarray as xr # The Digital Object Identifier of the data doi = "10.6084/m9.figshare.13643837" # Known MD5 checksum (from figshare) checksum = "md5:16c94a792003714efee2bdb4f3181d3a" # Download the netCDF file and check integrity fname = pooch.retrieve( url=f"doi:{doi}/australia-ground-gravity.nc", known_hash=checksum, ) # fname is the path to the file data = xr.load_dataset(fname)
Running this code multiple times will only result in a single download because the data are cached where Pooch can find it.
Harmonica is our library for processing, forward modeling, and inversion of gravity and magnetic data. Our goal is to incentivise good practices by carefully designing the software and offering state-of-the-art methods with efficient implementations.
Functional but still evolving
Code: fatiando/harmonica
doi: 10.5281/zenodo.3628741
Boule defines reference ellipsoids for calculating normal gravity of the Earth and other planetary bodies (Moon, Mars, Venus, Mercury).
Functional but still evolving
Code: fatiando/boule
doi: 10.5281/zenodo.3530749
Ensaio makes it easy to download our open-access sample datasets. It taps into the Fatiando a Terra FAIR data collection which is designed for use in tutorials, documentation, and teaching.
Functional but still evolving
Code: fatiando/ensaio
doi: 10.5281/zenodo.5784202
We are always happy to welcome anyone who is interested in getting involved! Whether it be coding, teaching, designing, or just hanging out. Getting involved in open-source can be great way to meet new people, improve your coding skills, and make an impact in your field.
Happy community members at a Fatiando Community Call.
2021/09/01: Documentation for the Python 2.7 fatiando package has been moved to legacy.fatiando.org.
2021/09/01: Fatiando is now on LinkedIn! Give our page a follow to keep up with the latest releases, events, and other news.
2021/05/20: Santiago, Agustina, and Leo gave a talk to the Geophysical Society of Houston about using Fatiando for potential field data (slides are available).
Weekly Fatiando Development Calls: we discuss various aspects of the
project. All are welcome, regardless of skill level and prior knowledge!
Notes and connection details:
fatiando/community
AGU 2021: Going to the AGU Fall Meeting? Come to our talk! Details at
fatiando/agu2021. | https://www.fatiando.org/ | CC-MAIN-2022-40 | refinedweb | 554 | 58.89 |
Modifying UI Designer controls? [Solved]
- TutorialDoctor
How do I modify controls added in the UI Designer, via the python script?
The help says this:
- Add a button by tapping ‘+’.
- Drag it to the center of the canvas (it will snap to automatic alignment guides).
- Select “Edit Title” from the button’s context menu, and enter ‘Tap me!’ (or whatever you like).
- Finally, open the ‘Attributes...’ inspector (from the button’s menu, or by tapping the (i) button), and navigate to the “Frame / Auto-Resizing” section. Check all the margins (but not “Width” or “Height”). - This ensures that the button stays centered in its container.
- Still in the inspector, set the button’s action to button_tapped (just the function name, without any parentheses or parameters).
- For the code below to work as is, rename the UI file to “My UI”.
This is the code:
<pre>import ui
def button_tapped(sender):
sender.title = 'Hello'
ui.load_view('My UI').present('sheet')</pre>
However, how would I change attributes of a label, or a slider etc, as a button action, or as a result of a tableView item being selected?
Delegates? If so, how?
An example would be helpful.
- TutorialDoctor
I found out how to do it from a Pythonista script, and made a basic example:
<pre>
import ui
def button_tapped(sender):
label= sender.superview['label']
print label.text
ui.load_view().present('sheet')
</pre>
Create a button with the name (not title) "label" for this code to work. Also, make its action "button_tapped" (no quotes). | https://forum.omz-software.com/topic/1273/modifying-ui-designer-controls-solved | CC-MAIN-2018-13 | refinedweb | 251 | 68.77 |
.
Many times, we create overloaded methods or constructors to allow them to accept different kinds of data. Further, there are times that we may accept object when any value will do. This works well (aside from boxing/unboxing concerns for value types), but if you have an overload that accepts object and one that takes an enum, and you pass a constant expression of 0, where does it go?
Let’s use a contrived example of a messaging framework where you can either construct messages with a specific payload, or construct a “basic” message which will have one of an enumerated set of “standard” payloads. For example, let’s say we allow these basic messages:
1: public enum BasicMessage
2: {
3: Ack,
4: Heartbeat,
5: }
And we allow for a Message to be constructed either using an object, or from a BasicMessage:
1: public class Message
3: public string Detail { get; private set; }
4:
5: public Message(object messageDetail)
6: {
7: Detail = messageDetail.ToString();
8: }
9:
10: public Message(BasicMessage messageType)
11: {
12: switch (messageType)
13: {
14: case BasicMessage.Ack:
15: Detail = "Acknowledgement";
16: break;
17:
18: case BasicMessage.Heartbeat:
19: Detail = "Heartbeat";
20: break;
21:
22: default:
23: Detail = "Unknown";
24: break;
25: }
26: }
27: }
Seems fine, right? So if we had something like:
1: // Detail will be "This is a test message."
2: var m1 = new Message("This is a test message.");
3:
4: // Detail will be "3.1415927"
5: var m2 = new Message(3.1415927);
6:
7: // Detail will be "Acknowledgement"
8: var m3 = new Message(BasicMessage.Ack);
10: Console.WriteLine(m1.Detail);
11: Console.WriteLine(m2.Detail);
12: Console.WriteLine(m3.Detail);
Everything looks fine and dandy. We see the output:
1: This is a test message
2: 3.1415927
3: Acknowledgement
So it seems that our overloads work and we are able to handle both our special BasicMessage enumeration, and any other object, which will use the ToString() result on that object for the message details. It all sounds straightforward, but what if we had this:
1: // We'd expect Detail to be "0"
2: var m4 = new Message(0);
4: Console.WriteLine(m4.Detail);
We’d expect to get a “0”, but we don’t, we get “Acknowledgement” instead. What happened?
Well, it happens that any (well, nearly any – depending on .NET version) constant zero expression has an implicit conversion to any enum. In short, this means that .NET prefers to implicitly convert the 0 above into BasicMessage instead of an object. This is all according to the language specs which.
For this to occur, it must be a constant zero expression. That is, it must involve literals or compile-time constants and no variables. In truth, depending on your .NET version, there are some const zero expressions that don’t qualify, but we won’t get too far in the weeds on which do or don’t (See Eric Lippert’s blog posts referenced in the summary for more details). The main point is to be prepared for the possibility of it happening. So, consider the following:
1: // 0 is a constant literal, converts to the enum
4: // still a const zero expression, converts to the enum
5: var m5 = new Message(0 * 13);
7: const double IHaveNothing = 0.0;
8:
9: // STILL a const zero value (double at that...), converts to the enum
10: var m6 = new Message(IHaveNothing * 13);
11:
12: // not a const zero expression, because involves a non-const variable, goes to object
13: int x = 0;
14: var m7 = new Message(x);
Curious, eh? Nearly any constant zero value will prefer to implicitly convert to an enum rather than an object if no other choice exists. This is true even if you attempt to force a cast to int, however casting to object would force it to the “correct” side:
1: // The cast to int does nothing here, still const zero expression
2: var m4 = new Message((int)0);
4: // This works, because it will box and then prefer object
5: var m5 = new Message((object)0);
This also means that you can assign an enum a const zero expression as well:
1: // complies, implicit conversion from const zero expression to enum
2: BasicMessage b1 = 0;
4: // does not compile, must cast if non-zero or non-const
5: BasicMessage b2 = 13;
In truth, the situations in which this happens seem to be contrived, yet you’d be surprised how many times this question comes up on sites like Stack Overflow. So how do we keep us from biting us?
First of all, this behavior is as designed, this is not a bug, so if this is ever not our desired behavior we should provide overloads for int and the other appropriate numeric value types (double, short, long, etc.) to prevent the issue.
In this way it won’t need to choose between object and an enum, but can directly match the appropriate numeric parameter. Just making an int overload isn’t always enough, this would not catch larger-than-int types like double, long, etc., and it would create an ambiguous overload error for smaller-than-int types like short, byte, etc. since now it can’t decide between the enum or the widening of the value type, as both are simple implicit conversions.
Thus, to really bullet-proof, we either need to have overloads for all the valid numeric value types:
1: public Message(object messageDetail) { ... }
2:
3: public Message(int messageDetail) { ... }
5: public Message(short messageDetail) { ... }
7: public Message(long messageDetail) { ... }
9: public Message(float messageDetail) { ... }
10:
11: public Message(double messageDetail) { ... }
12:
13: // etc for sbyte, byte, char, ushort, uint, ulong, and decimal
Or instead have a method with a generic type parameter. Note that this won’t work on overloading a constructor where the generic type parameter is not a generic type parameter of the class itself (can’t add generic type parameters to a constructor), but it will work on other methods where you may have a similar issue with overloads.
In short, when you are supplying overloads to handle many different values types, be aware that a constant zero expression can silently and implicitly convert to an enum instead of going to an object.
As such, if this is not the behavior you desire, make sure you have overloads for the primitive numeric types (or use a generic if possible), which also has the added benefit of avoiding boxing costs.
See Eric Lippert’s excellent blog entries “The Root of All Evil, Part One” and “The Root Of All Evil, Part Two” for more details on when and why this happens.
Print | posted on Thursday, January 26, 2012 6:31 PM |
Filed Under [
My Blog
C#
Software
.NET
Fundamentals
Little Pitfalls
] | http://blackrabbitcoder.net/archive/2012/01/26/c.net-little-pitfalls-implicit-zero-to-enum-conversion.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+BlackRabbitCoder+%28James+Michael+Hare%29 | crawl-003 | refinedweb | 1,130 | 60.65 |
Raspberry Pi MCP9808 Temperature Sensor Python Tutorial
Introduction: Raspberry Pi MCP9808 Temperature Sensor Python Tutorial
MCP9808 is a highly accurate digital temperature sensor ±0.5°C I2C mini module. They are embodied with user- programmable registers that facilitate temperature sensing applications. The MCP9808 high-accuracy temperature sensor has become an industry standard in terms of form factor and intelligence, providing calibrated, linearised sensor signals in digital, I2C format. Here is the demonstration with a python code using Raspberry Pi.
Step 1: What You Need..!!
1. Raspberry Pi
2. MCP9808 MCP9808 sensor and the other end to the I2C shield.
Also connect the Ethernet cable to the pi or you can use a WiFi module.
Connections are shown in the picture above.
Step 3: Code
The python code for MCP9808 can be downloaded from our github repository- ControlEverythingCommunity
Here is the link for the same :...
The datasheet of MCP9808.
# MCP9808
# This code is designed to work with the MCP9808_I2CS I2C Mini Module available from ControlEverything.com.
#...
import smbus
import time
# Get I2C bus
bus = smbus.SMBus(1)
# MCP9808 address, 0x18(24)
# Select configuration register, 0x01(1)
# 0x0000(00) Continuous conversion mode, Power-up default
config = [0x00, 0x00]
bus.write_i2c_block_data(0x18, 0x01, config)
# MCP9808 address, 0x18(24)
# Select resolution rgister, 0x08(8)
# 0x03(03) Resolution = +0.0625 / C
bus.write_byte_data(0x18, 0x08, 0x03)
time.sleep(0.5) # MCP9808 address, 0x18(24)
# Read data back from 0x05(5), 2 bytes
# Temp MSB, TEMP LSB
data = bus.read_i2c_block_data(0x18, 0x05, 2)
# Convert the data to 13-bits
ctemp = ((data[0] & 0x1F) * 256) + data[1]
if ctemp > 4095 :
ctemp -= 8192
ctemp = ctemp * 0.0625
ftemp = ctemp * 1.8 + 32
# Output data to screen
print "Temperature in Celsius is : %.2f C" %ctemp
print "Temperature in Fahrenheit is : %.2f F" %ftemp
Step 4: Applications..:
MCP9808 Digital Temperature Sensor has several industry level applications which incorporate industrial freezers and refrigerators along with various food processors. This sensor can be employed for various personal computers, servers as well as other PC peripherals. | http://www.instructables.com/id/Raspberry-Pi-MCP9808-Temperature-Sensor-Python-Tut/ | CC-MAIN-2018-05 | refinedweb | 333 | 51.14 |
There are many libraries and services to generate PDF files for asp.net core web applications. There are excellent commercial solutions out there, but if you need a free solution, it gets harder. Some libraries are hard to use, or others are limited in functionality. I need a free, easy to use, and quick solution to generate PDF files on an Azure Web App.
Can a View retrun a PDF?
What I need is a View that returns a PDF and not HTML what it usually does. The beauty of using a standard View is that I can use my web and asp.net core knowledge to design the View. In this case, I need to generate invoices.
I'm using MVC as a pattern to structure my web project.
I start by creating an invoice controller and a correlated view, where I can design an invoice in HTML.
public class InvoiceController : Controller { public IActionResult Index() { return View(); } }
html to pdf
Next, we need a way to render the HTML (the View) as PDF. I use the opensource command-line tool wkhtmltopdf. It is easy to use and compatible to run on Azure Web Apps.
wkhtmltopdf is an opensource (LGPLv3) command-line tool to render HTML into PDF using the Qt WebKit rendering engine. It runs entirely "headless."
Download wkhtmltopdf and add the files to your project. I created a folder
/wkhtmltopdf in my solution. When downloading, pick the correct version that is compatible with your Azure Web App (Windows or Linux).
Add the files
wkhtmltoimage.exe,
wkhtmltopdf.exe, and
wkhtmltox.dll to your solution and change the 'Copy to Output Directory' to 'Copy always.'
Rendering the PDF
An easy way to interact with the wkhtmltopdf command-line tool is to use the Rotativa library from NuGet.
First, we need to tell Rotativa where to find the wkhtmltopdf tool. Add the following line to
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... RotativaConfiguration.Setup(env.ContentRootPath, "wkhtmltopdf"); }
Next, we create a new action result in our InvoiceController that will return the PDF file. This new action result 'IndexAsPDF' will reuse the View we already had created.
public class InvoiceController : Controller { ... public IActionResult Pdf() { return new ViewAsPdf("Index") { FileName = "Invoice.pdf", PageSize = Size.A4, MinimumFontSize = 16, ContentDisposition = ContentDisposition.Inline, }; } }
When we go to the URL it will show the HTML version of the Invoice, but when we go to we get the PDF version.
Top comments (0) | https://dev.to/cschotte/generate-pdf-files-with-asp-net-core-on-azure-5853 | CC-MAIN-2022-40 | refinedweb | 407 | 68.67 |
On Thursday 13 March 2003 22:53, Hilbert wrote: > Hello, > > I started writing a script to keep track of my > bookmarks. > This is the first script where I'm using classes. > I wanted to ask your opinions so that I know > I'm on the right (or wrong) path > I want to turn this into a cgi script, so the input > part is just for testing. I'm not sure if this is the > correct way for setting up the groups class. > > > def Print(self): > print self.group,':',self.name,':',self.url > this is my only major issue with your class design. Depending on print limits your class's usefulness. You are better off implenting something like your asTuple() method and passing that to print: print myclass.asString() in Python a common way to accomplish this is via __str__ or __repr__: >>> class Foo: ... def __str__(self): ... return "I am foo" ... >>> f = Foo() >>> print f I am foo Now your class can be used in cgi's, GUIs, text based programs, etc. As a purely matter of style, your naming convention is reverse from what I am used to. In projects I have worked on classes/types get capital letters, methods as studlyCaps (note the first word is lower case) and variables get names_like_this. Often you will see functions declared like_this() as well. class Bookmark: def __init__(self, group, name, url): self.group = group self.name = name self.url = url def __str__(self): return '%s:%s:%s' % (self.group, self.name, self.url) def asTuple(self): return (self.group, self.name, self.url) class BookmarkGroupDb: pass | https://mail.python.org/pipermail/python-list/2003-March/180275.html | CC-MAIN-2016-30 | refinedweb | 265 | 76.42 |
I needed a simple way to test if a list of keywords (tags) had the required words, but one moment later, conditional operators other than AND were required. I didn't find a public module that satisfied my needs. Some of this was discussed in AND and OR on Regular Expressions.
I took my subs and group them in a module, then changed into objects (my first attempt in OOP) and worked nice.
Examples of use:
# Simple query (same as: +xxx -ppp -jjj):
my $query = "xxx-(ppp,jjj)";
use Keywords;
my $kw = Keywords->new(ignorecase => 1);
$kw->prepare($query);
# Simple test:
print "Match!" if $kw->test($list_of_tags);
# @ids has some keys %table:
@ok = grep {$kw->test($table{$_}[$col])} @ids;
# Same as before:
@ok = $kw->grep_keys(map {$_ => $table{$_}[$col]} @ids);
# Hash only has keywords lists:
@ok = $kw->grep_keys(%tags);
# When ids are full keywords:
@ok = $kw->grep(@ids);
[download]
Now, I want to share my efforts and decided to upload this to CPAN, but I need to define or append to a namespace. I thought on Search::Keywords, but Keywords::Match might be a better one.
Hints for a proper namespace?
Hints for extra features? I'm thinking on set/get parms, reparse, sentences (when tags have more than one word), UTF8 (un)support...
Thanks!
Neither is particularly compelling.
Having a root namespace "Keywords::" means you can do lots of things with keywords. Is there that much you can do to keywords?
Sounds like it would be better integrated into "Search::" or some other existing top-level namespace.
I would actually prefer if the query parser provided a standard interface that supported multiple query languages. (The one you provided, Google's, etc)
I also have a feeling the matching functionality shouldn't be too heavily integrated.
Is there that much you can do to keywords?
I think not, but this module provides a query parser, a regexp builder and some tests methods. Not only the query language is relevant. Also it is the way that a list of keywords is being stored if you want to use some specific options, then a method to clean up the list string is provided. So it's not only a Search thing. That's made me doubt.
I don't think that "Search::Query" is appropiate, for the same reason as above. May be "Regexp::Keywords"?
BTW, "Search::Query::Google" made me think on a module to retrieve some results from Google (as "Google::Search")... "Search::Keywords::Google" is not much better, but I got the idea and agree on that.
I also have a feeling the matching functionality shouldn't be too heavily integrated.
Could you explain this?
If query building is separate from matching, then you'll be able to match against inputs other than a flat string.
Specifically, only supporting flat strings prevents it from being extended to support "is:unread" or "title:foo"
I'm not saying you should implement those features. I'm saying it would be great if the designed allowed someone to do so.
UPDATE: This module was uploaded at CPAN as Regexp::Keywords.
Thunder fish
Shocky knifefish
TBD
Electric eels were invented at the same time as electricity
Before electricity was invented, electric eels had to stun with gas
Results (293 votes). Check out past polls. | http://www.perlmonks.org/?node_id=792394 | CC-MAIN-2017-09 | refinedweb | 553 | 73.27 |
Category: Best text editor
14/09/05
Categories: General, Best text editor
No allows it!
28/07/05
Categories: General, Software, Best text editor
Text.
Results in numbers
18/07/05
Categories: General, Software, Best text editor
Tabular overview of tested text editors available
I have now started to make a tabular overview of the tested text editors available. You can find it here and I will keep it updated with new results as I continue to test.
15/07/05
Categories: General, Software, Best text editor
Text.
Results in numbers
13/07/05
Categories: General, Software, Best text editor
Text editor test: UltraEdit-32
So here it is, the first test result in my quest for the best text editor. I started with UltraEdit because I had recently downloaded the trial version of it, and because the web site makes full-bodied promises about it: UltraEdit the #1 selling, most powerful, value priced text editor available! The ideal text, HEX, HTML, PHP, Java, Perl, Javascript, and programmer's editor!
UltraEdit-32 is a commercial product by IDM Computer Solutions, Inc. and has its homepage at. The version I tested was v11.10a (5/10/05) with a hotfix dated 07/07/05 installed.
First impression
The first impression I got was that the installer didn't work correctly. The download I got was a zip file and I ran the setup from there directly, which apparently didn't extract two additional files correctly. During installation, I also elected to install a German dictionary in addition to the standard English one, and the setup program wasn't able to deal with that. A dialog told me that a file would have to be downloaded from somewhere, but this didn't seem to work. After a while, the dialog switched to another file, and back again after another while. I recognized that one of the files was the standard English dictionary that was really in the zip file - I killed the setup process, extracted the two files alongside the setup executable, went without the German dictionary and finally the setup was able to complete its job.
General features
The program startup is fast enough. Although the evaluation period is a generous 45 days, a nag screen appears on program startup from day 1, which is not so nice because it hangs around in the way for a while. It's actually possible to work with that dialog in the foreground, but I would have thought it should suffice to show that dialog when the evaluation period is nearing its end.
The document model is a mixture of MDI and a tabbed interface, the tabs are implemented in a docking window which can be closed. Anyhow, UltraEdit needs only to be started up once for any number of documents.
Regular expressions are supported, and the online help even lists a two variants, namely the "old UltraEdit syntax" and the "Unix-compatible" syntax. I was going for the Unix syntax and this proved to be a bit of a problem because I failed to see the sentence in the help file where it says that I have to switch UltraEdit to use that syntax in the Options dialog. After I finally found out about this I was able to search for the expression
([^\s]+) ([^\s]+) and replace by
\2 \1, although I didn't find in the help that there was any support for regular expression replacements at all. So, at a glance, very good!
UltraEdit's memory consumption is a peculiar thing. Right after startup it was at only 4.3 MB, which went up to 7.5 after my first use of the file select dialog. Then, after playing around with the regular expression tests, with three small files open, I noticed that memory was now up to 23.6MB. I'll keep an eye on this while I continue the tests. (Update: During the course of the tests, memory usage went up to about 30MB, but no more than that, even with a lot more files loaded and the editor running for two days.)
The button to toggle line-wrapping is right there in the default toolbar. Toolbar configuration is very flexible, although the user interface for it is not very intuitive. A nicer configuration dialog, like Office has had since 1997 at least, would do no harm here.
The next not-so-nice thing is scrolling and redrawing. Scrolling is sluggish - I have my keyboard set to the highest possible repeat rate, but I can't scroll very fast by holding down the cursor key. I tried timing things, and I came to about 20 lines a second, merely 2/3 of the keyboard repeat rate. UltraEdit takes close to 100% CPU while the down key is being held. Even worse is redrawing: the complete editor surface is being redrawn all the time while the window is being resized, or while the splitter of the "File tree view" is being dragged (which also results in a resize of the editor pane). This redraw seems to be very slow, so that I can more or less watch it happening, regardless of the screen I'm running the editor window on. Both redrawing and scrolling get much worse when the editor pane is actually covered with text (long lines from top to bottom), resulting in bad flickering when scrolling up or down. Although it wasn't reliably reproducible, I saw a scrolling bug a few times when using Page up or down, where only part of the editor pane would be redrawn after the key press.
In general, navigating large files can be quite painful. I have a test XML file with all its content (3.5M
on one line and it's not really possible to comfortably work in this file. The single line is wrapped at what looks like 4096 characters, for no apparent reason, but even moving the cursor left or right within any line is painfully slow, while up and down is even slower than in the test with the "normal" file.
Hex editing is supported, together with searching and replacing values. Regular expressions even work with hex edit search, but they are restricted to the ASCII text - would be nice if they also worked for the hex representation. Why not search for
DEAD....?
UltraEdit is a disk-based editor which doesn't load edited files into memory completely (there's an option to use memory buffers instead, which I haven't tested extensively). Editing extremely large files without performance issues becomes possible this way. To approach the programmers have chosen is to make use of temporary files - for every file that's opened in UltraEdit, a temporary file is created first. There are a few options to control this behaviour, but only to a certain extent. For example it doesn't seem to be possible to automatically have memory buffers used for files up to a certain size... but maybe that's just a weird idea of mine, wanting to reduce hard disk traffic.
The editor is completely usable with mouse or keyboard. All menus and toolbars are configurable, as are the keyboard shortcuts. Very good!
There are a few simple text formatting options, but nothing too fancy. All formatting takes place after text entry and has to be invoked manually. It's possible to define the layout of a paragraph (left, right, center, fill), but apart from that only indented paragraphs and line wraps at specific columns are supported.
UltraEdit supports all the various line endings as well as Unicode in UTF-8 and UTF-16, with and without BOM. All these types can be converted from one to the other. In addition, there's ASCII to EBCDIC conversion. For non-Unicode files, the codepage and even the locale can be switched. Great!
UltraEdit can save its settings either in an INI file (stored in the proper path under Documents and Settings) or in the registry. In both cases, this should be transportable fairly easily.
System integration
UltraEdit does certainly look like a modern Windows application, but the UI could do with a workover in several places. For example, the Options dialog is enormously overloaded and the layout of many dialogs is inconsistent and unprofessional. Throughout the application, there are at least five different layout variants for standard buttons like Ok, Cancel or Help. Many dialogs should also simply be larger. Guys, read some UI guidelines! Once again I can't help but wonder how a program goes through eleven (11!) major versions without anybody bothering about the UI. It's the business card of an application, the first and most immediately impressive part of an application that a user sees. With UltraEdit, at least the main window doesn't have any archaic elements, but the dialogs... oh well.
The installer integrated an entry for UltraEdit in the Explorer context menu, and file type registration and configuration is available directly from the Options dialog.
My use of ClearType was a problem at first, because fonts weren't anti-aliased at all. I changed the font to Consolas and the result was even more horrible. An option in the long list on the General page helped: "Setting this may improve display issues with ClearType fonts on Windows XP". Yes, that's the name of the option. Fine that it works, but I can't help but wonder if these guys really know what they are doing. What funny development language/environment are they using that allowed them to break ClearType support in the first place?
Handling files in virtual directories (namespace extensions) and UNC paths was no problem for UltraEdit.
Syntax highlighting
The syntax highlighting supports C#, Perl, HTML and XML (from my list of wanted formats) out of the box. Support for languages can be extended, but the means to do it are quite... hm... ridiculous, really. UltraEdit has a so-called wordlist, which is a text file in which a list of at most 20 blocks of highlighting configurations is stored. To extend the system, you have to edit that file manually and restart UltraEdit afterwards. The blocks in the file are numbered, and it's up to the user to make sure that there are no duplicate numbers.
In a download area on the UltraEdit web server there's a long list of add-on wordlist entries that need to be downloaded and manually fiddled into a wordlist file locally - as long as there aren't twenty entries already in that list (11 are used by the default installation). I was able to find a Delphi highlighting there, but I didn't find any for diff or e-mail formats.
Extensibility
UltraEdit can be automated by its macro system, which also supports a recording function. The macro editor didn't look particularly comfortable to me, it could probably benefit from a UI workover as much as any other part of the application. For example, it would be extremely helpful if there was some hinting system that would show information about the syntax and parameters of the various commands.
The macro system itself looked quite capable and there are a few macros in the download area on the web site - together with the recording function that should be enough to get started.
Although the program comes with a few functional modules that look like they might be extensions (a colour selector, HTML tidy, ...), I couldn't find any information on an extensibility API. It's possible to configure external tools to call from the editor, but these don't integrate with the editor in any way.
Networking
UltraEdit is able to access files on FTP servers (my god, the UI!) and it was able to open a file from a WebDAV location that was previously configured in My Network Places. It didn't have any support for WebDAV of its own, though.
Support and community
There's an active community forum for UltraEdit and a support e-mail address at support@idmcomp.com. I haven't had reason to contact the support team, but I generally like the fact that they want to hear about bugs and feature requests in this direct way, because I haven't had many good experiences with companies who supposedly handle their support solely via forums (apart from the fact that forums are far more difficult to use for me than my own mailer, you usually have to register first (yeah, yet another password!) and so on... but I digress).
Price
The price for a single, non-concurrent, user license is $39.95 at the current time, which seems a little on the high side, as shareware prices go. It's nevertheless a reasonable price to ask, given the largely mature functionality that UltraEdit offers.
Other miscellaneous impressions
Why the *#**! can't I resize the Options dialog? The options list on the General page is long and even too wide to fit without scrolling, yet I can't resize the dialog.
Results in numbers
As announced, I assign points for each of my categories, from 1 (worst) to 100 (best). As this is the first in a sequence of tests, I won't assign extremely high nor extremely low numbers right now, apart from places where the asked functionality is simply absent. So the real range is 20 to 80 for this first test. | http://www.sturmnet.org/blog/category/software/best-text-editor/ | crawl-002 | refinedweb | 2,235 | 61.16 |
Script developers can declare constants, variables, functions and classes at global scope by writing the appropriate lines of code. Script hosts (Internet Explorer, ASP, WSH, etc) however can only add objects to the script engine’s global scope. For practical purposes, it’s as though the host creates a new global variable which is assigned to a particular object and cannot be changed.
I suppose that we could have enabled hosts to add named constants pretty easily — the host could pass in a name and a variant containing the value. We could even do host variables by having the host pass in the address of a variant containing the variable. There’s no obvious way to do host-supplied functions other than having the host provide a named object with a default property that calls the function, and now we’re back where we started with host-added objects. It’s also kind of a pain in the rear to provide a hundred different function objects if you have a hundred functions to inject.
Fortunately we can effectively get host-provided constants, variables and functions even if hosts can only add named objects. How? By enabling the host to pass in flags to say “the members of this object may/must/cannot be accessed by qualifying with the object name“.
That’s how Internet Explorer does it. IE adds the window object to the script engine with the flag “you may access members of window without qualification”. Therefore, both window.document.whatever() and document.whatever() work. ASP, by contrast, sets the flags indicating that members of the Response object must be accessed via Response.Write. Just plain Write doesn’t work.
Given this mechanism, the other mechanisms become unnecessary. If the host wants to add a named constant then the host just creates an object, sets the appropriate flags, and gives the object a property with a getter, no setter. From the scripter’s point of view, it’s just like the constant was added to the global namespace.
Back to type library importing. We’ve got
typelib Cheese {
enum Blue{
Stilton = 1
Gorgonzola = 2
}
}
so we want to add two constants to the global namespace, plus two objects, so that we can say
foo.bar = Stilton
foo.bar = Blue.Stilton ‘ Blue must be an object
foo.bar = Cheese.Blue.Stilton ‘ Cheese must be an object
At this point we were faced with two choices. We could come up with some new mechanism whereby constants could be added to the script engine, or we could re-use the existing named object injection mechanism. The former wouldn’t have been that hard, but we chose the latter.
When you inject a type library into the engine, what we do is we build up an object with the following properties:
Cheese.Stilton
Cheese.Gorgonzola
Cheese.Blue
where Cheese.Blue is itself an object with the right properties. We then inject Cheese as a named item into the script engine and mark it as “may be qualified”.
This solution has the (arguably) nice property that you can disambiguate with only the outer name as well. That is, you can say
foo.bar = Cheese.Stilton
That’s maybe a little weird. We could have instead built the object hierarchy by not putting the bottom-level values on the top-level object, and instead added the top and mid-level objects as named items instead. That is, create Cheese with only property Blue, and Blue with properties Stilton and Gorgonzola, and then add both Cheese and Blue as “may be qualified” named items. That solution presents additional problems though. Suppose we did that, and also added
typelib Food {
enum Cheese {
Green = 1
Blue = 2
Yellow = 3
White = 4
}
}
We’d then have two top-level items both named Cheese, both with a Blue property, and it would be ambiguous which was which – we’d need to invent a mechanism for resolving conflicts amongst global named items, which is not something we really wanted to do.
So far we’ve seen how type library injection works at a high level. Next time we’ll delve into some of the performance issues that arise. | https://blogs.msdn.microsoft.com/ericlippert/2005/06/29/scripting-type-library-constant-injection-performance-characteristics-part-two/ | CC-MAIN-2016-44 | refinedweb | 697 | 62.48 |
Back to: LINQ Tutorial For Beginners and Professionals
Architecture of LINQ
In this article, I am going to discuss the Architecture of LINQ. The term LINQ stands for Language Integrated Query and it is pronounced as LINK. Nowadays the use of use LINQ increasing rapidly. So, as a developer, you should understand the Linq and its architecture. At the end of this article, you will have a very good understanding of the following pointers.
- What is LINQ?
- Why should we learn LINQ?
- How LINQ works?
- What are LINQ Providers?
- Advantages of using LINQ.
- Disadvantages of using LINQ.
What is LINQ?
The LINQ (Language Integrated Query) is a part of a language but not a complete language. It was introduced by Microsoft with .NET Framework 3.5 and C# 3.0 and is available in System.Linq namespace.
LINQ provides us common query syntax which allows us to query the data from various data sources. That means using a single query we can get or set the data from various data sources such as SQL Server database, XML documents, ADO.NET Datasets, and any other in-memory objects such as Collections, Generics, etc.
Why should we learn LINQ?
Let us understand why we should learn LINQ with an example.
Suppose we are developing a .NET Application and that application requires data from different data sources. For example
- The application needs data from SQL Server Database. So as a developer in order to access the data from SQL Server Database, we need to understand ADO.NET and SQL Server-specific syntaxes. If the database is Oracle then we need to learn SQL Syntax specific to Oracle Database.
- The application also needs data from an XML Document. So as a developer in order to work with XML Document, we need to understand XPath and XSLT queries.
- The application also needs to manipulate the data (objects) in memory such as List<Products>, List<Orders>, etc. So as a developer we should also have to understand how to work with in-memory objects.
LINQ provides a uniform programming model (i.e. common query syntax) which allows us to work with different data sources but using a standard or you can say unified coding style. As a result, we don’t require to learn different syntaxes to query different data sources.
Note: If you are either a C# or a VB.NET Developer (Web, Windows, Mobile, Console, etc.) then you should learn LINQ.
How LINQ works?
As shown in the above diagram, you can write the LINQ queries using any .NET supported programming languages such as C#, VB.NET, J#, etc.
The LINQ provider is a software component that lies between the LINQ queries and the actual data source. The Linq provider will convert the LINQ queries into a format that can be understood by the underlying data source. For example, LINQ to SQL provider will convert the LINQ queries to SQL statements which can be understood by the SQL Server database. Similarly, the LINQ to XML provider will convert the queries into a format that can be understood by the XML document.
What are LINQ Providers?
A LINQ provider is software that implements the IQueryProvider and IQueryable interface for a particular data source. In other words, it allows us to write LINQ queries against that data source. If you want to create your custom LINQ provider then it must implement IQueryProvider and IQueryable interface. Without LINQ Provider we cannot execute our LINQ Queries.
Let us discuss some of the LINQ Providers and how they work internally.
LINQ to Objects:
The LINQ to Objects provider allows us to query an in-memory object such as an array, collection, and generics types. It provides many built-in functions that we can use to perform many useful operations such as filtering, ordering, and grouping with minimum code.
LINQ to SQL (DLINQ):
The LINQ to SQL Provider is designed to work with only the SQL Server database. You can consider this as an object-relational mapping (ORM) framework which allows one to one mapping between the SQL Server database and related .NET Classes. These .NET classes are going to be created automatically by the wizard based on the database table.
LINQ to Datasets:
The LINQ to Datasets provider provides us the flexibility to query data cached in a Dataset in an easy and faster way. It also allows us to do further data manipulation operations such as searching, filtering, sorting, etc. on the Dataset using the LINQ Syntax.
LINQ to Entities:
The LINQ to Entities provider looks like LINQ to SQL. It means it is also an object-relational mapping (ORM) framework that allows one to one, one to many, and many to many mapping between the database tables and .NET Classes. The point that you need to remember is, it is used to query any database such as SQL Server, Oracle, MySQL, DB2, etc. Now, it is called ADO.NET Entity Framework.
LINQ to XML (XLINQ):
The LINQ to XML provider is basically designed to work with an XML document. So, it allows us to perform different operations on XML data sources such as querying or reading, manipulating, modifying, and saving the changes to XML documents. The System.Xml.Linq namespace contains the required classes for LINQ to XML.
Parallel LINQ (PLINQ):
The Parallel LINQ or PLINQ was introduced with .NET Framework 4.0. This provider provides the flexibility of parallel implementation of LINQ to Objects. The PLINQ was designed in such a way that it uses the power of parallel programming which targets the Task Parallel Library. So if you want to execute your LINQ query simultaneously or parallel on different processors then you need to write the query using PLINQ.
Advantages of using LINQ?
- We don’t need to learn new query language syntaxes for different data sources as it provides common query syntax to query different data sources.
- Less code as compared to the traditional approach. That means using LINQ we can minimize our code.
- It provides Compile time error checking as well as intelligence support in Visual Studio. This powerful feature helps us to avoid run-time errors.
- LINQ provides a lot of inbuilt methods that we can use to perform different operations such as filtering, ordering, grouping, etc. which makes our work easy.
- Its query can be reused.
Disadvantages of using LINQ?
The disadvantages of using LINQ are as follows:
- Using LINQ it’s very difficult to write complex queries like SQL.
- LINQ doesn’t take the full advantage of SQL features like cached execution plan for the stored procedure.
- We will get the worst performance if we don’t write the queries properly.
- If we do some changes to our queries, then we need to recompile the application and need to redeploy the dll to the server.
In the next article, I am going to discuss the different ways to write LINQ Queries using C#.NET. Here, in this article, I try to explain the Architecture of Linq and I hope you enjoy this Linq Architecture article.
2 thoughts on “Architecture of LINQ”
Thank you
Thank you | https://dotnettutorials.net/lesson/introduction-to-linq/ | CC-MAIN-2021-31 | refinedweb | 1,185 | 66.84 |
Classifier decision functions in Python
Hi, everyone in this tutorial we are going to see about classifier decision functions in brief with Python.
What are the Decision functions?
The Decision Function is used in classification algorithms especially in SVC (support Vector Classifier). The decision function tells us the magnitude of the point in a hyperplane. Once this decision function is set the classifier classifies model within this decision function boundary.
Generally, when there is a need for specified outcomes we use decision functions. This decision function is also used to label the magnitude of the hyperplane (i.e. how close the points are lying in the plane).
Implementation of classifier decision functions in Python
The Sklearn package provides a function called decision_function() which helps us to implement it in Python. Now let us implement this decision_function() in SVC,
The Coding part is done in Google Colab, Copy the code segments to your workspace in Google Colab. Refer to this tutorial Google Colab for Machine Learning to get started with the Google Colab, If you are new to Google Colab.
- To import necessary packages and create X,y data and to create an svc model we use the below code segment.
import numpy as np X = np.array([[12,11],[1,1],[2,2],[2,12]]) y = np.array([1,2,2,2]) from sklearn.svm import SVC mod = SVC(kernel='linear', C = 1.0) mod.fit(X, y)
- To Visualize the data and the division line,
weight = mod.coef_[0] data = -w[0] / w[1] xax=np.linspace(0,12) yax=a*xax-mod.intercept_[0] / w[1] h0 = plt.plot(xax, yax, 'k-', label="non weighted div") plt.scatter(X[:, 0], X[:, 1], c = y) plt.legend() plt.show()
Here, look at our program as well as the figure.
- To set the decision function and to predict the data we use the below code segment.
print(mod.decision_function(X)) mod.predict(X)
Output:
[-0.99986929 1.19991504 0.99993465 0.99993465] array([1, 2, 2, 2])
We can say that the decision function has labeled the values according to their presence in the hyperplane. So we did it.
Hope this tutorial helps!!!
Hi Infant,
When trying to run the code snippets given in your article, I have run into several problems as multiple things aren’t defined, including w, a, and plt. I am operating under the assumption that w is supposed to be weight and plt is from an import of matplotlib.pyplot, but the variable a is never declared anywhere. | https://www.codespeedy.com/classifier-decision-functions-in-python/ | CC-MAIN-2020-50 | refinedweb | 423 | 58.99 |
- Simple Prop Models
- Conclusion
- About This Article
Simple Prop Models
We'll begin by making a relatively simple prop model from the Parking Spot project. Going through this process a few times should make the process of prop modeling clear. We'll also cover a few modeling techniques.
BigBone
The simplest of the props is the big bone that Spot gets from the pet shop. It's a caricatured bone, meant as a tasty reward for a really good dog to eat, like an oversize Milk-Bone biscuit.
Artwork for such a model is probably unnecessary, so we'll wing it without any drawings.
First, create a Maya project called BigBone in which the model files will reside. Most of the standard subdirectories are unnecessary, so create only the Scenes, Shaders, Textures, and Images directories.
NOTE
Although you can select Use Defaults in the New Project dialog window, it can be clearer for simple props to just enter names in the few fields that will be needed. In this case, only the Scenes, Shaders, Textures, and Images directories likely will be needed.
Next, it's time to determine just how big that bone really is. After a few minutes of considering the dog's size, the size of the valve nuts on the nearby fire hydrant, and what the bone might look like in the nearby store window, a size of about 15 inches long by 3 inches wide by 1 inch thick seems about right.
Starting in the Front window (assuming that characters will reach out and grab a vertically oriented bone), create half of the bone profile as a uniform NURBS curve using the CV Curve tool (see Figure 1), and adjust its shape until satisfactory. My initial curve is found in the Maya scene BigBoneCurve.ma.
Figure 1 Initial BigBone curve.
Note that the beginning of the curve is on the YZ plane and that the beginning tangent is normal to this plane (that is, parallel to the X-axis). The curve will be revolved about the Z-axis, so we want to avoid a point at the ends of the surface.
The other end of the curve ends at the XY plane (that is, at Z = 0). To make both ends the same, mirror the curve by duplicating it and inverting the scale on the Z-axis (see Figure 2). Join the two ends using the Edit Curves, Attach Curves command with the Blend method selected. The result is a nicely symmetric curve with a classic "bone" shape.
Figure 2 BigBone curve halves joined by the Attach operation.
Revolve this curve to make the initial BigBone surface.
Using the Surface, Revolve tool to create a cubic surface about the Z-axis, you can see that the resulting surface (see Figure 3) looks more like a dumbbell than a bone, but we can fix that.
Figure 3 Initial revolved BigBone surface.
The plan here is to flatten the front and back of this surface to get a shape close to the desired one. So, scale the CVs at the "corners" of the bone (as seen from the Top view), as well as the matching CVs along the midline (see Figure 4). This quickly makes the BigBone into less of a dumbbell and more of a bone.
Figure 4 The first flattening pass in the Top view.
The resulting shape is still too thickat least, at the ends. Flatten the ends some more by selecting just the CVs that protrude too far in Y at the ends and scaling them down in Y until they lie about where those along the shaft do.
This produces a bone surface (see Figure 5) that doesn't bulge out in Y anymore.
Figure 5 Flattened ends on the BigBone surface.
The flattening operations have created some distinct ridges at the front and back of the BigBone surface ends. To remove these, simply select all four of these CVs (two at each end) and scale them down in Z until they are about the level of the next CV row on the bone. Then, because there's now a little hiccup in the mesh caused by bringing our ridge-making CVs close to the untouched CVs near the pole, select these too-near CVs and scale them down a bit, too.
The result (see Figure 6) is getting pretty close to the Milk-Bone shape we initially imagined.
Figure 6 Ridges removed from BigBone surface.
Our BigBone is still a little too oval on its edges, though, so the extreme X-axis CVs in the ends could be scaled in a bit. A little experimentation shows that this ruins the bone-shape profile we created in our initial curve.
A better approach is to take the CVs on either side of the extreme X-axis CVs and scale them out in X. Because this is a surface, this also affects the profile (moving the surface out beyond the curve profile). So, when the edge shape is better, scale in a bit all of the aforementioned CVs until the shape is back at the profile curve (see Figure 7).
Figure 7 Improved end profiles at BigBone ends.
We need to make a similar profile improvement at the top and bottom of the ends. The most extreme Z-axis CVs pull up the ends of the bone, but not enough to match the initial profile anymore. Again, the answer is not to pull up these extreme CVs, but to pull up their neighbors.
First, though, widen these CVs so that they line up in X with the extreme Z CVs. This needn't be exactmerely get reasonably close (see Figure 8).
Figure 8 Lining extreme Z tip CVs on BigBone.
Next, do the vertical adjustments (to better match the bone profile curve) by grabbing the extreme Z CVs and their profile-shaping neighbors and scaling them in Z. This should bring the bone surface shape back into agreement with the profile curve (see Figure 9).
Figure 9 BigBone ends fully improved.
The result is now pretty close to our intended shape, but the dimensions are just a bit off. The bone's a little too wide in the handle, mostly, and maybe a bit short. Fortunately, these are really easy problems to fix.
To slim down the handle, just go to the Front view and grab the CVs along the handle area (there are five rows of CVs there). Scale them down in X until it's more manageable for poor Spot (see Figure 10). Of course, Spot lacks opposable thumbs, so it's all a cheat anyway, but at least it will look more plausible with a slimmer handle.
Figure 10 The BigBone handle slimmed down.
Finally, to get the desired length, just select the CVs for each end and move them in Z. To make the bone the intended 16 inches long, move the end CVs about an inch farther out. Now the basic BigBone is complete (see Figure 11). Set this aside for use before Spot takes a bite out of it (or you can just load up my file, BigBoneMainSurface.ma).
Figure 11 The BigBone main surface completed.
To take the chomp out of it, we'll do a simple NURBS trimming operation.
First, create a curve that describes the shape of the bite mark required. Because this is supposed to somehow work on the valve nuts of the fire hydrant, it's a good idea for the curve to generally matches the shape of the nut itself. Because these nuts are five-sided, create a linear NURBS circle with five sections in the Front view as a template. Draw the curve (see Figure 12) to describe the shape of Spot's bite. Because the curve is intended to look somewhat irregular, yet fairly symmetrical, create it freehand and massage it a bit so that it has a credible dog-induced shape.
Figure 12 Spot's bite curve shape.
Duplicate the bite curve and move it to one side of the bone end, completely outside of the bone surface. Move the original to the other side, and then use Loft to construct a surface between them. In case the interior shape of the bite needs adjusting, create this lofted surface as a cubic surface with two spans (see Figure 13). It's unlikely that we'll fuss over this shape, but it's handy to already have the CVs in place if we do.
Figure 13 Lofted bite surface through the end of BigBone.
With the bone surface and bite surface now passing through one another, use the Intersect Surfaces tool to generate curve-on-surface entities for both surfaces. Then trim the surfaces using the Trim tool and examine the result (see Figure 14).
Figure 14 Result of trimming out the bite in BigBone.
The result looks awfully sharp (and the sharp edges can cause shading difficulties). Undo the intersection results and use the Circular Fillet tool instead. Use a radius of 0.05 inch and enable curve-on-surface creation to achieve a resulting fillet that looks promising. After trimming, it looks just about right (see Figure 15).
NOTE
Circular fillets are constructed by offsetting the two surfaces in their normal directions. If you don't get the fillet in the location you wanted (there are four possible locations), reverse the normal of one or both to produce a fillet in the required location.
Figure 15 Result of filleting the bite in BigBone.
Good enough! The bone won't be seen too closely or for too long, so that'll do. The geometry is ready.
Now group, name, and set the resulting surfaces to a consistent normal direction (in case the shading approach cares about such things). Grouping and naming are straightforward, but to set normal directions, just select the new object (named BigBone now) and open the Attribute spreadsheet. Click the Render tab and set the Double Sided attributes to Off (entering 0 is a handy shortcut). If any surfaces are inside-out (see Figure 16), use the Reverse Surface Direction tool to reverse either U or V (not both) for the offending surfaces. If you don't care to have single-sided surfaces, feel free to set Double Sided back to On (1).
Figure 16 Inconsistent surface normals need to be flipped.
Now it's time to assign a suitable surface shader. If you try to call the shader BigBone, you'll find that the name has already taken (by the object you just named). Shaders and objects share the same namespaces, so use a naming convention that easily distinguishes between them (such as adding a suffix or prefix to all shader names).
With the shader assignment in place (even if the shader details aren't ironed out yet), the model is ready to go (see Figure 17).
Figure 17 Ready-to-use BigBone model.
To ensure that the model used is only the object itself (and not the construction curves, et al., which are also in the file), pick just the BigBone object and export it to its own file with the File, Export Selection command. If you'd like to compare yours with mine, check out the scene file BigBoneReady.ma. Leave previously saved files in the BigBone project, in case you need them later. The exported file will be used to incorporate the BigBone into the Parking Spot project for the appropriate scenes.
Although the BigBone model isn't a difficult model, it has given us an opportunity to show some prop-modeling decisions in action. | http://www.peachpit.com/articles/article.aspx?p=31348 | CC-MAIN-2014-15 | refinedweb | 1,933 | 70.63 |
Long ago, I wrote a post on the first part of DF benefits. Now, I’m finally getting back to it. My apologies about the laxness in posting. Blame it on my Cards losing to the Sox. And on being really busy with testpasses and bug bounces for a while. We’re finally settling down a little bit, so that gives me time to pull out the keyboard and do some more blogging.
Last time, we discussed ref types on the stack, and the benefits they provide. But, if you can put ref types on the stack, where else can you put them? Try this one on for size:
using namespace System;
ref struct A{ ~A(){ Console::WriteLine(“~A()”); } };
ref struct B{
A a1;
A a2;
};
int main(){
B b;
}
Compile and run that, and you’ll see ~A() output twice. Now, you can have ref types as class members, and we call the destructors for you automatically. Dig this, they can even be static! The same rules as native C++ apply all over the place. If I want to call a constructor with arguments, I can do it inside the ctor initializer list. And object unwinding works as well.
Okay, so maybe I didn’t need to split this into a separate posting. I could have bundled it, and divluged this little nugget of coolness weeks ago. In any case, next time, I’ll wrap up this whole DF business with a discussion on how our DF model works with the CLR Dispose pattern. (See part 1, or some CLR persons’ blog for more on the CLR Dispose pattern.) After that, I’ll probably get into copy ctors on ref types, or maybe my new favorite subject: hidebysig.
Thanks for the great idea! 🙂
PingBack from
PingBack from | https://blogs.msdn.microsoft.com/arich/2004/11/05/deterministic-finalization-iv-benefits-part-ii/ | CC-MAIN-2016-36 | refinedweb | 298 | 82.85 |
JavaScript allows you to update HTML without reloading the page. This makes the interaction with your website faster as you only need to upload some parts of the page instead of the whole page. jQuery is a popular JavaScript library used by a lot of developers regardless of the language or framework used.
This tutorial focuses on using jQuery with Rails. This is for you if you are:
- a Rails developer new to jQuery
- familiar with jQuery but new to Rails
We'll talk about:
Creating a new Rails app
Effects
Events
Selectors
JavaScript Console
Notes
Conclusion
jQuery With Rails Step By Step
jQuery provides a lot of features but we'll start with the basics. We'll discuss Effects, Events, and Selectors. In the future, I will dedicate a whole post for Ajax which is used to make remote requests.
There are other JavaScript libraries or frameworks that can be used with Rails like Turbolinks, React, Vue, or Ember. At some point, your app might need one of these but today we'll discuss jQuery. If you want to suggest a topic for a future blog post, please leave a comment below.
Create the Rails app
You can follow along and start from scratch or you can clone the full application here.
Generate a new Rails 5.1 application named tutorialapp. This is a simple app that displays a list of tutorials saved in the database.
rails new tutorialapp --skip-turbolinks
Starting Rails 5.1, jQuery is not included by default. Let's add it on the Gemfile.
gem 'jquery-rails'
The jquery-rails gem contains the jQuery files. Install the gem with
cd tutorialapp bundle install
To include the jQuery files in our application, we will require a few files on
app/assets/javascripts/application.js. We'll also remove
rails-ujs since we're using jquery_ujs for the same purpose.
//= require jquery3 //= require jquery_ujs //= require_tree .
Now, let's generate the tutorial resource which will create the Tutorial model and controller and update the routes. The model will have a title and a url, both Strings.
rails g resource tutorial title:string url:string
On
app/controllers/tutorials_controller.rb, add the index action.
def index @tutorials = Tutorial.all end
On the index view
app/views/tutorials/index.html.erb, display all the tutorials.
<h1>Tutorials</h1> <ul> <% @tutorials.each do |tutorial| %> <li><%= tutorial.title %></li> <% end %> </ul>
Before we start the application, let's add a few records so our app has data to display. Add the following to
db/seeds.rb.
Tutorial.create(title: 'Encrypted Rails Secrets on Rails 5.1', url: '') Tutorial.create(title: 'Using Docker for Rails', url: '') Tutorial.create(title: 'Running a Rails App in Kubernetes', url: '')
Then run the migration and seed commands.
bin/rake db:migrate bin/rake db:seed
Start the application and go to the tutorials index page.
bin/rails server
On your browser, go to
This is a standard Rails application so far. Now let's add some jQuery code. We'll add a Hide link beside each tutorial. When you click Hide, the tutorial will be hidden without reloading the page. We will not delete the tutorial from the database for now.
Change the view
app/views/tutorials/index.html.erb to include the Hide link
<h1>Tutorials</h1> <ul> <% @tutorials.each do |tutorial| %> <li><%= tutorial.title %> <%= link_to "Hide", "", class: 'hide', data: {'js-hide-link' => true} %></li> <% end %> </ul>
We use a data attribute js-hide-link which we'll use in our JavaScript code. The code above will result in
<a data-Hide</a>
On application.js,
$(document).ready(function() { $('[data-js-hide-link]').click(function(event){ alert('You clicked the Hide link'); event.preventDefault(); }); }
Let's take a look at this code line by line. The whole thing is wrapped around
$(document).ready. We need this so that our JavaScript code gets loaded after the DOM is ready.
Now we get all elements that has the data-js-hide-link attribute with
$('[data-js-hide-link]') and bind an event handler using
.click(). When the link is clicked, the function will be called.
Inside the function, I used an alert to visually confirm that our code works. We'll remove this later.
We call
event.preventDefault() to prevent the page from reloading as the link points to the same page. A new request will be made and the page will load again without this code.
Reload the page, you don't need to restart the Rails app. When you click Hide you should see an alert. When that's working, replace the alert with this code
$(this).parents('li').hide();
$(this) refers to the
a element and
parents('li') refers to the
li element.
hide() is the jQuery method to hide the element from the page.
Try it. Clicking Hide should hide the tutorial from the page.
Effects
If you want to use effects other than
hide(), check out the API documentation for Effects. You can use for example,
fadeOut to hide the tutorial gradually.
$(document).ready(function() { $('[data-js-hide-link]').click(function(event){ $(this).parents('li').fadeOut(2000); event.preventDefault(); }); }
Events
click isn't the only event you can bind to. The API documentation for Events lists all the events. Below, we will add a text field and add JavaScript code that fires up after you type on the text field.
On the view
app/views/tutorials/index.html, add a search text field.
Search <%= text_field_tag 'search', '', data: {'js-search' => true} %>
On application.js, inside
$(document).ready(function() { add
$('[data-js-search]').change(function(event) { search_term = $(this).val(); alert('You are searching for ' + search_term); });
When you type some text and press tab or click anywhere on the screen, an alert will show up and display the text you typed on the text field. The text is retrieved using
val(). We will not build the actual search functionality. The search text field is only used to demonstrate the
change() event.
Selectors
So far, we select elements using the data attribute like
$('[data-js-search]'). There are multiple ways to select elements as you can see on the API documentation for Selectors.
In fact, most tutorials out there use classes or ids. The search text field above has an id of search. The html produced by
text_field_tag is
Search <input type="text" name="search" id="search" value="" data-
Your JavaScript code can then use
$('#search').change(function(event) { .... You can (but shouldn't) even remove the data attributes since you can find the element using the id.
The Hide links above have a class of 'hide'. You can use
$('.hide').click(function(event){. You can also use
$('a').click(function(event){ to select all
<a> elements.
To summarize, you can use
# for ids,
. for classes, and the element name
a inside
$(). However, it is recommended that you use data-* attributes like
$('[data-js-search]') instead of ids and classes. I only showed you the selectors for ids and classes because most tutorials will use these.
Ids and classes are used to style HTML using CSS. We can style all elements with the
.hide class to have a color of red by adding the code below on
app/views/stylesheets/application.css.
.hide { color: red; }
Using a class selector
$('.hide') works but then you'll be using the hide class for both CSS and JavaScript. If you don't like to use a data attribute and prefer classes, you should at least add a different class like
js-hide to have separate classes for CSS and JavaScript.
JavaScript Console
When writing code in JavaScript, it is helpful to look at the JavaScript Console for possible errors. In Chrome, you can open the JavaScript Console by going to View then Developer.
You can use
console.log to log information on the console. Another option is to add
debugger. We use both options below.
$(document).ready(function() { $('[data-js-hide-link]').click(function(event){ console.log('You clicked the Hide link'); debugger $(this).parents('li').fadeOut(2000); event.preventDefault(); }); }
When you click Hide, the debugger will pause the script execution and show you the line where you called
debugger under the Sources tab. You can inspect the local and global variables on the right side.
Click the Console tab to go back to the JavaScript Console. You will see 'You clicked the Hide link'. You can also use
$(this) which points to the
a element at this point as you're inside the function passed to
click(). Type
$(this).parents('li').fadeOut(2000); and
$(this).parents('li').fadeIn(2000); and you will see the
li element fade out and in.
When you're done debugging, click the Resume button under the Sources tab or F8 to resume the script execution.
Notes
- The jquery-rails gem contains all 3 jQuery versions. You can use jQuery 1, 2, and 3 by requiring jquery, jquery2, and jquery3 on application.js respectively. You can view the versions included in the gem on this page.
- We put the JavaScript code on application.js and CSS code on application.css but in your application, you should put them on their respective files.
- The jquery-rails gem was removed as a dependency starting Rails 5.1. It does not mean that jQuery is not recommended to be used. jQuery as a default library is mainly used for Unobtrusive JavaScript which we'll take more about in a future post.
- The use of data attributes instead of classes is documented more on this repo. Thank you to Rico Sta. Cruz for creating this guide.
Conclusion
This tutorial got you started with using jQuery on your Rails application. We discussed data attributes, using them on your Selectors, binding to Events, and using Effects when the Events are triggered. There are more things we can discuss but you should now be able to go to the jQuery API documentation or follow other jQuery tutorials for additional learning.
Was this tutorial helpful to you? Do you have suggestions on future topics? We like to hear from you in our Comments section. | https://blog.engineyard.com/using-jquery-with-rails-how-to | CC-MAIN-2020-24 | refinedweb | 1,681 | 68.36 |
Micro Frameworks
I came across Bottle today and thought it was kind of silly. Not in the sense that the actual framework design or functionality is silly, but rather that there are so many attempts to make stripped down frameworks. There is really nothing wrong with making these frameworks. I’m sure the authors learn a lot and they scratch an itch. Every time one comes up though, I wonder about something similar built on CherryPy and I’m reminded that CP is really the original microframework and works even better than ever.
Even though CP has become my framework of choice, others may not realize how it really is similar to the other micro frameworks out there with the main difference being it has been tested in the real world for years. Lets take a really simple example of templates and see how we can make it easy to use Mako with CherryPy.
First off, lets write a little controller that will be our application. I’m going to use the CP method dispatcher.
import cherrypy class SayHello(object): exposed = True # the handler is exposed or else a 404 is raised. very pythonic! def GET(self, user, id): some_obj = db.find(user, id) return { 'model': some_obj } def POST(self, user, id, new_foo, *args, **kw): updated_foo = SomeModel(user, id, new_foo) updated_foo.save() raise cherrypy.HTTPRedirect(cherrypy.request.path_info)
I’ve kind of stacked the deck a little bit here with my ‘GET’ method. It is returning a dict because we are going to use that to pass info into a render function that renders the template. There are many ways you could do this, but since I like to reuse the template look up, I’ll make a subclass that includes a render function.
import os import cherrypy import json from mako.template import Template from mako.lookup import TemplateLookup __here__ = os.path.dirname(os.path.abspath(__file__)) class RenderTemplate(object): def __init__(self): self.directories = [ os.path.normpath(os.path.join(__here__, 'view/')) ] self.theme = TemplateLookup( directories=self.directories, output_encoding='utf-8' ) self.constants = { 'req': cherrypy.request, } def __call__(self, template, **params): tmpl = self.theme.get_template(template) kw = self.constants.copy() kw.update(params) return tmpl.render(**kw) _render = RenderTemplate() class PageMixin(object): def render(self, tmpl, params=None): params = params or {} params.update(dict([ (name, getattr(self, name)) for name in dir(self) if not name.startswith('_') ])) return _render(tmpl, **params) def json(self, obj): cherrypy.response.headers['Content-Type'] = 'application/json' return json.dumps(obj)
There is a bunch of extra code here but what I’m doing is setting up a simple wrapper around the Mako template and template look up. I could have use pgk_resources as well here. You’ll also notice that the handler will automatically get the cherrypy.request as a constant called ‘req’ for use in the template. Below our renderer is a PageMixin. I do this b/c it is easy to add simple functions to make certain aspects faster, for example, quickly returning JSON.
Here is how our controller class’ GET method would change.
def GET(self, user, id): some_obj = db.find(user, id) return self.render('foo.mako', { 'model': some_obj })
Pretty simple really. I could try to get more clever by automatically passing in our locals() or do some other tricks to make things a little more magic, but that is really not the point. The point here is that I’m just using Python. I don’t have to use CherryPy Tools to make major changes to the way everything works. Including a library is just an import away. If I wanted to write my render function as a decorator that is possible since it would just be a matter of writing the wrapper. If we wanted to do some sort of a cascaded look up on template files, no problem. It is all just Python.
To wrap things up, the other day I started looking into writing a Tool for CherryPy. After messing with things a bit, I came to the conclusion I wasn’t really a huge fan of the Tool API. After thinking of ways I could improve it and getting some good ideas from Bob, something struck me. The Tool API has been around for a long time and yet it never has been a really important part of my writing apps with CherryPy. The reason is really simple. I can write Python with CherryPy. Python has decorators, itertools, functools, context managers and a whole host of facilities for doing things like wrapping function calls. It doesn’t mean I can’t write a tool, but I don’t have to. The framework is asking me to either. When I used WSGI, I would write my whole application as bits of middleware and compose the pieces. It felt reusable and very powerful, but it also ended up being a pain in the neck. Frameworks have a tendency to be opinionated and while CherryPy is seemingly rather unbiased, I’d argue the real opinion it reflects is “quick messing with frameworks and get things done”. I like that. | http://ionrock.org/2010/12/21/micro-frameworks.html | CC-MAIN-2017-17 | refinedweb | 854 | 67.15 |
Changelog History
Changelog History
v0.6.0September 29, 2017
🚀 This release contains no other changes than updated project settings to target Swift 4.
Coming from earlier versions you will be faced with errors like
'Decodable' is ambiguous for type lookup in this context. Unfortunately you have to use the following import-syntax to get around it:
import protocol Decodable.Decodable
where you can also import other structs and enums as required.
-
v0.5September 12, 2016
v0.4.4July 09, 2016
- ⬆️ Project settings upgraded to support Xcode 8 with legacy Swift 2.3 support.
🚀 Note: Unsure if this works with Xcode 7 or if you explicitly have to target
v0.4.3. And if you've clicked on the releases page and wonder where the Swift 3 support is, it's on the master branch. Stable releases are coming.
- | https://swift.libhunt.com/decodable-changelog | CC-MAIN-2021-17 | refinedweb | 138 | 67.15 |
The DipoleShowerHandler class manages the showering using the dipole shower algorithm. More...
#include <DipoleShowerHandler.h>
The DipoleShowerHandler class manages the showering using the dipole shower algorithm.
Definition at line 44 of file DipoleShowerHandler.h.
Make a simple clone of this object.
Reimplemented from Herwig::ShowerHandler.
Finalize this object.
Called in the run phase just after a run has ended. Used eg. to write out statistics.
Reimplemented from Herwig::ShowerHandler.
Initialize this object after the setup phase before saving an EventGenerator to disk.
Reimplemented from Herwig::ShowerHandler.
Initialize this object.
Called in the run phase just before a run begins.
Reimplemented from Herwig::ShowerHandler.
Make a clone of this object, possibly modifying the cloned object to make it sane.
Reimplemented from Herwig::ShowerHandler..
Set the pointer to the Merging Helper.
Used by the merging factory.
Definition at line 131 of file DipoleShowerHandler.h.
The static object used to initialize the description of this class.
Indicates that this is a concrete class with persistent data.
Definition at line 507 of file DipoleShowerHandler.h.
Limit the number of emissions.
Limit applied if > 0.
Definition at line 364 of file DipoleShowerHandler.h.
The merging helper takes care of merging multiple LO and NLO cross sections.
Here we need to check if an emission would radiate in the matrix element region of an other multipicity. If so, the emission is vetoed.
Definition at line 497 of file DipoleShowerHandler.h.
The verbosity level.
0 - print no info 1 - print diagnostic information on setting up splitting generators etc. 2 - print detailed event information for up to printEvent events. 3 - print dipole chains after each splitting.
Definition at line 397 of file DipoleShowerHandler.h. | http://herwig.hepforge.org/doxygen/classHerwig_1_1DipoleShowerHandler.html | CC-MAIN-2018-05 | refinedweb | 276 | 55.1 |
Lopy GPS/DHT/RFiD
Hi all
so now that I have my Lopy working with my own LoraWan network (based on RPi+ic880 and Loraserver+ mainflux)
I wanted to add sensors to the Lopy
is there already a DHT library
a GPS library ? I connected my GPS (I didn't get any pytrack yet) sensors through UART but there is no sentence support for the reading I found a python micropython lib called micropyGPS but I'm still having issue with the lib
any suggestion are welcome
I'll share some of the code later (from Lora or LoraWAN to mqtt server)
@100rabhh : Just put these lines to your code:
from nmeaParser import NmeaParser #Create NMEA structure nmea = NmeaParser() #..then send your uart input to the library if gps_uart.any(): nmea.update(gps_uart.readline()) #...then you can access your data by print ('Latitude: ' + str(nmea.latitude)) print ('Longitude: ' + str(nmea.longitude)) print('Altitude:'+ str(nmea.altitude)) #...there are several other data available, just check the parser code for more info
@affoltep Hi, How can i use it with my code?
Here is my simple receive code for Adafruit Ultimate Breakout GPS----
from machine import Pin
from machine import UART
#Interface definitons for GPS
gps_pps = Pin('P23', mode = Pin.IN)
gps_enable = Pin('P8', mode=Pin.OUT)
gps_enable(False)
#gps_uart = UART(2, 9600)
#gps_uart.init(9600, bits=8, parity=None, stop=1)
gps_uart = UART(2, baudrate=9600, bits=8, parity=None, stop=1, pins=('P10', 'P11'))
uart.write('abs')
gps_enable(True)
while True:
if gps_uart.any():
print(gps_uart.readline())
Here i am simply reading the strings from GPS Rx. Now how do i implement in your code to parse it? Please help...
Cool the GPS part work well
Beside DHT11 that is reading all the time zero all the other are working well
PIR, RFId, GPS, Distnace , all this with Lora working to send the messages
Next is accelerometer MPU 92/65
@johnmcdnz Cool, thanks - in case it still doesn't work, feel free to come to this quarter, spring is starting here ;o)
@affoltep The NmeaParser codes works really well (almost) :-)
I've been using it this weekend, and discovered a minor flaw, and have fix for you.
The code ignores the S/W hemispheres, so will only be correct for 1/4 of the planet.
This change provides the correction
# Update Object Data
self.latitude = lat_degs + (lat_mins/60)
if lat_hemi == 'S':
self.latitude = -self.latitude
self.longitude = lon_degs + (lon_mins/60)
if lon_hemi == 'W':
self.longitude = -self.longitude
Good job I can test in the Southern hemisphere and spot the problem!
Once I have my project working I'll post on github.
@Movsun I changed the name to DHT22RinusW-call.py. Described in the readme.
I never got the dht working I get always 28025 which is the zero values
not sure id there are other action or I'm missing soemthing from teh library DHT itself
>>> import DHT >>> dht_pin=Pin('P19', Pin.OPEN_DRAIN) >>> dht_pin(1) >>> temp, hum = DHT.DHT11(dht_pin) >>> temp_str = '{}.2{}'.format(temp//10,temp%10) >>> hum_str = '{}.2{}'.format(hum//10,hum%10) >>> print("sending Temp/Hum : %s/%s" % (temp_str,hum_str)) sending Temp/Hum : 280.25/280.25
@johnmcdnz
Hello, I look into your github repository. But I count not find DHT22RinusW.py file.
Where can I find the file? Thank you in advance.
@gas I wrote a minimalistic NMEA parser, based on micropyGPS, which parses just the GPGGA messages. This message delivers lon, lat, alt, hdop and UTC. Feel free to use it.
#Minimalistic NMEA-0183 message parser, based on micropyGPS #Version 0.1 - January 2017 #Autor: Peter Affolter import utime class NmeaParser(object): """NMEA Sentence Parser. Creates object that stores all relevant GPS data and statistics. Parses sentences using update(). """ def __init__(self): """Setup GPS Object Status Flags, Internal Data Registers, etc""" ##################### # Data From Sentences # Time self.utc = (0) # Object Status Flags self.fix_time = 0 self.valid_sentence = False # Position/Motion self.latitude = 0.0 self.longitude = 0.0 self.altitude = 0.0 # GPS Info self.satellites_in_use = 0 self.hdop = 0.0 self.fix_stat = 0 #raw data segments self.nmea_segments = [] def update(self, sentence): self.valid_sentence = False self.nmea_segments = str(sentence).split(',') #Parse GPGGA if (self.nmea_segments[0] == "b'$GPGGA"): self.valid_sentence = True try: # UTC Timestamp utc_string = self.nmea_segments[1] # Skip timestamp if receiver doesn't have on yet if utc_string: hours = int(utc_string[0:2]) minutes = int(utc_string[2:4]) seconds = float(utc_string[4:]) else: hours = 0 minutes = 0 seconds = 0.0 # Number of Satellites in Use satellites_in_use = int(self.nmea_segments[7]) # Horizontal Dilution of Precision hdop = float(self.nmea_segments[8]) # Get Fix Status fix_stat = int(self.nmea_segments[6]) except ValueError: return False # Process Location and Speed Data if Fix is GOOD if fix_stat: # Longitude / Latitude try: # Latitude l_string = self.nmea_segments[2] lat_degs = float(l_string[0:2]) lat_mins = float(l_string[2:]) # Longitude l_string = self.nmea_segments[4] lon_degs = float(l_string[0:3]) lon_mins = float(l_string[3:]) except ValueError: return False # Altitude / Height Above Geoid try: altitude = float(self.nmea_segments[9]) geoid_height = float(self.nmea_segments[11]) except ValueError: return False # Update Object Data self.latitude = lat_degs + (lat_mins/60) self.longitude = lon_degs + (lon_mins/60) self.altitude = altitude self.geoid_height = geoid_height # Update Object Data self.timestamp = (hours, minutes, seconds) self.satellites_in_use = satellites_in_use self.hdop = hdop self.fix_stat = fix_stat # If Fix is GOOD, update fix timestamp if fix_stat: self.fix_time = utime.time() return True
I have connected the DHT22 sensor and had working very well. My code and description is here. Pay attention to the sample size change I made and that I had to adjust the bit sampling. Using the print statements to debug and understanding the one wire protocol can help in fine tuning the data conversion. Hope this helps. | https://forum.pycom.io/topic/780/lopy-gps-dht-rfid | CC-MAIN-2018-39 | refinedweb | 950 | 60.21 |
I have a couple of template classes "Stats<T>" and "Numerical<T>" within a "Statistics" namespace. The Numerical<T> class inherits publicly from Stats<T>. They are defined as below.
namespace Statistics { //declare Statistics namespace template <typename T> class Stats { protected: vector<T> dataSet; //contains the actual data set to be analyzed /* ... other members and declarations ... */ }; //end Stats Class template <typename T> class Numerical : public Stats<T> { protected: double mean; //the numeric average /* ... other members ... */ void updateMean(); //called by other methods to update the mean when necessary /* ... other declarations ... */ }; //end Numerical Class } //end Statistics namespace
Now here's where the question comes in. I'm working on the implementation of Numerical<T>::updateMean(), and based on the class structure above, the method should have access to the dataSet vector. The problem that I'm having is that I seem to have to resolve the Stats class every time I want to use one of its members from Numerical. I don't remember having to do that before.
Is this normal? Or is there some nuance that I'm missing somewhere? Do I need to add some sort of using statement(s) to the Numerical class?
Implementation of method:
namespace Statistics { //declare Statistics namespace /* ... other implementations ... */ template <typename T> void Numerical<T>::updateMean() { vector<T>::const_iterator cpData; double sigma = 0.0; if (Stats::dataSet.size() == 0) { this->mean = 0.0; return; } for (cpData = Stats::dataSet.begin(); cpData != Stats::dataSet.end(); ++cpData) { sigma += (*cpData); } mean = (sigma / Stats::dataSet.size()); } /* ... other implementations ... */ } //end Statistics namespace
I foresee this same issue extending to every other method as well. I know how to deal with it if necessary, but if I can avoid it altogether that would be great. | https://www.daniweb.com/programming/software-development/threads/317496/templates-inheritance-and-name-resolution | CC-MAIN-2017-43 | refinedweb | 284 | 51.24 |
Lenz Grimmer wrote: > >. > > Yes! This is something I was waiting for a long time ago. I always had the > feeling, that LSB is not addressing the most pressing problems first. Most > users today complain about wrong or missing dependencies and different > names for the same package on different distributions. SuSE has finally > come around with using longer names for their packages (no more 8 char > cryptic names) and we would be more than happy to change the package names > to the most common denominator. Is there such a thing as a common package > namespace?. This sounds like a small, reasonable task. Is it? If progress can be made on this, people might start feeling better about the state of the LSB. - Dan | https://lists.debian.org/lsb-discuss/2000/10/msg00044.html | CC-MAIN-2021-04 | refinedweb | 122 | 72.87 |
IRC log of xproc on 2010-08-26
Timestamps are in UTC.
15:00:08 [RRSAgent]
RRSAgent has joined #xproc
15:00:08 [RRSAgent]
logging to
15:00:28 [ht]
zakim, code?
15:00:29 [Zakim]
the conference code is 97762 (tel:+1.617.761.6200 tel:+33.4.26.46.79.03 tel:+44.203.318.0479), ht
15:00:48 [Zakim]
XML_PMWG()11:00AM has now started
15:00:52 [Zakim]
+[ArborText]
15:01:53 [Norm]
On my way
15:02:21 [Vojtech]
Vojtech has joined #xproc
15:03:00 [Norm]
Meeting: XML Processing Model WG
15:03:00 [Norm]
Date: 26 August 2010
15:03:00 [Norm]
Agenda:
15:03:00 [Norm]
Meeting: 179
15:03:00 [Norm]
Chair: Norm
15:03:01 [Norm]
Scribe: Norm
15:03:03 [Norm]
ScribeNick: Norm
15:03:09 [Zakim]
+[IPcaller]
15:03:13 [Zakim]
-PGrosso
15:03:14 [Zakim]
+PGrosso
15:03:16 [ht]
zakim, [ is me
15:03:17 [Zakim]
+Norm
15:03:47 [Zakim]
+ht; got it
15:03:54 [Zakim]
+Jeroen
15:04:01 [Vojtech]
zakim, jeroen is Vojtech
15:04:07 [Zakim]
+Vojtech; got it
15:04:10 [Norm]
zakim, who's here?
15:04:14 [Norm]
Regrets: Mohamed
15:04:18 [Zakim]
On the phone I see PGrosso, ht, Norm, Vojtech
15:04:26 [Zakim]
On IRC I see Vojtech, RRSAgent, Norm, Zakim, PGrosso, ht, Liam, caribou
15:04:27 [Norm]
Present: Paul, Henry, Norm, Vojtech
15:05:02 [Norm]
Topic: Accept this agenda?
15:05:02 [Norm]
->
15:05:07 [Norm]
Accepted.
15:05:15 [Norm]
Regrets: Mohamed, Alex
15:05:20 [Norm]
Topic: Accept minutes from the previous meeting?
15:05:20 [Norm]
->
15:05:28 [Norm]
Accepted.
15:05:33 [Norm]
Norm's action is continued. :-(
15:05:40 [Norm]
Topic: Next meeting: telcon, 2 September 2010?
15:06:12 [Norm]
Vojtech gives regrets for 2 September.
15:06:18 [Norm]
Propose to cancel 9 September.
15:06:34 [Norm]
Accepted.
15:07:02 [Norm]
Topic: Comments on XML processor profiles
15:07:45 [Norm]
Henry: I'd like to talk about whether people think Section 3 is useful.
15:08:29 [Norm]
->
15:08:52 [Norm]
->
15:12:04 [Norm]
Norm: I like it. I think it's good to ground our work in the Infoset. I just didn't have a chance to look at the detail.
15:12:14 [Norm]
Henry: I'm happy to let the public help with that.
15:12:48 [Norm]
Henry: I don't like the layout, the "Whether the remaining information item is present is implementation-defined" line is too subtle.
15:13:24 [Norm]
Henry: I think I'd like to say "fix that", fix the other obvious editorial problem wrt the word "ditto", and republish, asking for comments.
15:13:49 [Norm]
Norm: That seems fine to me.
15:14:19 [Norm]
Vojtech: Before we tried to stay away from using infoset terms. I wonder if that's ok, or ...
15:14:33 [Norm]
Henry: I think it is. I don't know what else to do.
15:15:24 [Norm]
Norm: I fear if we don't ground it in the infoset, then it will either not be grounded or we'll have to recapitulate the Infoset.
15:15:46 [Norm]
Vojtech: Does that mean we should use the infoset terms for, for example, base URI, in the profiles?
15:16:24 [Norm]
Henry: I'm not sure, I think we chose that wording very carefully.
15:16:33 [Norm]
...I don't think there's any conflict between the specs.
15:16:46 [Norm]
Norm: I don't think we're obligated to update the language spec based on our terms in this spec.
15:17:00 [Norm]
Henry: Ok. I'll try to have a draft ready in the next 10 days or so.
15:18:57 [Norm]
Topic: What's the progression of this document?
15:19:16 [Norm]
Paul: Does this document go through CR? Does it go directly to PR? What do we need to do?
15:19:31 [Norm]
Norm: Good question.
15:20:29 [Norm]
Norm: I guess we need to get the staff contact involved. I'd be a little disappointed if we had to make it a Note, but it wouldn't be the end of the world.
15:20:55 [Norm]
ACTION: Norm to touch base with the staff contact to see what they suggest.
15:21:34 [Norm]
Topic: Possible new XProc 1.1 step: p:template
15:22:51 [Norm]
Norm attempts to paraphrase the problem: making it easier to construct fragments of XML from variables and expressions in an XProc pipeline.
15:23:59 [Norm]
Henry encourages us to look at the discussion of Richard Tobin's XML tools functionality near the end of his first message.
15:25:53 [Norm]
Henry: As Vojtech observed, there are two things going on, abbreviating the p:input and interpolation.
15:26:54 [Norm]
Norm: I find the change in the the content model of steps a bit disturbing.
15:27:03 [Norm]
Henry: I also want the variable bindings to be on other ports.
15:27:10 [Norm]
Norm: I think you'll need to stick those in variables.
15:27:31 [Norm]
Henry: The template has to come from a secondary port so that you can write things as I do in the reply to Vojtech.
15:28:48 [Norm]
Vojtech: My problem with the original syntax is that it's not clear how to create elements in the XProc namespace and maybe there would be value in being able to generate the templates dynamically.
15:29:40 [Norm]
Norm: I proposed p:interpolated-inline.
15:30:14 [Norm]
Henry: The problem I have with this is there's no match attribute. There's a fundamental semantic difference, yours takes a document and does what it does with it.
15:30:35 [Norm]
...whereas my proposal uses @match to change everywhere that matches.
15:30:42 [Norm]
Vojtech: How does that differ from putting this in a viewport?
15:30:49 [Norm]
Henry: Maybe it's not, but it's a lot more verbose.
15:31:44 [Norm]
...We're very clear in the document that the only bindings that are visible to step implementations are the option and parameter bindings. And for this to be implemented as a step would require us to break that rule. The curly brace substitution has to be done by the step.
15:31:59 [Norm]
Vojtech: I proposed that we could do it with a parameter input port where you'd pass all these bindings.
15:33:06 [Norm]
Vojtech: We could add a new attribute to p:inline so that we didn't have to have a different binding.
15:34:51 [Norm]
Vojtech: Ideally it would be nice if we could make *any* kind of binding dynamic.
15:35:50 [Norm]
Norm: You could give the binding a step and port for interpolation.
15:36:06 [Norm]
...You could say <p:inline
15:37:42 [Norm]
Norm; Putting it on the binding does make sense.
15:37:47 [Norm]
s/sense./sense to me./
15:38:05 [Norm]
Vojtech: I might want to have two inputs but only have one of them be dynamic.
15:39:13 [Norm]
Norm: To cut the other way entirely, if we allowed AVTs in literal option values, would that be enough?
15:39:29 [Norm]
Vojtech: I think we'd still have the p:string-replace quoting issues.
15:39:42 [Norm]
Henry: It might be a good idea to do that, but I don't think it solves this problem.
15:40:53 [Norm]
Norm: I need to think about this some more.
15:41:15 [Norm]
Vojtech: Yes, there are two parts, enabling templating and deciding what the substitution rules are.
15:41:25 [Norm]
Henry: Right. I don't want to go all the way to the bottom of the slippery slope.
15:42:44 [Norm]
...I think saying that curly braces in literal content (attribute values or text content) is enough.
15:43:06 [Norm]
Vojtech: We could do like p:exec and allow users to specify the quoting characters.
15:43:24 [Norm]
Henry: We're doing just the part of XQuery syntax that does XPath expressions, not full XQuery constructors.
15:44:31 [ht]
<elt attr="{concat($a,'}')}"/>
15:45:35 [ht]
<elt attr="{concat($a,'}}')}"/>
15:46:52 [Norm]
Some discussion of escaping curly braces.
15:47:36 [Vojtech]
So how would I create the following document: <doc>{}</doc> ?
15:47:48 [Norm]
<doc>{{{}}}</doc>
15:48:18 [Norm]
Of course!
15:49:21 [Norm]
Norm: I think that's good progress on the issue.
15:49:27 [Norm]
Topic: Any other business?
15:49:51 [Norm]
Norm: I think TPAC registration and hotels are ready for booking.
15:52:32 [Norm]
Adjourned.
15:52:37 [Zakim]
-Vojtech
15:52:39 [Zakim]
-PGrosso
15:52:39 [Zakim]
-Norm
15:52:42 [Zakim]
-ht
15:52:42 [Norm]
rrsagent, draft minutes
15:52:42 [RRSAgent]
I have made the request to generate
Norm
15:52:43 [Zakim]
XML_PMWG()11:00AM has ended
15:52:44 [Zakim]
Attendees were PGrosso, [IPcaller], Norm, ht, Vojtech
15:52:48 [Norm]
rrsagent, set logs world-visible
15:52:56 [Norm]
rrsagent, draft minutes
15:52:56 [RRSAgent]
I have made the request to generate
Norm
15:53:11 [PGrosso]
PGrosso has left #xproc
15:53:21 [Norm]
Oh, crap. I generated the minutes before changing the logs, now I can't read the f'ing minutes
15:53:35 [Norm]
Oh, hey, it *did* fix itself. Yay!
17:25:27 [Zakim]
Zakim has left #xproc | http://www.w3.org/2010/08/26-xproc-irc | CC-MAIN-2014-10 | refinedweb | 1,634 | 81.33 |
Structure and macros for filesystem events
#include <sys/fs_events.h> typedef struct fse_event_s { uint32_t signature; /* Version and fixed identifier */ uint16_t length; /* Type and length of the event data */ uint16_t command; /* Command / request information */ uint32_t properties; /* Classification of the event */ uint32_t reserved; /* Reserved for future use (zero) */ uint32_t identity; /* Locale and ID of the event */ } fsev_t;
The <sys/fs_events.h> header file includes everything necessary to read and process events from the filesystem event manager, fsevmgr.
The fsev_t structure is a header that describes a filesystem event, including its origin, locale, and identity. It's followed by any data associated with the event. Generally the data is a path string, but depends on the type of event.
Events are organized into tuples that have a common header, a description of the event, and length of that event. The length field represents the entire length from the starting address of the tuple.
You read an event from the event manager into an array of bytes, but there's no guarantee of alignment, so you should use the FSE_READ_EVENT_S() macro—which is a cover for the memcpy() function—to copy the data into an fsev_t structure:
#define FSE_READ_EVENT_S(pev, pdata)
where pev is a pointer to a fsev_t structure, and pdata is a pointer to the array of bytes.
To access a tuple, use the following FSE_*() macros, which take as an argument a pointer to an fsev_t structure:
Properties
Properties are boolean attributes of an event that help to describe its purpose, data, and/or impact to the system. An event can have multiple properties ORed together.
To assist in the filtering of events, properties are organized into a few groups: types, class, and data. FSE_TYPE_* properties indicate the purpose of an event; FSE_CLASS_* properties indicate the impact an event might have on a system; FSE_DATA_* properties describe attributes of the data attached to the event.
Properties of events aren't exclusive; some events may have two class properties.
Locales
Locales indicate the source of the event. An event can have only a single locale. In general, event client handlers filter out those events that don't match the locale that they're monitoring.
Event IDs
Event IDs indicate the cause of the event and the data associated with it. If the event data includes any strings, they're null-terminated.
Here's an example of extracting the information associated with an event:
char *data, *mntpath, *spacestr; size_t len; uint64_t freespace; if (FSE_ID_VAL(event) == FSE_ID_FREE_SPACE) { data = FSE_DATA_PTR(event); len = FSE_DATA_LEN(event); /* Determine the starting buffer offsets for the mount path and freespace integer value. */ mntpath = data; spacestr = data + strlen(mntpath) + 1; /* If the path exceeds the data buffer, then there's no freespace value present. */ if (spacestr >= (data + len)) { LOG(LOG_ERROR, "freespace data exceeds event buffer length (%p >= %p)", spacestr, data+len); return; } /* Convert the freespace string to a 64-bit unsigned integer value. */ else if (sscanf(spacestr, "%" PRIu64, &freespace) != 1) { LOG(LOG_ERROR, "freespace data conversion failed"); return; } }
Notes
There are several unique situations that clients of the event manager should be aware of:
Initializing events
If your client application has opened the event manager's device for writing, you can inject events. You can initialize an event structure by using the FSE_INIT_EVENT() macro:
#define FSE_INIT_EVENT(p, cmd, loc, id, prop, len)...
The arguments are:
The event manager checks the event data to ensure it's well-formed; if it isn't, the event manager aborts the writing of all events that were sent in the write operation. | http://www.qnx.com/developers/docs/6.6.0_anm11_wf10/com.qnx.doc.neutrino.lib_ref/topic/f/fse.html | CC-MAIN-2018-09 | refinedweb | 586 | 58.32 |
Fibonacci series is a series in which the next term is the sum of the previous two numbers. Here, we’ll write a program to print Fibonacci series on the basis of series elements to be printed.
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21
Logic:
We will take two variables with values 0 and 1. Then a third var which will be the sum of the first two var and then loop through it.
Algorithm:
- Take the input for the series of elements to be printed.
- Take two variable, pre and next and assign pre = 0 and next = 1.
- Take another variable, last which will be the sum of pre and next.
- Run a while loop.
- Print the value of pre.
- Change the values of pre, next and last in the loop.
- End loop after n iterations.
Code:
#include<iostream> using namespace std; int main() { int n,pre,next,last; cout<<"How many numbers of fibonacci series do you want to print?"; cin>>n; pre=0; //previous number next=1; //next number last=pre+next; while(n>0) { cout<<"\n"<<pre; pre=next; //pushing the three values ahead next=last; last=pre+next; //third number is sum of new first and second number n--; } return 0; }
Output:
How many numbers of Fibonacci series do you want to print? 10 0 1 1 2 3 5 8 13 21 34
Report Error/ Suggestion | https://www.studymite.com/cpp/examples/program-to-print-fibonacci-series-in-cpp/?utm_source=related_posts&utm_medium=related_posts | CC-MAIN-2020-05 | refinedweb | 236 | 81.12 |
CryptoNugget
Introduction
When I was writing the C Unleashed outline, I knew that I wouldn’t be able to write the whole book myself but I didn’t know who the co-authors would be and, consequently, I didn’t know which chapters they would be able to take off my hands. Sams was very keen to have a chapter on cryptography in the book. So, until Mike Wright turned up (bless him!), I was faced with the very real possibility that I might have to write the chapter myself. I’m no expert in cryptography, but it is a minor hobby of mine and when I was approached for a “nugget” - something not specifically in the book, but which might interest readers, it seemed appropriate to include an article I wrote a while back. I've edited it in much the same way that I might have edited it for the actual book. Naturally this isn’t going to be a full-blown 50-page chapter, but I hope you’ll find it diverting, anyway.
Elementary Cryptography
Let’s begin by looking at a simple cipher - a substitution cipher. This cipher substitutes each letter of the alphabet with a different one. For the purposes of this article we will consider plaintexts consisting entirely of upper case letters, to simplify matters. The techniques shown here can be easily modified for plaintexts using a computer’s entire character set or any subset thereof.
Perhaps the most common form of substitution cipher is ROT13, which is typically available on Unix systems (on my Linux system it’s called Caesar). In ROT13 each letter is rotated 13 places around the alphabet. Thus, HELLO becomes WTAAD.
We can represent this as follows:
P is the plaintext (in this case, HELLO). C is the ciphertext (in this case, WTAAD). If we call the process of substituting ROT13, then C = ROT13(P).
In this case, to decrypt the message is simple. We just ROT13 it again. Think of a dial with an indicator pointing upwards. If you move it 180 degrees clockwise, it now points downwards. Turn it 180 degrees clockwise again, and it points upwards again. Thus, P = ROT13(C) and, therefore, P = ROT13(ROT13(C)).
As you might imagine, this is not a particularly difficult cipher to crack. It is sometimes used on Usenet to allow people to read information, if they so choose, by deciphering it. For example: for all those who can’t wait for the final episode of “Dying For A Drink,” I can exclusively reveal (ROT13): GUR OHGYRE QVQ VG. As you can see, those using ROT13 will frequently publish the fact to assist people who want to decrypt the ciphertext. ROT13 is not intended to be a super-secure cipher.
Programming ROT13 is relatively trivial. Here’s C code to do it and which assumes the ASCII character set is being used:
#include <string.h> char *rot13(char *s) { char *t = s; const char *lower = “abcdefghijklmnopqrstuvwxyz”; const char *upper = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”; char *p; if(s != NULL) { while(*s) { p = strchr(lower, *s); if(p != NULL) { *s = lower[((p - lower) + 13) % 26]; } else { p = strchr(upper, *s); if(p != NULL) { *s = upper[((p - upper) + 13) % 26]; } } ++s; } } return t; }
ROT13 is, not surprisingly, easy to crack. Nevertheless, by using different rearrangements of letters some people think they can achieve security. For example, here is a substitution cipher that is possibly a shade more secure than ROT13:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
QWERTYUIOPASDFGHJKLZXCVBNM
The cipher works like this: for each character in the plaintext, find that character in the top row. Look at the character beneath it: this is the corresponding character in the ciphertext. Decryption, of course, comprises the opposite operation (look it up in the second row, convert to the character above).
Thus, HELLOWORLD becomes ITSSGVGKSR
This seems a little more secure, no doubt. Unfortunately, it’s not. A short message makes it a little harder, but not much. It is possible, and indeed trivial, to cryptanalyse substitution ciphers using letter frequencies. You can easily determine which letters are used frequently in a given language using a simple program to count alphabetic characters in a large sample of text. You can then compare that table against your ciphertext and make deductions about it. According to one analysis, the frequency of English letters is (from most common to least common) ETAONRISHDLFCMUGPYWBVKXJQZ. Your mileage may vary: it obviously depends on the text sample you use. Nevertheless, E is a clear winner, and every study I ever saw puts T second and A/O third/fourth (sometimes the other way around - O/A). Between them, these four letters account for approximately 40% of all letters used!
There is more information yet to be gained from a monoalphabetical cipher - letter patterns. For example, consider the phrase “letter pattern”. Take each word in turn, and assign each unique letter in the word a number. “Letter” gives us “123324” (1 = L, 2 = E, etc). “Pattern” gives us “1233456”.
There aren’t that many words in the English language that give us these patterns. Some duplicates exist, for example, “LET” and “CAT” have the same pattern codes, but longer words can give us useful pattern information which we can use to help us crack a monoalphabetic cipher.
The following is a sample of C code that takes a list of words, one per line, and prints out their patterns. It’s not amazingly efficient - in fact it has a time complexity of O(m2 * n) where n is the number of words and m is the average number of letters in a word. Still, it’s better than nothing. It was actually written with a Unix system’s /usr/dict/words dictionary in mind (with the idea of building a pattern dictionary for decryption) but could be simply adapted to serve as a cryptanalytic tool (and was designed with this flexibility in mind).
#include <stdio.h> #include <string.h> #include <ctype.h> void pattern_map(char *answer, char *buffer, size_t len) { size_t idx, j; int done = 0; static const char *p = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”; static const size_t maxidx = strlen(p); int curr = 1; answer[0] = ‘1’; buffer[0] = tolower(buffer[0]); for(idx = 1; idx < len; idx++) { buffer[idx] = tolower(buffer[idx]); done = 0; for(j = 0; !done && j < idx; j++) { if(buffer[idx] == buffer[j]) { answer[idx] = answer[j]; done = 1; } } if(!done) { if(curr < maxidx) { answer[idx] = p[++curr]; } else { answer[idx] = ‘?’; } } } answer[idx] = ‘\0’; } int main(void) { char buffer[8192] = {0}; char answer[8192] = {0}; size_t len = 0; while(fgets(buffer, sizeof buffer, stdin)) { len = strlen(buffer) - 1; if(buffer[len] != ‘\n’) { fprintf(stderr, “Line too long: %s\n”, buffer); } else { pattern_map(answer, buffer, len); printf(“%s %s”, answer, buffer); } } printf(“\n”); return 0; }
As a result of these trivial cracks, substitution ciphers are not at all secure - frequency analysis of any ciphertext of 40 characters or more is unlikely to fail to reveal the plaintext.
A former colleague, in a former lifetime, was very keen on substitution ciphers. For some reason he thought that if he ran his plaintext through successive substitution tables, some of which were numbers rather than letters, and some of which were invented symbols, it would somehow be really secure. He presented his ‘uncrackable’ ciphertext to me proudly and it took me about 5 minutes to crack. He asked me how I’d managed to deduce the existence of the intermediate tables. My answer was “What intermediate tables?” I’d had no idea he’d gone to all that trouble! The existence of the intermediate tables was irrelevant to the crack, because there was still a one-to-one mapping between the plaintext and the ciphertext.
Homophonic substitution is a variation on the same theme. In homophonic substitution, each character of plaintext can be replaced by one of a small selection of ciphertext characters. So you could, for example, map A to 54, 90, 102, or 155; B to 2, 37, 39 or 158; C to 17, 38, 70 or 99; etc. This is a lot harder to crack, but it’s still not impossible. The same statistical irregularities of the plaintext will still show up and, thus, decryption is possible.
Maybe we can do better by encrypting groups of letters instead of individual letters. This certainly gives us more scope. If we take groups of three characters at a time, that gives us approximately 17000 (I’ll let you cube 26 for yourselves!) possible groups of plaintext triplets. If we mapped each to a unique ciphertext triplet, that would be a lot harder to crack, yes? For example, you can encipher AAA as FOO, AAB as BAR, AAC as QUX, AAD as FRE, etc.
Well, okay, it’s better. It’s still not very good, though. For sufficiently large samples of ciphertext it is still possible to get a handle on statistical anomalies in the data. For example, what’s the betting that THE is the most common triplet in the English language? (Not counting the capitalised word, the triplet THE still occurs three times in that last sentence alone.) So all you’d have to do is find the most common triplet and you have a hook into the cipher. I’m not saying that THE is necessarily the most common, although it is a good guess. Writing a program to determine a triplet frequency table is left as an exercise for the discerning reader.
Okay, how about using more than one substitution table? Maybe if we had, say, six tables, and we used the first table to encrypt the first, seventh, thirteenth letters of the plaintext, and the second to encrypt the second, eighth, and fourteenth, etc?
Not a bad idea, it seems, but all this really means is that it takes more ciphertext before the tables can be deduced (in this case, only six times as much ciphertext). Computer programs exist which can do this kind of cryptanalysis extraordinarily quickly and accurately.
But "WAIT!," I hear you cry. Any one of these methods could have been used. The cryptanalyst has no way of knowing which encryption method I’ve used! So how can one possibly decide which cryptanalytical technique to use on my ciphertext?
Three answers exist for this. Firstly, if your security relies on the secrecy of your algorithm, that’s not security, it’s obscurity. Your algorithm must be known to at least two people - the sender and the receiver of the information. If you have a group of people who all need to share secure information, you’re going to have to change your algorithm every time somebody leaves the group, because they know the secret and now they are a 'loose cannon', so to speak.
Secondly, even if it’s just the two of you, and even if you have complete confidence that your secret algorithm won’t be revealed (unwittingly, deliberately, or under coercion) by the other person, that still doesn’t help. Cryptanalysts know a huge number of algorithms and have a large selection of cryptanalysis programs at their disposal.
Thirdly, if you are using a “secret” computer program to encrypt and decrypt your secrets, remember that cryptanalysts are bright bunnies. If they can get hold of the binary of your program (to how many people have you distributed this binary, hmmm?), they can disassemble it and study your algorithm. In fact, it’s a rather perverse truth of cryptography that the truly secure algorithms are those which have been published by their authors and subjected to all kinds of attacks by some of the best cryptanalysts in the world. Anything which can survive that onslaught, intact, mustbe good.
So, if you used any of the techniques I’ve described so far and a professional cryptanalyst got hold of your ciphertext, I wouldn’t give your secret ten minutes before it was cracked. | http://www.informit.com/articles/article.aspx?p=20749 | CC-MAIN-2016-22 | refinedweb | 1,977 | 62.88 |
I'm going to make 3-4 choices in Rails.
StackOverflow "Create a quiz app for Ruby on Rails. Passing id"
Implementing with reference to.
For reference above,
def mark
quizzes = Quiz.find (params [: tests])
@answers = []
quizzes.each do | q |
answers<<{quiz: q, right: q.right_answer? (params ["quiz # {q.id}"])}
end
end
.
Does quizzes store all the selected quiz data in an array?
Also, what are the errors?
Couldn't find Quiz without an ID
I did various things to reflect the id of the question that would have been selected in [: tests]
I can't ...
Please provide more detailed information here.
- Answer # 1
Related articles
- ruby - i can't "rails db: create rails_env = production" on aws
- ruby on rails - when calling the create action, the name attribute changes depending on whether it is indexhtmlerb or newhtmlerb
- ruby - i want to transition from create to show with rails
- ruby on rails 5 - i don't understand why i create a virtual attribute
- ruby - rails even if i create a new model (user), it is not displayed
- ruby on rails - route and controller code when you want to create many rails pages
- ruby on rails - i want to create a screen with a calendar display for 2 weeks like the attachment
- ruby on rails 5 - i want to create data for a nested child model, but i can not pass the value well with strong_paramater [rails
- ruby - i can't save in create mezzotte of rails
- ruby - i can't create a custom account with rails stripe
- ruby - i don't know how to create a group function with rails and register a new participant there
- ruby on rails 5 - after the rails5 book_comment create action fails, render cannot be returned properly
- ruby - unable to create rails model (environment: cloud9)
- ruby on rails 5 - cannot get params value in controller
- ruby on rails - i can't create a database with rails db: create
- ruby - rails tutorial chapter 13 can't deploy to heroku with argumenterror
- ruby on rails - i got an error when i made a mistake in the controller name
- ruby on rails - i want to be able to get the user_id
- ruby on rails 6 - i want to resolve undefined method `[]' for nil:nilclass
- ruby on rails 6 - aws cloud9 blocks host on rails6
What about this? It may be better to put the URL of the site you are referring to.
That's right,
@quizzes = Quiz.all.sample (5)will contain the ID of the quiz extracted.
When you look at the source
controller:
quizzes = Quiz.find (params [: tests])
view:
<% = hidden_field_tag "quiz []" ;, quiz.id%>
params:
# params =>{: quizzes =>[1,5,8,14,20],"quiz1"=>'quiz1 form input&apos ;,"quiz5"=>&apos ;quiz5 form input&apos ;,"quiz8"=>'quiz8 form input&apos ;,"quiz14"=>'quiz14 form input&apos ;,"quiz20"=>'quiz20 Form input'}
and the parameter names used are different, so I can't say anything.
I think you should use the parameter name that contains the ID of the quiz on the console screen.
If you write the view in the same way as the reference page, you can get it with
params [: quiz]. | https://www.tutorialfor.com/questions-100833.htm | CC-MAIN-2020-45 | refinedweb | 521 | 65.05 |
Scott Mitchell
March 2007
Summary: Extend the built-in inserting, updating, and deleting capabilities of ASP.NET data Web controls, and customize the editing interface to update only a subset of the product fields, with this tutorial from Scott Mitchell. (29 printed pages)
Download the code for this sample.
Introduction Step 1: Updating a Product's ProductName and UnitPrice Fields Improving the UnitPrice Formatting Step 2: Prohibiting NULL UnitPrices Step 3: Providing an Interface to Add New Products Step 4: Assigning Values to the CategoryID and SupplierID Parameters Conclusion:
During this sequence of steps, a number of events fire, enabling us to create event handlers to add custom logic, where needed. For example, prior to step 1, the RowUpdating event of the GridView fires. We can, at this point, cancel the update request if there is some validation error. When the Update() method is invoked, the Updating event of the ObjectDataSource fires, providing an opportunity to add or customize the values of any of the UpdateParameters. After the method of the underlying object of the ObjectDataSource has completed executing, the Updated event of the ObjectDataSource is raised. An event handler for the Updated event can inspect the details about the update operation, such as how many rows were affected and whether or not an exception occurred. Finally, after step 2, the RowUpdated event of the GridView fires; an event handler for this event can examine additional information about the update operation that was-level and post-level events for both the data Web control and the ObjectDataSource.
Figure 1. A series of pre-level and post-level events fire, when updating data in a GridView. (Click on the picture for a larger image.)
In this tutorial, we'll examine using these events to extend the built-in inserting, updating, and deleting capabilities of the ASP.NET data Web controls. We'll also see how to customize the editing interface to update only a subset of the product NULL value into the UpdateProduct method of the Business-Logic Layer (BLL), is that the ObjectDataSource was configured to call the UpdateProduct method of the ProductsBLL class, which expected an input parameter for each of the product fields. Therefore, the UpdateParameters collection of the ObjectDataSource contained a parameter for each of the method's input parameters.
If we want to provide a data Web control that allows the end user to update only a subset of fields, then we must either programmatically set the missing UpdateParameters values in the Updating event handler of the ObjectDataSource or create and call a BLL method that expects only a subset of the fields. Let's explore the latter approach.
Specifically, let's create a page that displays just the ProductName and UnitPrice fields in an editable GridView. The editing interface of this GridView will allow the user to update only the two displayed fields, ProductName and UnitPrice. Because this editing interface only provides a subset of a product's fields, we must create either an ObjectDataSource that uses the UpdateProduct method of the existing BLL and has the missing product field values set programmatically in its Updating event handler or bool UpdateProduct(string productName, decimal? unitPrice,;
// Update the product record
int rowsAffected = Adapter.Update(product);
// Return true if precisely one row was updated, otherwise false
return rowsAffected == 1;
}
As with the original UpdateProduct method, this overload starts by checking to see if there is a product in the database that has the specified ProductID. If not, it returns false, indicating that the request to update the product information failed. Otherwise, it updates the ProductName and UnitPrice fields of the existing product record accordingly and commits the update by calling the Update() method of the TableAdapter, Update() method of the ObjectDataSource to the new UpdateProduct method overload of the ProductsBLL class.
Figure 2. Map the ObjectDataSource's Update() method to the new UpdateProduct overload. (Click on the picture for a larger image.)
Because our example will initially just need the ability to edit data, but not to insert or delete records, take a moment to indicate explicitly that the Insert() and Delete() methods of the ObjectDataSource shouldn't be mapped to any of the methods of the ProductsBLL class, by going to the INSERT and DELETE tabs and choosing (None) from the drop-down list.
Figure 3. Choose (None) from the drop-down list for the INSERT and DELETE tabs. (Click on the picture for a larger image.)
After completing this wizard, check the Enable Editing check box from the GridView's smart tag.
With the Create Data Source wizard completing and binding to the GridView, Microsoft Visual Studio has created the declarative syntax for both controls. Go to the Source view to inspect the declarative markup of the ObjectDataSource, which is shown here:
>
Because there are no mappings for the Insert() and Delete() methods of the ObjectDataSource, there are no InsertParameters or DeleteParameters sections. Furthermore, because the Update() method is mapped to the UpdateProduct method overload that only accepts three input parameters, the UpdateParameters section has just three Parameter instances.
Note that the OldValuesParameterFormatString property of the ObjectDataSource is set to original_{0}. This property is set automatically by Visual Studio when using the Configure Data Source wizard. However, because our BLL methods don't expect the original ProductID value to be passed in, remove this property assignment altogether from the declarative syntax of the ObjectDataSource.
Note If you just clear out the OldValuesParameterFormatString property value from the Properties window in the Design view, the property will still exist in the declarative syntax, but it will be set to an empty string. Either remove the property altogether from the declarative syntax or, from the Properties window, set the value to the default, which is on the picture for a larger image.)
When the end user edits a product and clicks its Update button, the GridView enumerates those fields that were not read-only. It then sets the value of the corresponding parameter in the UpdateParameters collection of the ObjectDataSource to the value entered by the user. If there is no declarative markup of the ObjectDataSource specifies only three input parameters (see Figure 5). Similarly, if there is some combination of non-read-only product fields in the GridView that doesn't correspond to the input parameters for an UpdateProduct overload, an exception will be raised when attempting to update.
Figure 5. The GridView will add parameters to the ObjectDataSource's UpdateParameters collection.
To ensure that the ObjectDataSource invokes the UpdateProduct overload that takes in just the product's name, price, and ID, we must just remove all GridView fields except the ProductName and UnitPrice BoundFields, after which the declarative markup of the GridView will look like the following:
>
Although the UpdateProduct overload expects three input parameters, we have only of just the product's name and price. (Click on the picture for a larger image.)
Note As discussed in the previous tutorial, it is vitally important that the View state of the GridView be enabled (the default behavior). If you set the EnableViewState property of the GridView to false, you run the risk of having concurrent users unintentionally delete or edit records. (See WARNING: Concurrency Issue with ASP.NET 2.0 GridViews/DetailsView/FormViews that Support Editing and/or Deleting and Whose View State is Disabled, for more information.)
While the GridView example shown in Figure 6 works, the UnitPrice field is not formatted at all, which results in a price display that lacks any currency symbols and has four decimal places. To apply a currency formatting for the non-editable rows, just set the DataFormatString property of the UnitPrice BoundField to {0:c} and its HtmlEncode property to false.
Figure 7. Set the UnitPrice's DataFormatString and HtmlEncode properties accordingly. (Click on the picture for a larger image.)
With this change, the non-editable rows format the price as a currency; the edited row, however, still displays the value without the currency symbol and with four decimal places.
Figure 8. The non-editable rows are now formatted as currency values. (Click on the picture for a larger image.)
The formatting instructions specified in the DataFormatString property can be applied to the editing interface by setting the ApplyFormatInEditMode property of the BoundField to true (the default is false). Take a moment to set this property to true.
Figure 9. Set the UnitPrice BoundField's ApplyFormatInEditMode property to true. (Click on the picture for a larger image.)
With this change, the value of the UnitPrice that is displayed in the edited row also is formatted as a currency.
Figure 10. The edited row's UnitPrice value is now formatted as a currency. (Click on the picture for a larger image.)
However, updating a product with the currency symbol in the text box—such as $19.00—throws a FormatException. When the GridView attempts to assign the user-supplied values to the UpdateParameters collection of the ObjectDataSource, it is unable to convert the UnitPrice string "$19.00" into the decimal that is required by the parameter (see Figure 11). To remedy this, we can create an event handler for the RowUpdating event of the GridView and have it parse the user-supplied UnitPrice as a currency-formatted decimal.
The RowUpdating event of the GridView accepts as its second parameter an object of type GridViewUpdateEventArgs, which includes a NewValues dictionary as one of its properties that holds the user-supplied values that are ready to be assigned to the UpdateParameters collection of the ObjectDataSource. We can overwrite the existing UnitPrice value in the NewValues collection with a decimal value that is parsed by using the currency format with the following lines of code in the RowUpdating event handler:
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
if (e.NewValues["UnitPrice"] != null)
e.NewValues["UnitPrice"] =
decimal.Parse(e.NewValues["UnitPrice"].ToString(),
System.Globalization.NumberStyles.Currency);
}
If the user has supplied a UnitPrice value (such as "$19.00"), this value is overwritten with the decimal value that is computed by Decimal.Parse, parsing the value as a currency. This will correctly parse the decimal in the event of any currency symbols, commas, decimal points, and so on, and uses the NumberStyles enumeration in the System.Globalization namespace.
Figure 11 shows both the problem that is caused by currency symbols in the user-supplied UnitPrice and how the RowUpdating event handler of the GridView can be utilized to parse such input correctly.
Figure 11. The edited row's UnitPrice value is now formatted as a currency. (Click on the picture for a larger image.)
While the database is configured to allow NULL values in the UnitPrice column of the Products table, we might want to prevent users who visit this particular page from specifying a NULL UnitPrice value. That is, if a user fails to enter a UnitPrice value when editing a product row, instead of saving the results to the database, we want to display a message that informs the user that, through this page, any edited products must have a price specified.
The GridViewUpdateEventArgs object that is passed into the RowUpdating event handler of the GridView contains a Cancel property that, if set to true, terminates the updating process. Let's extend the RowUpdating event handler to set e.Cancel to true and display a message that explains why, if the UnitPrice value in the NewValues collection is null.
Start by adding a Label Web control to the page named MustProvideUnitPriceMessage. This Label control will be displayed if the user fails to specify a UnitPrice value when updating a product. Set the Text property of the Label to You must provide a price for the product. I've also created a new CSS class in Styles.css that is named Warning and has the following definition:
.Warning
{
color: Red;
font-style: italic;
font-weight: bold;
font-size: x-large;
}
Finally, set the CssClass property of the Label to Warning. At this point, the Designer should show the warning message in a red, bold, italic, extra-large font size above the GridView, as shown in Figure 12.
Figure 12. A label has been added above the GridView. (Click on the picture for a larger image.)
By default, this Label should be hidden, so set its Visible property to false in the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
MustProvideUnitPriceMessage.Visible = false;
}
If the user attempts to update a product without specifying the UnitPrice, we want to cancel the update and display the warning label. Augment the RowUpdating event handler of the GridView, as follows:
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
if (e.NewValues["UnitPrice"] != null)
{
e.NewValues["UnitPrice"] =
decimal.Parse(e.NewValues["UnitPrice"].ToString(),
System.Globalization.NumberStyles.Currency);
}
else
{
// Show the Label
MustProvideUnitPriceMessage.Visible = true;
// Cancel the update
e.Cancel = true;
}
}
If a user attempts to save a product without specifying a price, the update is cancelled and a helpful message is displayed. While the database (and business logic) allow for NULL UnitPrices, this particular ASP.NET page does not.
Figure 13. A user cannot leave UnitPrice blank. (Click on the picture for a larger image.)
So far, we have seen how to use the RowUpdating event of the GridView to programmatically alter the parameter values assigned to the UpdateParameters collection of the ObjectDataSource, as well as how to cancel the updating process altogether. These concepts carry over to the DetailsView and FormView controls and apply also to inserting and deleting.
These tasks can also be done at the ObjectDataSource level through event handlers for its Inserting, Updating, and Deleting events. These events fire before the associated method of the underlying object is invoked, and they provide a last-chance opportunity to modify the input parameters collection or cancel the operation outright. The event handlers for these three events are passed an object of type ObjectDataSourceMethodEventArgs that has two properties of interest:
To illustrate working with the parameter values at the ObjectDataSource level, let's include a DetailsView in our page that allows the users to add a new product. This DetailsView will be used to provide an interface for adding a new product to the database quickly. To keep a consistent user interface when adding a new product, let's allow the user to enter values for the ProductName and UnitPrice fields only. By default, those values that aren't supplied in the inserting interface of the DetailsView will be set to a NULL database value. However, we can use the Inserting event of the ObjectDataSource to inject different default values, as we'll see shortly.
Drag a DetailsView from the Toolbox onto the Designer above the GridView, remove its Height and Width properties, and bind it to the ObjectDataSource that is already present on the page. This will add a BoundField or CheckBoxField for each of the product's fields. Because we want to use this DetailsView to add new products, we must check the Enable Inserting option from the smart tag. However, there's no such option, because the Insert() method of the ObjectDataSource is not mapped to a method in the ProductsBLL class; recall that we set this mapping to (None) when configuring the data source (see Figure 3).
To configure the ObjectDataSource, select the Configure Data Source link from its smart tag, which launches the wizard. The first screen allows you to change the underlying object to which the ObjectDataSource is bound; leave it set to ProductsBLL. The next screen lists the mappings from the methods of the ObjectDataSource to those of the underlying object. Although we explicitly indicated that the Insert() and Delete() methods should not be mapped to any methods, if you go to the INSERT and DELETE tabs, you'll see that a mapping is there. This is because the AddProduct and DeleteProduct methods of the ProductsBLL use the DataObjectMethodAttribute attribute to indicate that they are the default methods for Insert() and Delete(), respectively. Hence, the ObjectDataSource wizard selects these each time that you run the wizard, unless there's some other value that is specified explicitly.
Leave the Insert() method pointing to the AddProduct method, but again set the drop-down list of the DELETE tab to (None).
Figure 14. Set the INSERT tab's drop-down list to the AddProduct method. (Click on the picture for a larger image.)
Figure 15. Set the DELETE tab's drop-down list to (None). (Click on the picture for a larger image.)
After you have made these changes, the declarative syntax of the ObjectDataSource will be expanded to include an InsertParameters collection, as shown here:
either setting it to the default value ({0}) or removing it altogether from the declarative syntax.
With the ObjectDataSource providing inserting capabilities, the DetailsView's smart tag will now include the Enable Inserting check box; return to the Designer and check this option. Next, pare down the DetailsView, so that it has only two BoundFields—ProductName and UnitPrice—and the CommandField. At this point, the declarative syntax of the DetailsView should look like the following:
add a new product to the database quickly.
Figure 16. The DetailsView is currently rendered in read-only mode. (Click on the picture for a larger image.)
In order to show the DetailsView in its inserting mode, we must adding a new product quickly. (Click on the picture for a larger image.)
When the user enters a product name and price—such as "Acme Water" and "1.99", as in Figure 17—and clicks Insert, a postback ensues and the inserting workflow commences, which culminates that are lacking from the DetailsView interface—CategoryID, SupplierID, QuantityPerUnit, and so on—are assigned NULL database values. You can see this by performing the following steps:
This procedure will list all of the records in the Products table. As Figure 19 shows, all of the columns of our new product—other than ProductID, ProductName, and UnitPrice—have NULL values.
Figure 19. The product fields that are not provided in the DetailsView are assigned NULL values. (Click on the picture for a larger image.)
We might InputParameters collection of the DetailsView. This assignment can be done in either the event handler for the ItemInserting event of the DetailsView or the Inserting event of the ObjectDataSource. Because we've already looked at using the pre-level and post-level events at the data Web control level, let's explore this time using the ObjectDataSource's events.
For this tutorial, let's imagine that for our application, when adding a new product through this interface, it should be assigned a CategoryID and SupplierID value of 1. As mentioned earlier, the ObjectDataSource has a pair of pre-level and post-level events that fire during the data-modification process. When its Insert() method is invoked, the ObjectDataSource first raises its Inserting event, then calls the method to which its Insert() method has been mapped, and finally raises the Inserted event. The Inserting event handler affords us one last opportunity to tweak the input parameters or cancel the operation outright.
Note In a real-world application, you would likely want either to let users specify the category and supplier or to pick this value for them, based on some criteria or business logic (instead of blindly selecting an ID of 1). Regardless, the example illustrates how to programmatically set the value of an input parameter from the pre-level event of the ObjectDataSource.
Take a moment to create an event handler for the Inserting event of the ObjectDataSource. Notice that the event handler's second input parameter is an object of type ObjectDataSourceMethodEventArgs, which has a property to access the parameters collection (InputParameters) and a property to cancel the operation (Cancel).
protected void ObjectDataSource1_Inserting
(object sender, ObjectDataSourceMethodEventArgs e)
{
}
At this point, the InputParameters property contains the InsertParameters collection of the ObjectDataSource with the values assigned from the DetailsView. To change the value of one of these parameters, just use e.InputParameters["paramName"] = value. Therefore, to set the CategoryID and SupplierID to values of 1, adjust the Inserting event handler to look like the following:
protected void ObjectDataSource1_Inserting
(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters["CategoryID"] = 1;
e.InputParameters["SupplierID"] = 1;
}
This time, when adding a new product—such as Acme Soda—the CategoryID and SupplierID columns of the new product are set to 1 (see Figure 20).
Figure 20. New products now have their CategoryID and SupplierID values set to 1. (Click on the picture for a larger image.)
During the editing, inserting, and deleting processes, both the data Web control and the ObjectDataSource proceed through a number of pre-level and post-level events. In this tutorial, we examined the pre-level events and saw how to use these to customize the input parameters or cancel the data-modification operation altogether—both from the data Web control and the ObjectDataSource's events. In the next tutorial, we'll look at how to create and use event handlers for the post-level events..
This tutorial series was reviewed by many helpful reviewers. Lead reviewers for this tutorial include Jackie Goor and Liz Shulok. Interested in reviewing my upcoming MSDN articles? If so, drop me a line at mitchell@4GuysFromRolla.com. | http://msdn.microsoft.com/en-us/architecture/bb332383.aspx | crawl-002 | refinedweb | 3,529 | 50.67 |
[UPDATED 8/5]
Visual Studio 2015, Visual Studio 2013 Update 5, and .NET 4.6 were released on 7/20/2015. Check out this post announcing VS 2015 and VS 2013 Update 5 and this one announcing .NET framework 4.6.
[Original Post]
The Microsoft BUILD conference is typically a time when we release a lot of developer tools. This year we may have outdone ourselves. I’m going to talk a little about what we released today, but you’ll probably want to look at the announcements on Scott Guthrie’s Blog and Terry Myerson’s post on the Windows blog as well as Soma’s blog and Brian Harry’s blog. If you’d rather watch than read, head over to Channel 9 to watch the recordings.
The very short version is that we released Visual Studio 2015 Release Candidate (RC), .NET Framework 4.6, Team Foundation Server 2015 RC, and Visual Studio 2013 Update 5 RC and also a preview of a new tool that runs on MacOS, Linux, and Windows called Visual Studio Code. You may want to kick off those downloads while you read the rest of this post.
If you’re interested in a bit more detail, but not yet up for reading the entire post, here’s the dime novel version:, watch the demos from BUILD, learn more about the team, or read this blog post and follow Visual Studio Code on Twitter.
Download Visual Studio Enterprise 2015 RC (English). You can now download the VS Enterprise 2015 RC in English (or go here for other languages and editions). We’re in the end game for VS 2015 and would love your feedback. In addition to the many new features in this RC itself, we also released a cohort of related technologies: Tools for Apache Cordova (uninstall previous versions first, please), Entity Framework 7 Preview, ASP.NET 5 Preview, tools for Docker preview, and updates to the emulator for Android. You can get the entire list of what’s new in the Visual Studio 2015 RC Release Notes.
Download Team Foundation Server 2015 RC. Download the TFS 2015 RC and give us feedback on the new capabilities such as updates to the Kanban board, policies to enables gated builds, and better code review. As always, the Team Foundation Server 2015 RC Release Notes have the full list of what’s new.
Download Visual Studio 2013 Update 5 RC. This update includes everything from the previous CTPs plus enhancements for TFS and Visual Studio Online including the ability to easily run load tests by using TFS. Once again, the Visual Studio 2013 Update 5 RC Release Notes have the full list of changes.
You can download the releases from the links above or from MSDN subscriber downloads. You can also use an Azure VM image to try out any or all of these releases.
Visual Studio 2015 RC
There’s a lot in the RC of Visual Studio, from improvements to the editing experience (e.g. light bulbs, CodeLens, and code maps) to improvements to the sign-in experience. Let’s start with something many of you have asked for – an improved VS SDK for VS 2015 – then talk about a few other highlights of the RC.
Creating Extensions for VS 2015. With this release, the VS 2015 SDK is available for download. We’ve improved several aspects of building extensions for VS 2015. For example, we created NuGet packages for Visual Studio SDK assemblies, so you can now reference these assemblies using NuGet Package Manager and share your extension code. We’ve also eliminated the need to use a project creation wizard or template to add a feature to your extension: simply by use an item template. More information is available on the VS Extensibility Dev Center, and check out the extensibility samples and the SDK documentation to learn more about building extensions.
Debugger Improvements. Visual Studio 2015 addresses many of your requests, such as lambda debugging, Edit and Continue (EnC) improvements, child-process debugging, as well revamp core experiences such as powerful breakpoint configuration and introduces a new Exceptions Settings toolwindow. We also pushed the state of the art by integrating performance tooling into the debugger with PerfTips and the all new Diagnostic Tools window which includes the Memory Usage tool and the redesigned IntelliTrace for historical debugging.
.NET Framework 4.6: cross-platform support and new JIT. Last fall we said we’d do it and today we did: .NET Core is now available on Linux and MacOS. Along with that, we’re starting to make changes in the framework to enable more cross-platform support (e.g. we’ve added new methods to support converting DateTime to or from Unix time). But there’s quite a bit more. For example, we added a new version of the 64-bit JIT Compiler, which improves performance over the existing 64bit JIT compiler. To get a quick view of all the improvements take a look at .NET Framework 4.6 section of the release notes and read the roll-up post on .NET blog.
Sign in with work and school accounts in addition to MSA. In Visual Studio 2015, we have been improving the sign in experience. A notable update in this release: in addition to using Microsoft Accounts to sign into the IDE, you can now sign in with a work or school account. Visual Studio will manage your credentials and present them across different features and services inside VS, such as Azure and VS Online services, without extra prompts for credentials.
Improved Notifications user experience. In Visual Studio 2013, we introduced the Notifications Hub to surface notifications to developers with information about their environment. Most notably, we used this area to tell you when an update was available to VS or a component in VS. In VS 2015 RC, we’ve added a new notification: VS will now give you an option to Learn more about a recent Visual Studio crash. There are now quite a few notifications you may get through this UI, so we’ve simplified the UI to only show one-line titles and descriptions, to categorize notifications, and enable you to ‘always ignore’ notifications that are not important to you.
Add Connected Services. We’ve redesigned the Add Connected Services (under the References node in Solution Explorer) experience to make it easier to use and to make it extensible with the Connected Services SDK. From this dialog you can add:
- Azure Application Insights to detect issues, diagnose crashes and track usage in your apps
- Azure Storage to enable reliable, economical cloud storage for all types of data
- Azure Mobile Services to store app data in the cloud and use.NET or Node.js Web API backend
- Azure Active Directory single sign-on can be set up for ASP.NET Web projects
- Salesforce to configure access to Salesforce data via the Salesforce REST APIs
- Office 365 to access calendars, contacts, mail, files, sites and users & groups.
- To explore the O365 APIs, you can use the API Sandbox in your browser.
Other services can be discovered in the Extensions and Updates gallery using the Find more services link.
Editor Improvements. We’ve continued to hone Light bulbs and the Error List. Light bulbs help you identify and fix common coding issues, in many cases “live” as you type your code, and take quick code actions (like refactoring, implementing interfaces and more) from right inside the editor. Error List is your one stop shop for navigating and correcting code-related issues in your solution, whatever their source, from compile and build to code analysis issues.
CodeLens. The key thing we’ve done is to make CodeLens available in both VS 2015 Professional and Enterprise as well as in Visual Studio Online. In addition, we’ve added file-level indicators for all file types including C++, JavaScript, SQL, XAML, HTML, and CSS. You can learn more about this feature in the blog post on CodeLens availability for C++ JavaScript and SQL files.
Code Map. We’ve improved how code maps display and interpret test assets within solutions and how code maps carry that the context of your code through into the elements on the map. Learn more in this detailed post on latest changes in Code Map.
Visual Studio Tools for Apache Cordova. Using Tools for Apache Cordova you can build, debug, and test cross-platform applications that target Android, iOS, Windows, and Windows Phone, all from a single Visual Studio Project. In this release we have broadened the number of devices you can debug to, to now include Android 4.4, Android 4.3 and earlier with jsHybugger, iOS 6, 7, and 8, and Windows Store 8.1. Support for Apache Cordova 4.0.0 is also now available. Learn more about the Visual Studio Tools for Apache Cordova.
Visual Studio Tools for Universal Windows App Development. We have integrated the Visual Studio tools for Universal Windows app development into Visual Studio setup. These tools enable you to create, upgrade, build, deploy, and debug Windows apps that run across all Windows devices, from Windows Phone to Xbox and Windows Store. In addition, you can also use these tools to build Windows Desktop Applications that leverage Windows 10 APIs. (Note that in this release, Windows 10 is not supported as a targeted platform for production apps.) You can install the tools for Universal Windows apps during Visual Studio setup by selecting Custom, and then selecting “Universal Windows App Development Tools.” For more information on Windows app development, see the Guide to Universal Windows apps and the Windows Insider portal
C++ Improvements. One of the requests we continually receive from C++ developers continues to be for more C++ standards support. In this release, we continue to deliver C++11, C++14 and even C++17 features to make it easier for you to write better, cleaner, and compatible code. Some of the features in VS 2015 RC include resumable functions (resume/await), generic (polymorphic) lambda expressions, decltype(auto), thread-safe “magic” statics and return type deduction. Recognizing that customers want to access application functionality on different mobile platforms, we made a major investment enabling multi-device development with C++. You can use Visual Studio 2015 to generate dynamic/static libraries, native-library applications, and Xamarin native applications targeting the Android platform. We also now support building iOS applications using Visual Studio 2015. So you can now write C++ code targeting the iOS platform and also be able to take advantage of our advanced code authoring features such as code sharing, cross-platform IntelliSense, refactoring, peek definition and more. The iOS support is still work in progress, keep an eye out for more on this soon. This is being released as Preview today so we’d love to hear your feedback.
Check out Ankit Asthana’s BUILD talk “Building Multi-Device Applications in C++ with Visual Studio 2015” for more information including a few cool demos. For all things C/C++ related, visit the Visual C++ team blog. You can also find a list of all feature updates in this release in the Visual C++ section of the release notes.
Improved support for high-DPI displays. We’re continuing to ensure that Visual Studio looks beautiful on high-density, high-DPI displays. As an example, we added a central image service so Visual Studio can use variable resolution icons, which means those in-between DPI scaling factors of 150 and 250% now look just as good as 100 and 200% and that images in VS are themed properly for high-contrast and across the in-box themes (Blue, Light, Dark).
Team Foundation Server 2015 RC
With TFS 2015 CTP released earlier this year, we expanded the basic license to include web-based test execution, agile portfolio management, work item chart authoring, and team rooms. This means that all teams of five or fewer members with a “Basic” license now have access to these features using Team Web Access for free, while larger teams can access this functionality at a much lower price point. This release includes all changes from the CTP release including expansion of the “Basic” license of TFS and also has many additional improvements.
Policies – Gated Build and Code Review. If you are working with a Git project you can now set branch policies to require a successful build before any code can be submitted into a branch. You can also set branch policies on Git projects to require code reviews for any code submitted into a branch. You can also configure the policies to require a minimum number of code reviewers, as well as to require specific reviewers for particular paths and/or file types.
Quick Code Editing. If you are looking to make quick code edits we have now made it easy to edit a file in version control directly from your web browser and then commit those changes straight back to the service. With every save, we create a new commit/changeset with your changes. You can use the diff view to see exactly what changes you’re making before committing the changes. If the file is a Markdown or HTML file, you can also preview your changes before you save them.
Kanban Board. A new feature we’ve added to our Kanban board is called Kanban Split Columns. To track your work more effectively and help move work through the board, each column on your board is split into two sub columns—Doing and Done, making it much easier to track progress. As work moves through your board, it’s critical that you and your team are on the same page about what “done” means. In this release we provide a way for you to specify a definition of done for each column on your board.
You’ll also notice that in RC, all the cards have a slightly updated look—cards are now a bit wider, and have a solid white background (instead of a colored background). These changes lay the groundwork for more customization options on the cards, including adornments, additional fields, and tags. While these customizations options aren’t ready for RC, they’re coming soon, so stay tuned. Learn more about working with Kanban boards in TFS.
To read about all these changes in further detail, check out the Team Foundation Server 2015 RC Release Notes and Brian Harry’s blog.
Other Visual Studio Tools Available Today
At the start of this post, I mentioned that there are many other tools available alongside this release. Let’s start by highlighting some of Visual Studio 2015’s device support for Android and Windows, and work through a few others.
Visual Studio Emulator for Android. Our fast, free, Hyper-V compatible emulator for Android gets even better in Visual Studio 2015 RC with an update that adds Device Profiles and WiFi simulation. We’ve curated a set of profiles that represent the most popular hardware in the market, including devices from Samsung, Motorola, Sony, and LG, so that you can debug and test your Android app across a wide range of screen configurations, Android versions, and other properties. Manage your device profiles using the Emulator Manager, accessible from Visual Studio under the Tools > Visual Studio Emulator for Android menu option.
Visual Studio 2015 Tools for Docker Preview. Today we are also making Visual Studio 2015 RC Tools for Docker – Preview available to you. This enables you to provision Azure virtual machines containing the docker engine, and we provide both UI tools and scripts to package and deploy your Web application or console application to Docker hosts. This is a helpful companion tool to work with .NET on Linux.
Microsoft Azure SDK for .NET 2.6. This release provides new and enhanced tooling for Azure development with Visual Studio 2015 RC and Visual Studio 2013 Update 5 RC, including Azure Resource Manager Tools, HDInsight Tools, and various improvements to diagnostics for Cloud Services. Read this detailed blog post to learn more about what’s new in this release of Azure SDK 2.6.
Entity Framework 7 Beta 4. The latest version of Entity Framework enables new platforms and new data stores. Windows Phone, Windows Store, ASP.NET 5, and traditional desktop application can now use Entity Framework. EF7 also supports relational databases as well as non-relational data stores such as Azure Table Storage and Redis. This release includes an early preview of the EF7 runtime that is installed in new ASP.NET 5 projects. For more information on EF7, see what is EF7 all about and read this blog post for details.
ASP.NET 5 Beta 4. ASP.NET 5 Preview updates the runtime with a lightweight request pipeline and continues cross-platform support by running on Windows, Mac, and Linux. You can view the entire list of changes in the ASP.NET section of the release notes. Additionally you can read about these features in detail on the blog post on ASP.NET blog.
What does “release candidate” mean?
As a final note, we should explain what RC means to us. If you’re familiar with the community technology previews (CTPs) we’ve shipped, you know that our intent with those is to get you access to the work we’re doing sooner rather than later so you can give feedback. CTPs can be of pretty variable quality. When we say VS is an RC, we’re trying to indicate that the quality level is higher and the feature set is complete or nearly complete and we want your final feedback before calling the release done. As part of being an RC, some of our releases get the “go live” moniker, indicating that, despite the fact that the software isn’t done yet, we are licensing it for developing and deploying production applications. To decide whether using Visual Studio 2015 RC in a go live scenario is right for you, start by reading the license terms for RC, which includes the go live licensing terms. Here are some additional items to note about the RC:
Side by Side. Visual Studio 2015 RC works seamlessly side-by-side with Visual Studio 2013.
Install over Preview. You can install VS 2015 RC on top of VS 2015 Preview without the need to uninstall Preview. Since there is no upgrade path from TFS 2015 Preview, you will need to do a fresh install of TFS or upgrade from a previous TFS RTM release (such as TFS 2013 Update 4). You will be able to upgrade from TFS 2015 RC to TFS 2015 RTM.
Windows 10 with VS 2015 RC “go-live.” Applications built for Windows 10 cannot be distributed or uploaded to the Windows Store. Instead, you will need to rebuild applications built for Windows 10 using the final version of Visual Studio 2015 before submitting to the Windows Store.
ASP.NET 5 Preview with VS 2015 RC. ASP.NET 5 is still in preview and is not recommended for production use at this time. You are free to use ASP.NET 4.6 in production.
Upgrade to RTM. Upgrading from RC to the final release (“RTM”) of Visual Studio and TFS 2015 should be smooth. For TFS, the upgrade from RC to RTM will work as it always has: You will need to install the latest TFS build and then run the upgrade wizard. Please note that TFS replaces whatever is installed on your computer, so make sure you have a full back up of your current databases.
In Production Support. If you have questions that aren’t addressed above, check out the Visual Studio 2015 RC Release Notes or you can submit them on MSDN Forums which are frequented by Microsoft MVPs and members of the product group.
All that said, while we have done a lot to make this release safe to use in production environments, please take adequate measures to back up and protect your data prior to (and after) upgrading to RC.
As you use RC, please give us your feedback, suggestions, thoughts, and ideas on our UserVoice site, through the in-product Send-a-Smile and Send-a-Frown UI, or file a bug through the Visual Studio Connect site to help fine tune the final release of Visual Studio.
Thanks,
John
This was amazing work guys!
I'm disappointed about 'Code' a cheap editor wich is non-userfriendly, the UI sucks, is this only for ASP.NET ? Does simple console apps work ? This 'Code' is completely bizare, i hate it already
Really guys, making Visual Studio crossplatform would have been a better choice thanthis stupid Atom fork ..
@scel
If you don't like it, don't use it.
I think you're missing the fact that it's a preview. Not the final product, not even a beta.
VS Code makes perfect sense in MS 's strategy.
Why no beta? In my experience a RC isn't going to change much anyway until the final release, yet we didn't get any previous version of VS 2015 that could be tested in a production environment (which is the only environment that matters).
I think this build has broken TFS
@Florian
We had a Preview in November, and two CTPs (CTP5 and CTP6) since then. We don't really use the term "beta" much any more for Visual Studio — the term started to mean too many things to too many people.
We do still have time to take feedback, though, so please send it.
John
This is great guys, congratulations! Btw, there is any ETA for the Productivity Power Tools 2015?
I keep getting the following error when I try to install:
Windows 10 SDK 10.0.10069 : The installer failed. User cancelled installation. Error code: -2147023294
Contrary to what the message says, I did not cancel the installation.
@John Montgomery
The "term" doesn't matter to me either, but none of the CTPs were allowed to be installed on production machines (and previous "betas" were). So how am I supposed to test it properly?
I cannot install VS 2015 RC, installation is stuck at "Microsoft Build Tools 14.0 (x86). No errors, nothing in log files. Same with standalone installation BuildTools_Full.exe.
Please help
@Edison
Thanks!
We don't currently have anything to announce about Productivity Power Tools for Visual Studio 2015, but we are aware that the tools are important to many developers.
Mark
Ive uninstalled VS 2015 CTP6, and installed VS 2015 Community RC, and license expier after 15 days, no way to extend this date. So short testing period or there is a way to extend this date ?
@Chris, can you give me more details? What is broken?
Ed.
@Tristan. Sorry for the confusing product message. We have an incorrect date in one of the token files VS downloads that specifies the trial period for RC. The date is set to 5/15/2015 and should really be 11/1/2015. We have an update with the correct date deploying to production in a few days. VS will pick up the new date the next time it checks online for an updated token and will resolve the issue silently for you.
@Florian
I'd have to go back and check, but with one exception from ASP.NET a long time ago, I don't think we've done a lot of betas with go-live licenses. So we think about this next time around, were you mostly interested in TFS go-live, .NET go-live, ASP.NET go-live or…?
John
@John Montgomery: Both VS 2012 and VS 2013 preview / beta versions were available as go-live. I'm only interested in the IDE itself, because that's what I'm using at least 40 hours a week and I prefer it to be a good experience. Doing some tests in a VM does not ensure that.
@Holan Jan, can you run and share %TEMP%vslogs.cab on OneDrive, Dropbox, or some other place we can take a look at exactly where it's stuck. This collects a lot of logs that can help diagnose the issue.
1. In VS 2012 and 2013 javascript files that are somewhat long (> 600 lines), there is sometimes a delay when typing on a new line (like the word "function" or "if")…for a few seconds before the characters appear. This started when you re-wrote the .js editor in 2012. In 2015 it's better but still has the delay sometimes. Is this any better in the RC ?
2. Will the RTM have any improvement in allowing us to opt-out of things during install, or are you going to put that off once more until the next version?
For some reason, the Diagnostic Tool is not working for me, appears the message: "The diagnostic tool failed unexpectedly. The diagnostics Hub output in the Output window may contain additional information.". In the pointed output shows: "Um recurso de cluster falhou." (translating the message from pt-BR: A cluster resource failed.).
I have tried reset the configuration, tried run "devenv /setup" and "devenv /updateconfiguration", but no luck. It's Visual Studio Enterprise 2015 RC.
Can this be upgraded to Community version later?
@Adam & others…
Regarding this error: Windows 10 SDK 10.0.10069 : The installer failed. User cancelled installation. Error code: -2147023294
We're working to provide a full solution in VS setup. In the meantime, to work around this issue, go to dev.windows.com/…/windows-10-developer-tools. Scroll to the bottom of the page and install the Windows 10 SDK and Windows 10 emulators outside of Visual Studio setup.
@Edison: we've seen scattered reports of this issue, it would really help us to determine the root cause if we could collect logs from your machine. Can you contact me at dantaylo [at] Microsoft.com so that I can provide instructions?
VS2015RC: I downloaded the full installer using the command line /layout switch (as I usually do). After downloading everything it still took 5 hours to do a FULL install of all options. At no point did it look like it was still 'acquiring' according to the progress bars. I suspect however that in fact it really was downloading something else (maybe smartphone emulators/images???). I mean it had to be, right? What else could be taking all that time? *AND* Visual Studio 2013 won't run while the VS2015 installer is running. Of course once I was an hour+ invested in the 2015 installation I wasn't going to cancel it. I would not have imagined it was going to take 5 hours. So basically I lost a day of coding to the installer. No I don't have a crap PC: Quad i7 with 24gig of RAM. It would be nice if the installer better informed about the estimated time or made it clear that it was going to have to download more files based on user option choices in the installer.
Awesome stuff! Good job teams!
@Heath Stewart, Thanks.
I run vscollect and there is my logs download…/vslogs.cab
It seems that although the download page contains html source code for multibyte support in MFC link, it is not accessible directly.
It's the VC_MBCSMFC.exe file.
Although I could find the link from the source code, it would be probably better if the link was accessible to users 😉
While we appreciate the support for markdown welcome pages, the more or less standard way to resize an image doesn't work:
or
I have no idea why this doesn't work, but I'm guessing you once again rolled your own.
@Tristan, can you please reach out to me: acabello (at) microsoft . com for your licensing issue? I'd like to help!
@Istvan, thanks for reporting this, can you shoot me a mail at meyoun at microsoft dot com and let me know where you’re seeing the MFC link in source? We are in the process of getting MFC Mutibyte Library for VS 2015 RC published as a standalone installer and you should expect to see it alongside our other available products within a few business days.
Great stuff!
Side note that others may find useful: I wish the implications of this (msdn.microsoft.com/…/dn706236.aspx) had occurred to me this morning now that I am on 10074. The XAML designer (for modern/phone apps) is totally broken until you do the workaround there and enable the group policy settings (and reboot). It only dawned on me after fighting with it for a few hours today.
I had VS 2015 CTP release and was able to create Universal App and deploy to ARM emulator (deploy failed but that's another problem). I uninstalled everything and installed 2015 RC and now if I create universal app there are no emulators listed if I build for ARM, just Remote Machine and Device (which I don't have connected). When I installed 2015 RC I did not select any Android emulators nor any 8.x emulators. Only selected Universal App Dev tools which included Emulators for Windows Mobile 10.0.1069. This is on a Surface Pro running windows 10 build 10049. The menu does include a selection 'Download New Emulators' but if I go that route it says 'already installed'. Any way to get emulators to show up in 2015 RC?
@Bill Pittore — please zip up the setup log files and email them to me at paul<dot>chapman<at>Microsoft.com. The setup logs are in your %temp% folder. You'll want the files starting with dd_*.* and the folders Emulator and Standalonesdk. We'll investigate.
Thanks
-Paul
Please add column guides option for the text editor. You only need to add a GUI settings, you already have it! blogs.msdn.com/…/659281.aspx
@Dean, I'm sorry to hear you've experience perf problems with earlier versions of VS. We've made a huge number of "behind-the-scenes" improvements to the JavaScript editor in VS 2015 and perf — especially for projects making use of d.ts files — is hitting most of our goals. Having said that, if you continue to experience problems, we strongly encourage you to write the product team via UserVoice or (even better) use the smiley-face in the top-right corner of the window to provide contextual feedback. We earnestly read every one.
Regarding the ability to opt-out of certain components, our goal is absolutely to provide as much developer control over installation and setup. Are there specific components you'd like to see sub-divided to provide better control over the install and setup process?
Should i use it to personal production machine all things are stable regarding to web and Windows phone development.
I have been using VS premium 13
@Ryan Salva,
There's already a user-voice item called "Make the Visual Studio installer more customizable" with over 1600 votes. Like many other people, I want the option to NOT install:
— C++ (compiler and tools: if I don't program in C++, please don't put over 700MB of that on my drive)
— Windows Phone components
— ALL SDKs (phone, WCF, Azure, Android, etc.)
— Mobile emulators (Android, etc.)
— Blend
— **All things Azure**
— Python tools
— SQL Server Express and Local DB
etc. etc. etc.
There's no doubt the installer currently spams the heck out of your drive.
WRONG LINK. PLEASE FIX THIS! I'M EAGER TO LEARN MORE ABOUT THIS INCREDIBLE EDITOR
On the page "BUILD 2015 News: Visual Studio Code, Visual Studio 2015 RC, Team Foundation Server 2015 RC, Visual Studio 2013 Update 5"
blogs.msdn.com/…/build-2015-news-visual-studio-code-visual-studio-2015-rc-team-foundation-server-2015-rc-visual-studio-2013-update-5.aspx
there is a section:
, or watch some videos, or read this blog post and follow Visual Studio Code on Twitter."
In the last sentence "Visual Studio Code docs", "watch some videos" and "blog post" are separate links however both the first ones takes me currently to the same page "Why Visual Studio Code?" (at code.visualstudio.com/…/docs) and there are no videos to watch there.
very good
Like IT
Will there be a Visual Studio Community 2013 Update 5 German iso available instead of language pack?
Having logged into VS 2015 community RC the license status shows as expiring in 13 days even after checking for an updated license – how can this be fixed?
Really loving this release – congrats
@Ulf Landgren
Thanks for pointing out the missing link. I have edited the post and shared a link to the demo video from BUILD and a 'meet the team' video from Channel 9. In addition, check out the home page of for a quick overview of Visual Studio Code.
Radhika Tadinada [MSFT]
@Dean – This is something we are working on right now.
Thank you for the feedback!
Parul
@JustMe: We are not planning on releasing any ISOs for the VS Community 2013 Update 5 RC product, but we will release ISOs for the VS Community 2013 Update 5 RTM product. This is what all prior VS 2013 Updates have done. I'm curious, though – what is your scenario and why do you ask?
Whoops just read @Anthony Cangialosi answer above to my earlier query.
That Android Emulator is really slick.
@Alessio T:
Thanks for the feature request. Whilst we're not planning on adding column guides in the current release, you can get it (for Visual Studio 2013) via various editor extensions including the Productivity Power Tools for Visual Studio 2013 visualstudiogallery.msdn.microsoft.com/dbcb8670-889e-4a54-a226-a48a15e4cace .
Mark Wilson-Thomas, Visual Studio Editor PM
Lasted versions requieres to log in in Visual Studio. I dont use the cloud. I dont want the need to sign in in order to use a product. Also, in some cases, i dont have a network connection. Also, i dont want to share my preferences, options, configurations with Microsoft. And I dont want to share my code with Microsoft.
Also i lost my confidence in Microsoft. My world is not mobile first, cloud first. I dont develop to the cloud or mobile.
Requiring and forcing to log-on in order tu use Visual Studio, is the best feature to discard this version and continue sticking with Visual Studio 2010 in all our developer teams and also to not recommend it.
I'm struggling to get VS 2015 RC installed, I keep getting an error with Visual Studio Team Explorer Language Pack Enu failing half way through the install. If I look at the logs it's complaining about an invalid drive which points to a network drive I have, which exists and works. But I have the installer on a local drive (is there an ISO available?), and the installation folder is local so not sure why it would even look at my network drive.
@Christine the reason I want the ISO is to help sort out installation issues. I want to locate vs_teamExplorerCoreRes_enu to skip the 30min wait when attempting fixes (I'm having to choose repair install since the vs installer is not offering me the ability to continue install since only half the stuff is installed).
Can I use TFS online with Visual Studio Code?
@Stefan – If I understand your question correctly yes you can use Visual Studio Code with Visual Studio Online (or Team Foundation Server for that matter) as long as you host your code using Git. We actually do all of our own development with Visual Studio Online and it works a treat.
Here are out Git docs. code.visualstudio.com/…/versioncontrol
Sean McBreen – Visual Studio Code team member
@Radhika Tadinada
Thank you for puting in the missing link to the video.
The presentation was really great.
no idea why you are asking for a feedback but then ignoring it with this silly excuse:
editor syntax coloring stops working on lines longer than 32769 characters (connect.microsoft.com/…/editor-syntax-coloring-stops-working-on-lines-longer-than-32769-characters) which you submitted at the Microsoft Connect () site.
Hi jojomano,
Thank you for bringing up this issue to our attention. We will consider addressing it in the event that we receive more feedback indicating that this scenario significantly impacts the xml/xaml development experience.
Best,
Kino
I've hit a problem with the c++ compiler wrt 'sized deallocation' support. I know that this was just turned on in VS 2015 RC. I'm not an expert in 'placement new' syntax but I think that the MSC compiler is parsing a construct incorrectly. Here's what it looks like:
void* Chunk::operator new(size_t requested_size, size_t length) throw() {
return CHeapObj::operator new(requested_size + length);
}
void Chunk::operator delete(void* p, size_t length) {
CHeapObj::operator delete(p);
}
…
Arena::Arena( size_t init_size ) {
init_size = (init_size+3) & ~3;
_first = _chunk = new (init_size) Chunk(init_size);
On the line above I get error C2956: sized deallocation function 'operator delete(void*, size_t)' would be chosen as placment deallocation function.
note: see declaration of 'Chunk::operator new'
(You can see the full source at hg.openjdk.java.net/…/arena.cpp)
I built a gcc 5.1 release which also supports 'sized deallocation' and was able to compile this code with the -std=c++14 argument passed to g++.
In the above code, 'init_size' is a size_t and not a void * so I'm not sure why MSC compiler thinks that this is a placement new call.
Is there any way to turn off this particular feature via some flag or pragma?
thanks.
After re-reading some C++ doc, I guess the code I wrote about above would be an instance of a custom allocator using the placement new syntax. The issue then is why MSC++ compiler is complaining about the sized deallocation function void Chunk::operator delete(void* p, size_t length). That seems correct and it does build with gcc 5.1 with -std=c++14 option.
The error code given doesn't show up as an error in the current VS 2015 doc; at least I couldn't find it.
The installer (enterprise) has hang on my spent about 2 hours on "Android SDK Setup (API Level 19 and 21, System Images)
I had CTP 6 and did not do an uninstall. The installer has now being going about 9 hours so something is wrong. I am going to do a hard shut down and see what happens.
The server deployment that updates the RC timebomb from 5/15 to 11/1 is now live. VS will pick up the new date automatically but if you want to force a refresh you can open "File -> Account Settings" and click "Check for an updated license".
@Anton
Its likely that the installer was not able to acquire / download the 3rd party package from the Android site. If the issue does not resolve with your reattempt please let me know and I will send along instructions to figure out what exactly is going on.
Pat Litherland
@Edison – We've identified a primary cause for the error message "The diagnostic tools failed unexpectedly…." A fix will be included in the next public release of Visual Studio 2015. Until then, there are a few potential workarounds for RC. Check them out on the VS Diagnostics blog: blogs.msdn.com/…/known-issue-for-diagnostics-tool-window-in-visual-studio-2015-rc-the-diagnostic-tools-failed-unexpectedly.aspx
How to get Visual Studio 2015 RC any version to work on a Windows 7 Desktop?
connect.microsoft.com/…/visual-studo-community-enterprise-and-express-can-not-install
Please help 🙂
Please release a 2015-compatible version of Productivity Power Tools in time for release. It's something I've come to depend on and I will not be willing to upgrade from 2013 to 2015 unless that extension is also available.
Better yet, provide the source for Productivity Power Tools on GitHub.
Hi @Joel
Thanks for your feedback and suggestions. As mentioned above, we don't currently have anything to announce about Productivity Power Tools for Visual Studio 2015, but we are aware that the tools are important to many developers.
As an aside, I'd be interested in hearing more from you and other Productivity Power Tools users about which particular features of the tools you depend on most in your day to day work, and why. Drop me an email at mwthomas at microsoft dot com.
Thanks!
Mark Wilson-Thomas
Where is build for docker image for local deployment in our in-house servers?
Where is C# /.net native development for Wdnows Phone, ios and android without wrapping a html/javascript app?
@Michael – Sorry you're having these troubles installing. If you wouldn't mind, we'd really appreciate you logging a bug via our Connect site because then the issue can get routed directly to the engineer who can address your problem, and they can then close the loop with you directly. The link to the Connect site is above, at the bottom of the blog post, right about John's picture. Because the issue seems to be with VS Team Explorer Language pack, I actually recommend opening the connect bug against "Team Foundation Server 2015 RC" (as opposed to VS) because that team implements the Team Explorer functionality.
To get one of the VS 2015 RC ISOs directly, navigate your browser to…/visual-studio-2015-downloads-vs, click on "Visual Studio 2015" on the BOTTOM left hand side of the page, choose the edition you want from the submenu, and then change the "Download format" option from Web installer to ISO.
Hope this helps 🙂 Thank you for your feedback.
Christine
I'm running into the 'C2956: sized deallocation …' placement new/delete problem that bill pittore posted. Has this been officially acknowledged? Is there a work-around?
The new toolbar window that lets me select which startup project to use is nice but in 99% of cases I use multiple startup projects and it doesnt let me select that option from the list. I only have the option of choosing a single project as startup.
@bill pittore & Cary Sandvig
Thanks for reporting the issue! Yes, this is a bug that we will target fixing before the RTM (final) release. For now using the compiler switch /Zc:sizedDealloc- will workaround the issue till we fix it.
Thanks!
@bill pitore @Cary Sandvig
An update on the sized deallocation issue. There is a known bug in the implementation in RC where we emit this error when we should not. However, looking at this code I believe the error is correct in this case. Are you building with gcc with the -fpermissive option? The simplified repro below emits similar errors with all of MSVC, Clang, and gcc 5.1. If this is not an accurate representation of your source please let me know how it differs, I did not attempt to build the entire project.
#include <utility>
using namespace std;
class CHeapObj {
public:
void *operator new(size_t size) throw();
void operator delete(void *p);
};
class Chunk : public CHeapObj {
public:
void * operator new(size_t sz, size_t length) throw();
void operator delete(void *p, size_t length);
Chunk(size_t length);
};
class Arena : public CHeapObj {
Arena(size_t init_size);
Chunk *chunk_;
};
Arena::Arena(size_t init_size) {
chunk_ = new (init_size) Chunk(init_size);
};
Note: Both MSVC (as of the latest in-house development state) and GCC 5.1 will compile the above if you add "using CHeapObj::operator delete;" to the Chunk class – this un-hides the 1-argument delete in Chunk and causes the two-argument delete to no longer be considered a usual deallocator. Clang does not alter behavior with the added using declaration. The particular bug present in the RC is that the 2-argument deallocator will be considered a usual deallocator even when a 1-argument deallocator is present in the class, and this is incorrect.
The code snippet you have looks ok. As I mentioned the actual source is at hg.openjdk.java.net/…/adlc
When I compiled with gcc 5.1, this is the command line (minus all the -I options for clarity):
/export/tools/gcc-5.1.0/bin/g++ -DLINUX -D_GNU_SOURCE -DAMD64 -DASSERT -DTARGET_OS_FAMILY_linux -DTARGET_ARCH_x86 -DTARGET_ARCH_MODEL_x86_64 -DTARGET_OS_ARCH_linux_x86 -DTARGET_OS_ARCH_MODEL_linux_x86_64 -DTARGET_COMPILER_gcc -DCOMPILER2 -DCOMPILER1 -fno-rtti -std=c++14 -fno-exceptions -D_REENTRANT -fcheck-new -fvisibility=hidden -pipe -fno-strict-aliasing -Werror -g -c -o ../generated/adfiles/arena.o /export/jdk8u/hotspot/src/share/vm/adlc/arena.cpp
There are no warnings emitted.
Are you saying that the 'using CHeapObj::operator delete;' line is the proper fix for the issue? Or is that a workaround?
thanks,
bill
@bill pittore
Thank you! The culprit is -fno-exceptions. Adding this option to my simplified repro causes it to compile with gcc 5.1.0 and Clang. This makes sense: The placement delete is only needed and looked up if the constructor for Chunk throws an exception, and -fno-exceptions tells the compiler this can never happen. But strictly speaking I'd argue this program is technically ill-formed, but accepted by those compilers with -fno-exceptions.
I'm not certain I can make the claim that adding the using declaration is the correct fix: the wording in the standard here is unclear and there is variance in how different compilers behave with it (it wouldn't fix the issue in Clang without -fno-exceptions, for example). This is an issue we can bring up with the C++ standardization committee for clarification. This fix also won't work with the RC version, due to the bug I mentioned before, but is fixed for RTM and in the meantime you can use /Zc:sizedDealloc- to work around the issue. A fix that works with all compilers I have tested (again, after the RC bugfix) is to provide a one-argument operator delete function in Chunk.
Thanks Jonathan for the detailed explanation. I'll pass this info on to other team members who work directly on this code. In the meantime the /Zc option seems to workaround the issue.
bill
@Ayman Shoukry and @Jonathan Emmett, thank you for your response. Adding /Zc:sizedDealloc- definitely addressed my problem allowing me to continue testing my codebase against 2015. For completeness I'm including below a very reduced complete fragment that generates the error for me in the way that it is used in my code.
template< typename TailT >
struct TailAllocationHelper
{
void * operator new(size_t size, size_t elements = 0)
{
return malloc(size + (sizeof(TailT) * elements));
}
void operator delete(void * site)
{
free(site);
}
void operator delete(void * site, size_t)
{
operator delete(site);
}
};
struct SomeTailType
{
unsigned val1, val2, val3;
};
struct TypeWithTail
: TailAllocationHelper<SomeTailType>
{
unsigned outter;
SomeTailType tail[];
};
TypeWithTail * factory(size_t count)
{
return new(count) TypeWithTail;
}
This will generate (when compiled without /Zc:sizedDealloc-):
1>—— Build started: Project: demo, Configuration: debug Win32 ——
1> Demo.cpp
1>C:startOverPlatformsrcdemoDemo.cpp(32): error C2956: sized deallocation function 'operator delete(void*, size_t)' would be chosen as placement deallocation function.
1> C:startOverPlatformsrcdemoDemo.cpp(32): note: see declaration of 'TailAllocationHelper<SomeTailType>::operator new'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Again, thank you for the work-around.
Do i need to download all components explicitly of visual studio 2015??
@Parul Bhargava,).
@Cary Sandvig
Thanks for the repro – this is indeed hitting the known bug in RC and will be fixed for RTM. I can compile that snippet with our current development build of the compiler.
I have a question on command line environment setup. If I run VC/bin/amd64/vcvars64.bat which calls Common7/tools/vcvarsqueryregistry.bat I end up with the following INCLUDE variable:
INCLUDE='C:Program Files (x86)Microsoft Visual Studio 14.0VCINCLUDE;C:Program Files (x86)Microsoft Visual Studio 14.0VCATLMFCINCLUDE;C:Program Files (x86)Windows Kits10\include10.0.10056.0ucrt;C:Program Files (x86)Windows Kits8.1includeshared;C:Program Files (x86)Windows Kits8.1includeum;C:Program Files (x86)Windows Kits8.1includewinrt;'
In Windows Kits10include there is a 10.0.10056.0 as well as 10.0.10069.0. The 10.0.10056.0 directory only has ucrt subdirectory. The 10.0.10069.0 directory has ucrt as well as um, shared, winrt. The vcvarsqueryregistry.bat script has 8.1 hardwired as the SDK to look for. If I want to build my project for Windows 10 desktop, phone, runtime whatever, should my INCLUDE variable just point into the 10.0.10069.0 directories instead of the 8.1 directories?
thanks,
bill
I'm trying a brand new TFS build server having ONLY VS2015 RC Premium and i can't get to build any project using UnitTest and MS Fakes. My TFS Server is still TFS 2013 Update 4.
My build definitions are using TfVcTemplate.12.xaml process template and i couldn't get fakes to be compiled until i changed the ToolsVersion=14.0 within every .csproj AND added /ToolsVersion=14.0 to the MSBuild Arguments within the build process template settings.
After this, my fakes would compile but i keep getting the error TF900547: The directory containing the assemblies for the Visual Studio Test Runner is not valid '' where the bin directory seems to always be empty.
Shouldn't the update/migration be more seemless?
Before i changed to ToolsVersion to 14.0 (in projects and Build definition) it kept searching for targets within C:Program Files (x86)MSBuildMicrosoftVisualStudiov11.0… and using C:Program Files (x86)MSBuild12.0
Is the only workaround i installing every version of VS to make it work?
I've also created a simple hello world project with a single unit test and i keep getting the same error. Can't make it any simpler…
Thanks who anyone who done the "same journey" who shares if informations!
@Dominic,
Thank you for reporting this. We will have this investigated and get back.
Will there be an update to the image library for VS 2015?
@Pratap Lakshman
Additionnal informations to previous post:
When i check my build log i can see that MSBuild.exe is called from the 12.0 version even if i've set the /ToolsVersion:14.0 to the MSBuild Arguments within the build definition… shoudn't it call the one from the 14.0 version?
Extracted from the build log:
C:Program FilesMicrosoft Team Foundation Server 12.0Toolsnuget.exe restore "SolutionFile.sln" -NonInteractive
C:Program Files (x86)MSBuild12.0binamd64MSBuild.exe /nologo /noconsolelogger "SolitionFile.sln" /nr:False …
@pmont – We will likely release an update to the Image Library for Visual Studio 2015 but I don't have any exact dates yet. We'll share more about this after we release the RTM for 2015, so stay tuned.
Thanks!
Cathy Sullivan (Visual Studio IDE Team)
Since Office 2016 will be available soon on Windows and OSX, I assume that the Excel TFS add-in is currently being updated to work on Excel 2016, but is it planned to make it work in the OSX version ?
I don't think it's that hard to do. Even if the TFS SDK is not available on OSX (maybe it's going to change) since there is the new REST API that should not require more than an HTTP library.
@Pratap Lakshman
Just to let you know that i've been able to make it work! I've upgraded the TFS Server and Build Server to TFS 2015 RC and my unit tests began to work!
I hope this is not not the only way to make it work tho… These were servers from my tests environment.
I just can't install the TFS 2015 RC onto my production environment and all our build server right now… but we got dev teams wich started development with VS2015 RC and their build server only have VS2015 RC.
Just hope you'll make it work (VS2015 with TFS 2013 Update 4) before the RTM release!
Is now "By Design" that when i try to open a build log (Team Explorer->Builds->Double click on a build) it nows only open within the browser and no more within VS2015?
Within the contextual menu, there is still an option saying "Open in browser"
Shouldn't the action "Open" opens the build within the IDE?
If anyone is wondering why the installer spends a long time at "Android SDK Setup", it is because the Android SDK is being downloaded. The progress isn't shown using the "acquiring" progress bar (but it should be!).
@Danny
Thank you for calling awareness to this issue. The Visual Studio Setup team is working on piping more progress information from the 3rd party installers back to our setup UI. The Android SDK is indeed a big download. We are working to better report that progress back to the user so you have a better idea of what's going on.
Pat Litherland
Was any solution found for the hangup when installing Build Tools 14.0?
I am trying to get Community 2015 RC installed but it keeps dying on "Microsoft Build Tools 14.0 (x86)".
After a few hours trying it comes up with "Fatal error during installation.".
@Les – what you're describing is something new to me (I'm the Engineering Manager in charge of VS setup), so would you mind helping me figure out what's happened on your machine by collecting setup-related log files?
To do so, I'll need you to run the VS setup collect tool and share the generated file via OneDrive/DropBox/…. To do this, run and then share %temp%vslogs.cab with me. It captures all VS install activity, so the file can be between 10-50MB.
Thanks, and I look forward to hearing from you at eric.knox@microsoft.com
Eric Knox, VS Engineering Manager
Can I have an answer about the TFS excel add-in 🙂 ?
@LiohAu, as you know we've been working hard to fill out our REST APIs. With that work, we will be able to move the Excel Add-in to the new Office Application platform. This would make the Excel integration functionality available on the web versions as well as installed versions. This is absolutely on our roadmap.
Thanks
What's up with VSTO and the RC? it won't seem to convert any of my old vsto add-ins; (and the preview did). Also these project types aren't in the product anymore from what I see. Has VSTO been depricated or killed? some of us still write outlook add-ins….
@Gregg Boar Allelouya !!! After 4 years of iOS development in a company using exclusively microsoft based technologies, I will finally be able to drop this VMWare Fusion and work efficiently with my coworkers directly from OSX.
What about TFS Power Tools 2015? When they be available? Please move to Visual Studio some features from TFPT: Find By Status, Find By Wildcard and Forced Check-out Undo.
I really like what I see in VS 2015 RC. I noticed, but maybe I missed something….changing matching brace color (say to red) seems to work fine for JS files, but for JSON matching braces continue to be highlighted in grey?
Great!! When we can see RTM version ?
Any idea when vs 2013 update 5 rtm finally will ship?
It's now almost 2 month since rc…
@JaviAl – I'd hate to see you stuck on VS2010 just because of the sign in option. For the vast majority of people using VS Enterprise or VS Professional, signing in is optional. You can skip it if you don't want to and you can use a key to license VS instead. For the VS Community, you need. I'd love to talk to you more about your specific scenario to learn more. Please do reach out to me at tarekm (at) microsoft (dot) com. Thank you. | https://blogs.msdn.microsoft.com/visualstudio/2015/04/29/build-2015-news-visual-studio-code-visual-studio-2015-rc-team-foundation-server-2015-rc-visual-studio-2013-update-5/ | CC-MAIN-2017-22 | refinedweb | 9,301 | 63.29 |
>
have a class that inherits from ScriptableObject with a few fields that can't be serialized and one that can be. In another script I create an instance of the ScriptableObject, set all of its fields and then save it using UnityEditor.AssetDatabase.CreateAsset(string path). I have a final script with a serialized field of the ScriptableObject. When adding the newly saved ScriptableObject to the third script and attempting to read data from it, the List and the Dictionary are both set to null, while the Sprite retains the value it was set to. Is there any way to save the List and Dictionary to the .asset file? My code is as follows: The ScriptableObject:
public class MyScriptableObject : ScriptableObject
{
public Dictionary<string, Sprite> sprites;
public Sprite sprite;
}
Where I save the ScriptableObject through code:
MyScriptableObject myObject = (MyscriptableObject)ScriptableObject.CreateInstance("MyScriptableObject");
Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
//loadedSprites is a [SerializeField] List<Sprite> present in this class
for(int i = 0; i < loadedSprites.Cout; i++)
{
sprites[i + ""] = loadedSprites[i];
}
myScriptableObject.sprites = sprites;
myScriptableObject.sprite = loadedSprites[0];
Where I attempt to read the saved ScriptableObject elsewhere:
//loadedMyScriptableObject is a [SerializeField] MyScriptableObject present in this class
//and I drag the saved asset onto this script
//when this code is run, loadedMyScriptableObject.sprites is null,
//but loadedMyScriptableObject.sprite is what it was set to in the previous code
List<Sprites> sprites = loadedMyScriptableObject.sprites;
Sprite sprite = loadedMyScriptableObject.
Prevent changes in ScriptableObject type Asset in Editor. Dont save it.
0
Answers
Determining which Asset is connected to a GameObject.
3
Answers
Where are asset labels stored?
1
Answer
Get prefab's path in file system
2
Answers
Importing and using custom assets
0
Answers | https://answers.unity.com/questions/1536722/saving-a-scriptableobject-with-complex-fields.html | CC-MAIN-2019-18 | refinedweb | 281 | 56.96 |
Brian Moseley wrote:
> Brian Moseley wrote:
>
>> my understanding is that you should be able to set arbitrary
>> properties on any resource that advertises support for PROPPATCH. but
>> i might be wrong :)
SHOULD :)
> furthermore, what's your take on PROPPATCHing the DAV:displayname
> property? it's not possible at the moment, but it seems like a standard
> operation that any webdav client would expect to be able to do. i don't
> believe that's a protected property.
sure, its not protected.
rfc says:
"Execution of the directives in this method is, of course, subject to
access control constraints. DAV compliant resources SHOULD support the
setting of arbitrary dead properties."
the name of the underlaying repository item cannot be altered, so
i think its fine that PROPPATCH for this fails.
i suggest to add all jcr-properties present on the underlaying
resource to the set of dav-properties present on the resource and
an attempt to call setProperty on the simple DavResource will try
to set them... so it would be possible to use the PROPPATCH with
the given implementation... i will do that.
regards
angela
ps: "DAV:" is defined to be the namespace uri.. not the prefix.
thats what i attempted to write before.... ;) | http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/200507.mbox/%3C42DF73C7.2000805@day.com%3E | CC-MAIN-2016-40 | refinedweb | 204 | 65.62 |
I'm new here, but it looks like an awesome place to get some help.
My assignment is to write a recursive function that determines the value of a unit of Pascal's triangle given the row and column, then use that to display the triangle with n number of rows. It's taken me quite a while to just understand how the Pascal's triangle works, much less code it. I don't totally understand the mathematical logic for it. I've finally coded it with an iterative loop, but I'm not sure I can figure it out recursively... or if I am supposed to... anyway, I've got my plain vanilla loop coded here.
#include <iostream> using namespace std; int main() { int n,k,i,x; cout << "Enter a row number for Pascal's Triangle: "; cin >> n; for(i=0;i<=n;i++) { x=1; for(k=0;k<=i;k++) { cout << x << " "; x = x * (i - k) / (k + 1); } cout << endl; } return 0; }
If anybody can help or guide me, it'd be great. | https://www.daniweb.com/programming/software-development/threads/68837/c-pascal-s-triangle-recursively | CC-MAIN-2017-34 | refinedweb | 177 | 69.01 |
Board index » MFC
All times are UTC
hello, i am creating a screen saver that uses multiple bitmaps, but as of now i can only show one. My .rc2 looks like
Just add the following line the top of drawwnd.cpp
#include "resource
Create another file called (any filename will do), say "bitmaps.rh" that has the content... ----- #define IDB_BITMAP1 9001 // this number must be a unique resource identifier #define IDB_BITMAP2 9002 // this one too ----- Now, include this file in your .rc2 by adding the following line of code to the .rc2 file... ----- #include "bitmaps.rh" ----- Now you can include this resource header in your source files to use the identifiers, IDB_BITMAP1 and IDB_BITMAP2 to refer to the previous resources. I hope this helps you. --
MiddleWorld SoftWare - -------------------------------------------------- He went out of his way to be good.
>
I'm sort of curious why you have these declarations in the .rc2 file. What is missing is that in resource.h you should have the declarations of #define IDB_BITMAP1 and #define IDB_BITMAP2. If you created these bitmaps in the .rc file, the resource editor would have created these definitions for you. Since you appear to have added them by hand to the rc2 file yourself (an unusual way, as I say), you don't have the symbols defined. If you *do* have the symbols defined, you have not included the header file in the compilation of the file that gives the error. joe
1. C's Qs
2. Using Resource .RES files to stick .bmp's and .wav files into .exe
3. HELP WITH BMP'S!!!!!!!!!!!!
4. Using multiple pch's in a project
5. Get access to a view's member var from another view using multiple templates
6. Multiple SDK's for EVC++ using the same CPU
7. View BMP imromation program with 'Dll'
8. View BMP imromation program with 'Dll'
9. Tool to help reduce multiple #include's
10. Help returning multiple int's from func...
11. Need Help using DLL with 'C'
12. Help: Sol'n of linear eq's using full pivoting | http://computer-programming-forum.com/82-mfc/25cb7d3c33208c20.htm | CC-MAIN-2022-33 | refinedweb | 344 | 76.93 |
Difference between revisions of "RPi CANBus"
Revision as of 06:22, 23 May 2013
CAN-bus is a communication protocol used mainly in car and some industrial products.
The Raspberry pi doesn't have CANbus built in, but it can be added through USB or SPI converters.
This document presents how to enable CANbus support in the kernel, using a SPI to CANbus converter (MCP2515). The same can be done for other SPI converters, or for PeakCAN Usb.
Raspbian kernel doesn't come with modules needed, so the kernel must be compiled from source. Refer to for more information on this. The following instructions present all steps requiered to build a kernel with the correct modules, and some useful commands to use it.
Contents
Prerequisite
At least, a proper gcc installation is needed, and ncurses development package are used by kernel menuconfig.
sudo apt-get install gcc ncurses-dev
Kernel configuration and compilation
For this example, everything will be done in a directory "/opt/raspberrypi/". So first create it, and then checkout the last version of the kernel for the raspberrypi in the linux subdirectory.
cd /opt sudo mkdir raspberrypi cd raspberrypi sudo chmod og+w . git clone --depth 1 cd linux
At the time of writing, the current kernel trunk version is 3.2. To use the 3.6 kernel, an additional branch has to be fetch.
git fetch --depth=1 git://github.com/raspberrypi/linux.git rpi-3.6.y:refs/remotes/origin/rpi-3.6.y git checkout rpi-3.6.y
Then copy the default cutdown .config file, and run the "oldconfig" make to make it up to date.
cp arch/arm/configs/bcmrpi_cutdown_defconfig .config make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- oldconfig -j 3
From the default file, I only changed the two following lines (first is for cross-compiling the kernel), and pressed "enter" for all other (there are a lot...).
Cross-compiler tool prefix (CROSS_COMPILE) [] (NEW) arm-rpi-linux-gnueabi- Default hostname (DEFAULT_HOSTNAME) [(none)] (NEW) raspberrypi
Then the CAN bus support must be added using "menuconfig" (see.)
cd /opt/raspberrypi/linux251x SPI CAN controllers ................[*] CAN devices debugging messages ....Device Drivers ---> ........[*] SPI support ---> ............<M> BCM2798 SPI controller driver (SPI0) ............<M> User mode SPI driver support .......-*- GPIO Support ---> ............[*] /sys/class/gpio/... (sysfs interface)
If another driver is used, activate it in place of the "MCP251x SPI CAN controllers". If using a USB controller, then SPI support is not needed, but USB must be correctly set up.
Then edit the board definition, to add the informations about the SPI bus, and to configure the interrupt pin of the MCP2515.
vi arch/arm/mach-bcm2708/bcm2708.c #apply patch
Note that the "IRQF_ONESHOT" flag is only required for kernel 3.6. For kernel 3.2 you should remove it. Adjust the GPIO pin used for interrupt (here 25), the SPI frequency (here 10MHz) and MCP2515 oscillator frequency (here 20MHz) to your setup.
diff --git a/arch/arm/mach-bcm2708/bcm2708.c b/arch/arm/mach-bcm2708/bcm2708.c index 838e0f2..10026ec 100644 --- a/arch/arm/mach-bcm2708/bcm2708.c +++ b/arch/arm/mach-bcm2708/bcm2708.c @@ -54,6 +54,12 @@ #include <mach/vcio.h> #include <mach/system.h> +#include <linux/can/platform/mcp251x.h> +#include <linux/gpio.h> +#include <linux/irq.h> + +#define MCP2515_CAN_INT_GPIO_PIN 25 + #include <linux/delay.h> #include "bcm2708.h" @@ -586,11 +592,21 @@ static struct platform_device bcm2708_spi_device = { .resource = bcm2708_spi_resources, }; +static struct mcp251x_platform_data mcp251x_info = { + .oscillator_frequency = 20000000, + .board_specific_setup = NULL, + .irq_flags = IRQF_TRIGGER_FALLING|IRQF_ONESHOT, + .power_enable = NULL, + .transceiver_enable = NULL, +}; + #ifdef CONFIG_SPI static struct spi_board_info bcm2708_spi_devices[] = { { - .modalias = "spidev", - .max_speed_hz = 500000, + .modalias = "mcp2515", + .max_speed_hz = 10000000, + .platform_data = &mcp251x_info, + /* .irq = unknown , defined later thru bcm2708_mcp251x_init */ .bus_num = 0, .chip_select = 0, .mode = SPI_MODE_0, @@ -602,6 +618,13 @@ static struct spi_board_info bcm2708_spi_devices[] = { .mode = SPI_MODE_0, } }; + +static void __init bcm2708_mcp251x_init(void) { + bcm2708_spi_devices[0].irq = gpio_to_irq(MCP2515_CAN_INT_GPIO_PIN); + printk(KERN_INFO " BCM2708 mcp251x_init: got IRQ %d for MCP2515\n", bcm2708_spi_devices[0].irq); + return; +}; + #endif static struct resource bcm2708_bsc0_resources[] = { @@ -749,6 +772,7 @@ void __init bcm2708_init(void) system_serial_low = serial; #ifdef CONFIG_SPI + bcm2708_mcp251x_init(); spi_register_board_info(bcm2708_spi_devices, ARRAY_SIZE(bcm2708_spi_devices)); #endif
Then compile the kernel. The example below is for cross compilation, using a 2 core x86 machine. For compiling on the Pi, just type "make".
make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- -j3
Then install the tools from git.
cd /opt/raspberrypi/ git clone --depth 1 git://github.com/raspberrypi/tools.git
Use the tools to generate an image from the build kernel, and copy that to a new "build" directory.
cd tools/mkimage ./imagetool-uncompressed.py ../../linux/arch/arm/boot/zImage mkdir -p /opt/raspberrypi/build/boot mv kernel.img /opt/raspberrypi/build/boot
Then return to the linux directory, to compile the kernel modules, and copy them to the build directory.
cd ../../linux/ make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- modules_install INSTALL_MOD_PATH=/opt/raspberrypi/build/ -j3 cp .config ../build/boot/
Again from git, get the last firmware for the raspberrypi, and copy it to the build directory.
cd .. git clone --depth 1 git://github.com/raspberrypi/firmware.git cd firmware git fetch --depth 1 git://github.com/raspberrypi/firmware.git next:refs/remotes/origin/next git checkout next cp boot/bootcode.bin /opt/raspberrypi/build/boot cp boot/fixup.dat /opt/raspberrypi/build/boot cp boot/start.elf /opt/raspberrypi/build/boot mkdir -p /opt/raspberrypi/build/opt cp -r hardfp/opt/vc /opt/raspberrypi/build/opt
You should now have the complete new kernel/modules/firmware in the "/opt/raspberrypi/build" directory. If you want to use it, simply puts its contents to the root directory. It is possible to do it directly without using a temporary build directory, but this method has the advantage of being possible on a remote machine, and to allow easier save of the binary generated (simply archive this directory if you need to give it to someone else).
MCP2515 Asynchronous Driver
The standard MCP251x has some drawbacks with kernel 3.6. It happens that it hangs and stop receiving frames. It has something to do with the "IRQF_ONESHOT" flag. Refer to the Raspberry Pi forum, for latest discussions on this point :.
However, another MCP2515 driver exists, and has been successfully tested with kernel 3.6. Please not that it only allows to use a MCP2515 and no MCP2510 like the MCP251x driver.
You can download it and activate it in your kernel like follows.
cd /opt/raspberrypi/linux wget gunzip linux-mcp2515-20101018.patch.gz patch -p1 < linux-mcp2515-20101018.patch2515 SPI CAN controller ................[*] CAN devices debugging messages
Then go again through the kernel compilation (see above if some line is missing). and module with MCP2515 driver support.
SPI low latency patch
Finally, the SPI adds a lot of latency, that can results in frame lost at high CANbus rate, due to the small receive buffer of the MCP2515 controller.
This can be reduced using the following patch. Refer to the discussion on the forum for more details :.
Warning : following the commit of 22 January 2013 () the patch fails to apply. A new patch is in process, see the forum above to check the last patch.
These instructions download it from the forum and apply it.
cd /opt/raspberrypi/linux wget -O spi-latency-branch3.6.y.patch.bz2 bunzip2 spi-latency-branch3.6.y.patch.bz2 patch -p1 < spi-latency-branch3.6.y.patch
Then a new compilation of the kernel is done. patched SPI driver with low latency. | http://elinux.org/index.php?title=RPi_CANBus&diff=next&oldid=215948 | CC-MAIN-2017-30 | refinedweb | 1,227 | 51.55 |
This blog has moved to please update your links!
WCF Data Services provides a very simple model driven way to expose data using REST and the OData format. As I was preparing my talk for Tech-Ed on Implementing REST in .NET I was asking myself if there would be any value in using Windows Server AppFabric with WCF Data Services. After all, AppFabric has monitoring which can capture tracking information across the server farm storing it in a monitoring database. Typically we show Workflow Services using this capability because they provide such a rich stream of tracking events. However, it is quite possible to use AppFabric to monitor data services. In this post I’ll take you through step by step how you can do it.
Note: To make this post more readable – click on the images to see them full size. The team also has a sample on this here
To benefit from Windows Server AppFabric your web application must be hosted in IIS. To use Visual Studio with IIS you must run it as administrator. Then go into the project properties of your web application and set it to run in the local IIS server.
In my RESTWeb demo application I’ve added some links to the Default.htm page that will exercise the service. If you run the app and hit a few pages you will see that AppFabric captures information about your service being invoked.
To see it
Here you can see that there were 4 calls to the WCF Data Service named Conference.svc. If you click on the hyperlink for Conference.svc you will get the detail on those 4 calls.
This is good, but because we have a WCF Data Service all the requests look the same in the tracking data. We can see that somebody invoked the service but we don’t know what things they were querying in the model or if they were doing a GET, POST, PUT etc.
In my RESTWeb web application, I’ve added some sample code I got from the AppFabric guys (with some minor modifications from me) that shows how you can emit a custom tracking record that will be displayed in AppFabric. By overriding the DataService.OnStartProcessingRequest method, I can now emit a tracking record with details of the request.
public class Conference : DataService<ConferenceDataEntities>
{
// Sample class allows you to emit custom tracking records
static WCFUserEventProvider eventProvider = new WCFUserEventProvider();
protected override void OnStartProcessingRequest(ProcessRequestArgs args)
{
string text = string.Format("Processing HTTP {0} request for URI {1}",
args.OperationContext.RequestMethod, args.RequestUri);
// Push the event through ETW to AppFabric
eventProvider.WriteInformationEvent("Conference Request", text);
}
To make this work you have to turn on end-to-end tracking in AppFabric. To do this
Step 5 – Verify Behavior
The attached sample code is what I showed at my Tech-Ed Session. Hope you find it helpful.
Hi Ron, excelent post.
I have a question for you, how can I filter the events using the tracked information as a filter?
Using your example, something like: Payload = 'filter value'
Thanks in advance...
The tracked events are stored in a database so you can query filter or do whatever you want with them.
Ron, thanks for your reply.
I understand you, but I want to use the user interface of AppFabric, but i think that is not possible to do.
Let me explain my idea, I want to implement an extension to the AppFabric's monitoring, the new functionality let you define "promoted fields" from request and response messages in a WCF service(this fields will be tracked), and I want to be able to query using this information in the same way that AppFabric filters using tracked WF variables.
As I can see, I need to extended AppFabric's UI too, maybe with a new IIS module
What do you think about?
Yes you can create an IIS Module and then show whatever you want in the UI. It isn't possible to extend the existing module | http://blogs.msdn.com/b/endpoint/archive/2010/06/09/tracking-wcf-data-services-with-windows-server-appfabric.aspx | CC-MAIN-2015-35 | refinedweb | 669 | 63.19 |
Back to index
#include "xdvi-config.h"
#include "xdvi.h"
#include "version.h"
#include <X11/Xatom.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xaw/Paned.h>
#include <X11/Xaw/Form.h>
#include <X11/Xaw/AsciiText.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include "message-window.h"
#include "util.h"
#include "x_util.h"
#include "string-utils.h"
#include "topic-window.h"
#include "help-window.h"
Go to the source code of this file.
Definition at line 72 of file help-window.c.
Definition at line 79 of file help-window.c.
{ Widget text; #if MOTIF Arg args[20]; int n = 0; XtSetArg(args[n], XmNeditable, False); n++; XtSetArg(args[n], XmNcursorPositionVisible, False); n++; XtSetArg(args[n], XmNvalue, value); n++; XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++; XtSetArg(args[n], XmNwordWrap, True); n++; XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++; /* XtSetArg(args[n], XmNtopWidget, top_widget); n++; */ /* XtSetArg(args[n], XmNtopOffset, 10); n++; */ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++; XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++; XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++; XtSetArg(args[n], XmNscrollingPolicy, XmAUTOMATIC); n++; XtSetArg(args[n], XmNscrollBarDisplayPolicy, XmAS_NEEDED); n++; text = XmCreateScrolledText(parent, (char *)name, args, n); XtManageChild(text); #else /* MOTIF */ text = XtVaCreateManagedWidget(name, asciiTextWidgetClass, parent, /* XtNfromVert, top_widget, */ /* XtNvertDistance, 10, */ XtNstring, value, XtNheight, 400, XtNwidth, 500, /* resizing of pane by user isn't needed */ XtNshowGrip, False, XtNscrollVertical, XawtextScrollAlways, XtNscrollHorizontal, XawtextScrollNever, XtNeditType, XawtextRead, XtNleftMargin, 5, NULL); XawTextDisplayCaret(text, False); #endif /* MOTIF */ return text; }
Definition at line 124 of file help-window.c.
{ char *tmp = xmalloc(len + 1); char *ptr; memcpy(tmp, str, len); tmp[len] = '\0'; if ((ptr = strchr(tmp, '\t')) == NULL) { XDVI_WARNING((stderr, "Help resource label `%s' doesn't contain a tab character - ignoring it.", tmp)); *title = tmp; *summary = NULL; } else { *ptr++ = '\0'; *title = tmp; *summary = ptr; } TRACE_GUI((stderr, "Title, Summary: |%s|%s|", *title, *summary)); }
Definition at line 147 of file help-window.c.
{ const char *ptr = NULL; char *widget_text = NULL; Widget help_form; Widget text; struct topic_item *item = &(info->items[idx]); char *translation_str = get_string_va("#override \n" "<Key>q:close-topic-window(%p)\n" #ifdef MOTIF "<Key>osfCancel:close-topic-window(%p)\n" #else "<Key>Escape:close-topic-window(%p)\n" #endif "<Key>Return:close-topic-window(%p)", info, info, info); if (resource != NULL) { if ((ptr = strchr(resource, '\n')) == NULL) { XDVI_WARNING((stderr, "Help resource text `%s' doesn't contain a newline character.", resource)); ptr = resource; } else ptr++; get_title_and_summary(resource, ptr - resource - 1, &(item->topic), &(item->title)); } else { /* resource not set; copy resource_default into malloc()ed widget_text: */ size_t size = 0, alloc_len = 0, offset; const size_t alloc_step = 1024; int i; for (i = 0; resource_default[i] != NULL; i++) { if (i == 0) { /* special case */ get_title_and_summary(resource_default[i], strlen(resource_default[i]) - 1, &(item->topic), &(item->title)); } else { offset = size; size += strlen(resource_default[i]); /* * allocate chunks of `alloc_step' to avoid frequent calls to malloc. * `alloc_len' is always 1 more than `size', for the terminating NULL character. */ while (size + 1 > alloc_len) { alloc_len += alloc_step; widget_text = xrealloc(widget_text, alloc_len); } memcpy(widget_text + offset, resource_default[i], size - offset); } } /* null-terminate string */ widget_text[size] = '\0'; } help_form = XtVaCreateManagedWidget("help_form", #if MOTIF xmFormWidgetClass, info->right_form, XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, XmNbottomAttachment, XmATTACH_FORM, #else formWidgetClass, info->right_form, XtNborderWidth, 0, XtNdefaultDistance, 0, #endif NULL); item->widget = help_form; if (ptr != NULL) { text = create_help_text(help_form, "help_text", ptr); } else { text = create_help_text(help_form, "help_text", widget_text); free(widget_text); } XtOverrideTranslations(text, XtParseTranslationTable(translation_str)); free(translation_str); #if !MOTIF { Dimension w; XtVaGetValues(text, XtNwidth, &w, NULL); if (w > *width) *width = w; } #else UNUSED(width); #endif }
Definition at line 239 of file help-window.c.
{ size_t k; Dimension width; /* * Define fallbacks: default_xyz is used as fallback text if * X resource xyz isn't specified. * * We use arrays of strings rather than simple strings because of C's * limitations on maximum string length; but since the resource needs to * be a simple `char *', these have to be copied into larger buffers * later on (which is a bit wasteful to space). OTOH, splitting the * strings into smaller pieces would make them hard to deal with as * X resources. They are defined as static so that they are initialized * only once. * * Last elem of each array is NULL for ease of looping through it. * * Advantages of this method vs. putting the help texts into a file: * - couldn't use #ifdef's as easily * - would need to invent our own file format * - file searching is more error-prone (needs to be installed etc.) */ static const char *default_help_general[] = { "Introduction\tAbout this version of xdvi\n", "This is xdvik, version ", XDVI_TERSE_VERSION_INFO ".\nThe program's homepage is located at:\n", "\n", "where you can find updates, report bugs and submit feature requests.\n", "\n", "\n", "Xdvi has many command-line options, too numerous to be listed here;\n", "see the man page for a full description.\n", "\n", "The most important key bindings are listed in the help sections shown\n", "in the left window.\n", "\n", "Note: Unless a key binding also has an uppercase version,\n", "all bindings are case-insensitive.\n\n", "\n", "The major parts of Xdvik are licensed under the X Consortium license.\n", "Parts (encoding.c) are licensed under the GNU General Public License.\n", "Xdvik uses the following libraries:\n", "- The kpathsea library, licensed in part under the GNU General Public\n", " License, in part under the GNU Library General Public License.\n", "- t1lib, licensed in parts under the GNU Library General Public License,\n", " in parts under the X Consortium license.\n", "There is NO WARRANTY of anything.\n", "\n", "Built on ", __DATE__, " using these configure options:\n", #if MOTIF "- Motif toolkit (", XmVERSION_STRING, ")\n", #else "- Athena toolkit\n", #endif #ifdef A4 "- paper: a4, units cm\n", #else "- paper: letter, units inches\n", #endif #ifdef GREY "- anti-aliasing (grey) enabled\n", #endif #ifdef T1LIB "- T1lib (direct rendering of PS fonts) enabled\n", #endif #if HAVE_ICONV_H "- Iconv support compiled in\n", #if USE_LANGINFO "- Langinfo support compiled in\n", #else "- Langinfo support not compiled in\n", #endif #else "- Iconv/langinfo support not compiled in\n", #endif #ifdef TEXXET "- left-to-right typesetting (TeXXeT) support enabled\n", #endif #ifdef USE_GF "- gf file support enabled\n", #endif #if HAVE_MISSING_FEATURES "\n", "Features not available on this platform:\n", #if !XDVI_XT_TIMER_HACK "- Could not redefine XtAppAddTimeOut(); some widgets may\n", " not be updated until the mouse is moved.\n", #endif #if !HAVE_REGEX_H "- regex.h header not available, regular expression support\n", " in string search is disabled.\n", #endif #endif /* HAVE_MISSING_FEATURES */ NULL }; static const char *default_help_hypertex[] = { "Hyperlinks\tNavigating links\n", "Whenever the mouse is positioned on a link, the cursor changes\n", "to a `hand' shape and the target of the link is displayed\n", "in the statusline at the bottom of the window.\n", "\n", "The following keybindings are pre-configured:\n", "\n", "Mouse-1\n", " Follow the link at the cursor position.\n", " If the link target is not a DVI file, try to launch\n", " an application to view the file.\n", "Mouse-2\n", " Open a new xdvi window displaying the link\n", " at the cursor position if the link is a DVI file;\n", " else, try to launch an application to view the file.\n", "B", #if MOTIF ", toolbar button 9\n", #else "\n", #endif " Go back to the previous hyperlink in the history.\n", "F", #if MOTIF ", toolbar button 10\n", #else "\n", #endif " Go forward to the next hyperlink in the history.\n", "\n", "By default, the hyperlinks are displayed in the colors \n", "`linkColor' and `visitedLinkColor' (for visited links) and \n", "underlined in the same colors. This can be customized \n", "by setting the resource or command-line option `linkstyle' \n", "to a value between 0 and 3, which have the following meaning:\n", " 0: no highlighting of links,\n", " 1: underline links,\n", " 2: color links,\n", " 3: color and underline links.\n\n", NULL }; static const char *default_help_othercommands[] = { "Other Commands\tMiscellaneous other commands\n", "Ctrl-f\n", " Opens a dialog window to search for a text string\n", " in the DVI file.\n", "\n", "Ctrl-g\n", " Search for the next string match.\n", "\n", "Ctrl-l\n", " Toggles fullscreen mode (which may not work with your\n", " window manager/desktop).\n", "\n", "Ctrl-o", #if MOTIF ", toolbar button 1\n", #else "\n", #endif " Opens a popup window to select another DVI file.\n", " With a prefix argument `n', the `n'th file from the file history\n", " is opened instead.\n", "\n", "Ctrl-p", #if MOTIF ", toolbar button 11\n", #else "\n", #endif " Opens a popup window for printing the DVI file, or parts of it.\n", "\n", "Ctrl-r or Clear\n", " Redisplays the current page.\n", "\n", "Ctrl-s\n", " Opens a popup window for saving the DVI file, or parts of it.\n", "\n", "G\n", " Toggles the use of greyscale anti-aliasing for\n", " displaying shrunken bitmaps. In addition, the key\n", " sequences `0G' and `1G' clear and set this flag,\n", " respectively. See also the -nogrey option.\n", "\n", "k\n", " Normally when xdvi switches pages, it moves to the home\n", " position as well. The `k' keystroke toggles a `keep-\n", " position' flag which, when set, will keep the same\n", " position when moving between pages. Also `0k' and `1k'\n", " clear and set this flag, respectively. See also the\n", " -keep option.\n", "\n", "M\n", " Sets the margins so that the point currently under the\n", " cursor is the upper left-hand corner of the text in the\n", " page. Note that this command itself does not move the\n", " image at all. For details on how the margins are used,\n", " see the -margins option.\n", "\n", "P\n", " ``This is page number n.'' This can be used to make\n", " the `g' keystroke refer to a different page number.\n", " (See also `Options->Use TeX Page Numbers' and the\n", " `T' keystroke).\n", "\n", "R", #if MOTIF ", toolbar button 2\n", #else "\n", #endif " Forces the DVI file to be reread.\n", "\n", "s\n", " Changes the shrink factor to the given number.\n", " If no number is given, the smallest factor that makes the\n", " entire page fit in the window will be used. (Margins\n", " are ignored in this computation.)\n", "\n", "S\n", " Sets the density factor to be used when shrinking\n", " bitmaps. This should be a number between 0 and 100;\n", " higher numbers produce lighter characters.\n", "\n", "t\n", " Switches to the next unit in a sorted list of TeX dimension\n", " units for the popup magnifier ruler and `Ruler mode' (see the\n", " section `Modes').\n" "\n", "V\n", " Toggles Ghostscript anti-aliasing. Also `0V' and `1V' clear\n", " and enables this mode, respectively. See also the the\n", " -gsalpha option.\n", "\n", "\n", "v\n", " Toggles between several modes of displaying postscript specials:\n", " Display specials, display specials with their bounding box\n", " (if available), and display bounding boxes only (if available).\n", " The prefix arguments 1, 2 and 0 also allow you to select one of\n" " these states directly.\n", "\n", "x\n", " Toggles expert mode (in which ", #if MOTIF "the menu bar, the toolbar\n", #else "the menu buttons,\n", #endif " the page list and the statusline do not appear).\n", " `1x' toggles the display of the statusline at the bottom of the window.\n", " `2x' toggles the scrollbars,\n", #if MOTIF " `3x' toggles the page list,\n", " `4x' toggles the toolbar,\n", " `5x' toggles the menu bar.\n", #else " `3x' toggles the page list and menu buttons.\n", #endif "\n", "Ctrl-+", #if MOTIF ", toolbar button 7\n", #else "\n", #endif " Makes the display of the page larger (zooms in).\n", "\n", "Ctrl-+", #if MOTIF ", toolbar button 8\n", #else "\n", #endif " Makes the display of the page smaller (zooms out).\n", "\n", "Alt-Ctrl-+", #if MOTIF ", toolbar button 16\n", #else "\n", #endif " Makes the fonts darker (by adding to the gamma value).\n", "\n", "Alt-Ctrl--", #if MOTIF ", toolbar button 17\n", #else "\n", #endif " Makes the fonts lighter (by substracting from the gamma\n", " value).\n", "\n", NULL }; static const char *default_help_marking[] = { "Printing and Saving\tMarking, printing and saving pages\n", "The `Save' and `Print' dialogs allow you to save or print all,\n", "pages, a range of pages, or all marked pages from a DVI file.\n", "\n", "Note that the page numbers for the `From ... to ...' range\n", "refer to physical pages, not TeX pages (compare the option\n", "`Use TeX Page Numbers' and the `T' keystroke).\n", "\n", "To mark a page or a range of pages, use one of the folllowing\n", "methods:\n", "- Click on the page in the page list with Mouse Button 2 to mark\n", " a single page, or drag the mouse while holding down Button 2\n", " to mark a range of pages.\n", "- Use one of the following key combinations:\n", " m: toggle the mark of the current page,\n", " 1m toggle the marks of all odd pages,\n", " 2m toggle the marks of all even pages,\n", " 0m: unmark all pages,\n", " Ctrl-n: toggle mark of current page, then move one page forward,\n", " Ctrl-u: move one page back, then toggle mark of that page.\n", #if MOTIF "- Use one of the toobar buttons 12 to 15 to toggle the marks\n", " of odd pages, toggle the marks of even pages, toggle the mark\n", " of the current page, or unmark all pages, respectively.\n", #endif "\n", "If the X resource or command line option `paper' has been used,\n", "its value is inserted into the `Dvips Options' field of the printing\n", "dialog so that the appropriate options can be passed to dvips.\n", "This doesn't happen if the paper size has been specified explicitly\n", "in the DVI file (e.g. by using the LaTeX `geometry' package).\n", "Note that not all of the paper options used by xdvi\n", "may be understood by dvips; dvips will ignore the option\n", "in that case, and will use its default paper setting.\n", NULL }; static const char *default_help_pagemotion[] = { "Page Motion\tMoving around in the document\n", "\n", "[\n", " Moves back one item in the page history. With a prefix\n", " argument n, move back n history items.\n" "\n", "]\n", " Moves forward one item in the page history. With a prefix\n", " argument n, move forward n history items.\n" "\n", "Ctr-[\n", " Deletes current item in the page history and move\n", " to the history item before the deleted one. With a prefix\n", " argument n, delete n previous history items.\n", "\n", "Ctr-]\n", " Deletes current item in the page history and move\n", " to the history item after the deleted one. With a prefix\n", " argument n, delete n next history items.\n", "\n", "n or f or Space or Return or LineFeed or PgDn", #if MOTIF ", toolbar button 5\n", #else "\n", #endif " Moves to the next page (or to the nth next page if a\n", " number is given).\n", "\n", "p or b or Ctrl-h or BackSpace or Del or PgUp", #if MOTIF ", toolbar button 4\n", #else "\n", #endif " Moves to the previous page (or back n pages).\n", "\n", "Up-arrow\n", " Scrolls page up.\n", "\n", "Down-arrow\n", " Scrolls page down.\n", "u\n", " Moves page up two thirds of a window-full.\n", "\n", "d\n", " Moves page down two thirds of a window-full.\n", "\n", "Left-arrow\n", " Scrolls page left.\n", "\n", "Right-arrow\n", " Scrolls page right.\n", "\n", "l\n", " Moves page left two thirds of a window-full.\n", "\n", "r\n", " Moves page right two thirds of a window-full.\n", "\n", "T\n", " Toggle the use of TeX page numbers instead of physical\n", " pages for the page list and the `g' command.\n", " (See also the `Options -> Use TeX Pages' menu.)\n", "\n", "g\n", " Moves to the page with the given number. Initially,\n", " the first page is assumed to be page number 1, but this\n", " can be changed with the `P' keystroke, described in the\n", " section `Other Commands'. If no page number is given,\n", " it moves to the last page.\n", "\n", "<, Ctrl-Home", #if MOTIF ", toolbar button 3\n", #else "\n", #endif " Moves to first page in the document.\n", "\n", ">, Ctrl-End", #if MOTIF ", toolbar button 6\n", #else "\n", #endif " Moves to last page in the document.\n", "\n", "^\n", " Move to the ``home'' position of the page. This is\n", " normally the upper left-hand corner of the page,\n", " depending on the margins set via the -margins option.\n", "\n", "Home\n", " Move to the ``home'' position of the page (the upper\n", " left-hand corner), or to the top of the page if the `keep'\n", " flag is set.\n", "\n", "End\n", " Move to the end position of the page (the lower\n", " right-hand corner), or to the bottom of the page if the\n", " `keep' flag is set.\n", "\n", "c\n", " Moves the page so that the point currently beneath the\n", " cursor is moved to the middle of the window. It also\n", " warps the cursor to the same place.\n", "\n", NULL }; static const char *default_help_mousebuttons[] = { "Mouse Buttons\tActions bound to the mouse buttons\n", "The mouse buttons can be customized just like the keys;\n", "however the bindings cannot be intermixed (since\n", "a mouse event always requires the cursor location\n", "to be present, which a key event doesn't).\n", "The default bindings are as follows:\n" "\n", "Buttons 1-3\n", " Pops up magnifier windows of different sizes.\n", " When the mouse is over a hyperlink, the link overrides\n", " the magnifier. In that case, Button 1 jumps to the link\n", " in the current xdvi window, Button 2 opens the link target\n", " in a new instance of xdvi.\n", " In `Ruler Mode', Button1 shows/drags the ruler instead;\n", " in `Text Selection Mode', Button1 can be used to select\n", " a rectangular region of text from the DVI file.\n", "\n", "Shift-Button1 to Shift-Button3\n", " Drag the page in each direction (Button 1), vertically\n", " only (Button 2) or horizontally only (Button 3).\n", "\n", "Ctrl-Button1\n", " Invoke a reverse search for the text on the cursor\n", " location (see the section SOURCE SPECIALS for more\n", " information on this).\n", "\n", "The buttons 4 and 5 (wheel up and down for wheel mice)\n", "scroll the page up and down respectively, or jump to the\n", "next/previous page when the mouse is over the page list.", "\n", "In the page list, Button 2 toggles the mark a page (see\n", "section `Marking Pages'); moving the mouse while holding\n", "Button 2 lets you toggle a range of pages.\n", "\n", NULL }; static const char *default_help_sourcespecials[] = { "Source Specials\tNavigating between the TeX and the DVI file\n", "Some TeX implementations have an option to automatically\n", "include so-called `source specials' into a DVI file. These\n", "contain the line number and the filename of the TeX source\n", "and make it possible to go from a DVI file to the\n", "(roughly) corresponding place in the TeX source and back\n", "(this is also called `reverse search' and `forward search').\n", "\n", "On the TeX side, you need a TeX version that supports the `-src'\n", "option (e.g. teTeX >= 2.0) or a macro package like srcltx.sty\n", "to insert the specials into the DVI file.\n", "\n", "Source special mode can be customized for various editors\n", "by using the command line option \"-editor\" or one of the\n", "environment variables \"XEDITOR\", \"VISUAL\" or \"EDITOR\".\n", "See the xdvi man page on the \"-editor\" option for details\n", "and examples.\n", "\n", "Forward search can be performed by a program (i.e. your editor)\n", "invoking xdvi with the \"-sourceposition\" option like this:\n", "xdvi -sourceposition \"<line> <filename>\" <main file>\n", "If there is already an instance of xdvi running that displays\n", "<main file>, it will try to open the page specified by\n", "<line> and <filename> an highlight this location on the page.\n", "Else, a new instance of xdvi will be started that will try to\n", "do the same.\n", "\n", "The following keybindings are pre-configured:\n", "\n", "Ctrl-Mouse1\n", " [source-special()] Invoke the editor (the value\n", " of the \"editor\" resource ) to display the line in the\n", " TeX file corresponding to special at cursor position.\n", "\n", "Ctrl-v\n", " [show-source-specials()] Show bounding boxes for every\n", " source special on the current page, and print the strings\n", " contained in these specials to stderr. With prefix 1,\n", " show every bounding box on the page (for debugging purposes).\n", "\n", "Ctrl-x\n", " [source-what-special()] Display information about the\n", " source special next to the cursor, similar to\n", " \"source-special()\", but without actually invoking\n", " the editor (for debugging purposes).\n", "\n", NULL }; static const char *default_help_modes[] = { "Mouse Modes\tMagnifier Mode, Ruler Mode and Text Selection Mode\n", "The keystroke Ctrl-m [switch-mode()] switches between\n", "three different bindings for Mouse-1, which can also be\n", "activated via the Modes menu (in Motif, this is a submenu\n", "of the Options menu). The default mode at startup can be\n", "customized via the X resource `mouseMode' or the command-line\n", "option `-mousemode'. The default startup mode is Magnifier Mode.\n", "\n", "Note: The modes are activated by changing the magnifier()\n", "action. Switching the mode will not work if Mouse-1 has\n", "been customized to an action sequence that does not contain\n", "the magnifier() action.\n", "\n", "Magnifier Mode\n", "\n", " In this mode, the mouse buttons 1 to 5 will pop up a\n", " ``magnifying glass'' that shows an unshrunken image of\n", " the page (i.e. an image at the resolution determined by\n", " the option/X resource pixels or mfmode) at varying sizes.\n", " When the magnifier is moved, small ruler-like tick marks\n", " are displayed at the edges of the magnifier (unless\n", " the X resource delayRulers is set to false, in which case\n", " the tick marks are always displayed).\n", "\n", " The unit of the marks is determined by the X resource\n", " `tickUnits' (mm by default). This unit can be changed at\n", " runtime via the action `switch-magnifier-units()', by\n", " default bound to the keystroke `t' (see the description\n", " of that key, and of `switch-magnifier-units()' for more\n", " details on the units available). The length of the tick\n", " marks can be changed via the X resource `tickLength'\n", " (4 by default). A zero or negative value suppresses the\n", " tick marks.\n", "\n", "\n", "Text Selection Mode\n", "\n", " This mode allows you to select a rectangular region of\n", " text in the DVI file by holding down Mouse-1 and moving\n", " the mouse. The text is put into the X primary selection\n", " so that it can be pasted into other X applications with\n", " Mouse-2.\n", "\n", " If xdvi has been compiled with locale, nl_langinfo() and\n", " iconv support, the selected text is converted into the\n", " character set of the current locale (see the output of\n", " `locale -a' for a list of locale settings available on\n", " your system). If nl_langinfo() is not available, but\n", " iconv is, you can specify the input encoding for iconv\n", " via the X resource `textEncoding' (see the output of\n", " `iconv -l' for a list of valid encodings). If iconv support\n", " is not available, only the encodings ISO-8859-1 and UTF-8\n", " are supported (these names are case-insensitive).\n", "\n", " Note that UTF-8 is the only encoding that can render all\n", " characters (e.g. mathematical symbols). If ISO-8859-1 is\n", " active, characters that cannot be displayed are replaced\n", " by `\' followed by the hexadecimal character code. If a\n", " character is not recognized at all, it is replaced by\n", " `?'. For other encodings, such characters may trigger\n", " iconv error messages.\n", "\n", " If you want to extract larger portions of text, you\n", " can also save selected pages or the entire file in\n", " text format from the `File > Save as ...' menu.\n", "\n", "\n", "Ruler Mode\n", "\n", " This mode provides a simple way of measuring distances\n", " on the page. When this mode is activated, the mouse\n", " cursor changes into a thin cross, and a larger, cross-\n", " shaped ruler is drawn in the highlight color at the\n", " mouse location. The ruler doesn't have units attached\n", " to it; instead, the current distance between the ruler\n", " and the mouse cursor is continously printed to the\n", " statusline.\n", "\n", " When activating Ruler Mode, the ruler is at first\n", " attached to the mouse and can be moved around. It can\n", " then be positioned at a fixed place by clicking Mouse-1.\n", " After that, the mouse cursor can be moved to measure the\n", " horizontal (dx), vertical (dy) and direct (shortest)\n", " (dr) distance between the ruler center point and the\n", " mouse.\n", "\n", " Clicking Mouse-1 again will move the ruler to the\n", " current mouse position, and holding down Mouse-1 will\n", " drag the ruler around.\n", "\n", " In Ruler Mode, the following special keybindings extend\n", " or replace the default bindings:\n", "\n", " o [ruler-snap-origin()] Snap the ruler back to\n", " the origin coordinate (0,0).\n", "\n", " t [overrides switch-magnifier-units()] Toggle\n", " between various ruler units, which can be\n", " specified by the X resource tickUnits (`mm'\n", " by default).\n", "\n", " P [overrides declare-page-number()] Print the\n", " distances shown in the statusline to standard\n", " output.\n", NULL }; static const char *default_help_search[] = { "String Search\tSearching for strings in the DVI file\n", "The keystroke Ctrl-f or the menu entry File->Find ...\n", "opens a dialog window to search for a text string or a\n", "regular expression in the DVI file. The keystroke Ctrl-g\n", "jumps to the next match.\n", #ifdef MOTIF "(With Motif, you can also click on the `Binoculars' symbol\n", "in the toolbar.)\n", #endif "\n", #if HAVE_ICONV_H #if USE_LANGINFO "The search term is converted from the character set specified\n", "by the current locale into UTF-8. (See the output of `locale -a'\n", "for a list of locale settings available on your system).\n", #else /* USE_LANGINFO */ "Since langinfo() support is not available on this platform,\n", "the character set of the search string should be specified\n", "via the X resource/command-line option textEncoding if the\n", "encoding is different from iso_8859-1.\n", #endif /* USE_LANGINFO */ #else /* HAVE_ICONV_H */ "Since iconv() support is not available on this platform,\n", "the search term should be a string in the encoding specified\n", "by the X resource/command-line option textEncoding;\n", "currently, only the values iso_8859-1 and utf-8 are suported.\n", #endif "Internally, the text in the DVI file is represented in\n", "UTF-8 encoding (you can view the text by saving the DVI\n", "file to a text file in UTF-8 encoding via the `File -> Save As ...'\n", "dialog).\n", "\n", "Ideographic characters from CJKV fonts are treated specially:\n", "All white space (spaces and newlines) before and after such\n", "characters is ignored in the search string and in the DVI file.\n", "\n", "To match a newline character, use `\\n' in the search string;\n", "to match the string `\\n', use `\\\\n'.\n", "\n", "If the checkbox Regular Expression is activated, the\n", "string is teated as a regular expression in extended POSIX\n", "format, with the following properties:\n", "\n", " a? matches a zero or one times\n", "\n", " a* matches a zero or more times\n", "\n", " a+ matches a one or more times. Note that * and + are\n", " greedy, i.e. they match the longest possible\n", " sub string.\n", "\n", " a{n} matches a exactly n times\n", "\n", " a{n,m} matches a at least n and no more than m times\n", "\n", " a|b matches a or b. Brackets can be used for grouping,\n", " e.g.: (a|b)|c.\n", "\n", " The string matched by the nth group can be referenced\n", " by \\n, e.g. \\1 refers to the first match.\n", "\n", " The characters ^ and $ match the beginning and the end\n", " of a line, respectively.\n", "\n", " [abc] matches any of the letters a, b, c, and [a-z]\n", " matches all characters from a to z.\n", "\n", " The patterns . and [...] without an explicit newline\n", " don't match a newline character.\n", "\n", " Each item in a regular expression can also be one of\n", " the following POSIX character classes:\n", " [[:alnum:]] [[:alpha:]] [[:blank:]] [[:cntrl:]] [[:digit:]]\n", " [[:graph:]] [[:lower:]] [[:print:]] [[:space:]] [[:upper:]]\n", "\n", " These can be negated by inserting a ^ symbol after the\n", " first bracket: [^[:alpha:]]\n", "\n", " For more details on POSIX regular expressions, see\n", " e.g. the IEEE Std 1003.1 available online from:\n", "\n", "\n", "\n", " As a non-standard extension, the following Perl-like\n", " abbreviations can be used instead of the POSIX classes:\n", "\n", "\n", " Symbol Meaning POSIX Class\n", "\n", " \\w an alphanumeric character [[:alnum:]]\n", " \\W a non-alphanumeric character [^[:alnum:]]\n", " \\d a digit character [[:digit:]]\n", " \\D a non-digit character [^[:digit:]]\n", " \\s a whitespace character [[:space:]]\n", " \\S a non-whitespace character [^[:space:]]\n", "\n", " The following characters are special symbols; they\n", " need to be escaped with \\ in order to match them\n", " literally: ( ) [ ] . * ? + ^ $ \\.\n", "\n", "The dialog also provides checkboxes to search backwards,\n", "to match in a case-sensitive manner (the default is to\n", "ignore case, i.e. a search string Test will match both\n", "the strings test and TEST in the DVI file) and to ignore\n", "newlines and hyphens in the DVI file.\n", "\n", NULL }; k = width = 0; init_item(resource.help_general, default_help_general, info, k++, &width); init_item(resource.help_pagemotion, default_help_pagemotion, info, k++, &width); init_item(resource.help_othercommands, default_help_othercommands, info, k++, &width); init_item(resource.help_hypertex, default_help_hypertex, info, k++, &width); init_item(resource.help_mousebuttons, default_help_mousebuttons, info, k++, &width); init_item(resource.help_modes, default_help_modes, info, k++, &width); init_item(resource.help_search, default_help_search, info, k++, &width); init_item(resource.help_pagemotion, default_help_marking, info, k++, &width); init_item(resource.help_sourcespecials, default_help_sourcespecials, info, k++, &width); ASSERT(k < NUM_HELP_TOPICS, "Too many elements in help topics!"); /* NULL-terminate items info */ info->items[k].widget = 0; info->items[k].topic = info->items[k].title = NULL; /* adjust width of topics label to longest text */ #if !MOTIF XtVaSetValues(info->topic_label, XtNwidth, width, NULL); #endif }
Definition at line 1028 of file help-window.c.
{ size_t i; static Widget help_shell = 0; static struct topic_info info; static struct topic_item items[NUM_HELP_TOPICS]; static Boolean first_time = True; if (help_shell == 0) { /* called 1st time; create widget */ /* no special callbacks for OK/Cancel buttons */ info.ok_callback = NULL; info.cancel_callback = NULL; info.items = items; /* info.items_size = NUM_HELP_TOPICS; */ help_shell = create_topic_window(toplevel, "xdvik: Help", "help_window", &info, initialize_items, "Close", /* no Cancel button needed */ NULL); info.shell = help_shell; center_window(help_shell, globals.widgets.top_level); } #if MOTIF { /* check if resources are set properly */ Dimension w, h; XtVaGetValues(help_shell, XtNwidth, &w, XtNheight, &h, NULL); if (h < 200 || w < 400) { XDVI_WARNING((stderr, "Initial help window size too small (%dx%d); overriding size.\n" "Please check/update your application defaults file, and set both of\n" "`XDvi*help_text.rows' and `XDvi*help_text.columns' to a realistic value.", h, w)); XtVaSetValues(help_shell, XtNwidth, 620, XtNheight, 520, NULL); } } #endif XtPopup(help_shell, XtGrabNone); if (topic != NULL) { Boolean matched = False; for (i = 0; info.items[i].topic != NULL; i++) { if (strcmp(info.items[i].topic, topic) == 0) { /* match */ select_topic(&info, i); matched = True; } } if (!matched) { XBell(DISP, 0); popup_message(help_shell, MSG_WARN, NULL, "Shouldn't happen: Could not find topic `%s' in help list!\n" REPORT_XDVI_BUG_TEMPLATE, topic); } } else if (first_time) { first_time = False; select_topic(&info, 0); } } | https://sourcecodebrowser.com/tetex-bin/3.0/help-window_8c.html | CC-MAIN-2017-51 | refinedweb | 5,344 | 53.61 |
iOS Designer basics
This guide introduces the Xamarin Designer for iOS. It demonstrates how to use the iOS Designer to visually lay out controls, how to access those controls in code, and how to edit properties.
Warning
The iOS Designer will start to be phased out in Visual Studio 2019 version 16.8 and Visual Studio 2019 for Mac version 8.8. The recommended way to build iOS user interfaces is directly on a Mac running Xcode. For more information, see Designing user interfaces with Xcode.
The Xamarin Designer for iOS is a visual interface designer similar to Xcode's Interface Builder and the Android Designer. Some of its many features include seamless integration with Visual Studio for Windows and Mac, drag-and-drop editing, an interface for setting up event handlers, and the ability to render custom controls.
Requirements
The iOS Designer is available in Visual Studio for Mac and Visual Studio 2017 and later on Windows. In Visual Studio for Windows, the iOS Designer requires a connection to a properly configured Mac build host, though Xcode need not be running.
This guide assumes a familiarity with the contents covered in the Getting Started guides.
How the iOS Designer works
This section describes how the iOS Designer facilitates creating a user interface and connecting it to code.
The iOS Designer allows developers to visually design an application's user interface. As outlined in the Introduction to Storyboards guide, a storyboard describes the screens (view controllers) that make up an app, the interface elements (views) placed on those view controllers, and the app's overall navigation flow.
A view controller has two parts: a visual representation in the iOS Designer and an associated C# class:
In its default state, a view controller doesn't provide any functionality; it must be populated with controls. These controls are placed in the view controller's view, the rectangular area that contains all of the screen's content. Most view controllers contain common controls such as buttons, labels, and text fields, as illustrated in the following screenshot, which shows a view controller containing a button:
Some controls, such as labels containing static text, can be added to the view controller and left alone. However, more often than not, controls must be customized programmatically. For example, the button added above should do something when tapped, so an event handler must be added in code.
In order to access and manipulate the button in code, it must have a unique identifier. Provide a unique identifier by selecting the button, opening the Properties Pad, and setting its Name field to a value such as "SubmitButton":
Now that the button has a name, it can be accessed in code. But how does this work?
In the Solution Pad, navigating to ViewController.cs and clicking on the disclosure indicator reveals that the view controller's
ViewController class definition spans two files, each of which contains a partial class definition:
ViewController.cs should be populated with custom code related to the
ViewControllerclass. In this file, the
ViewControllerclass can respond to various iOS view controller lifecycle methods, customize the UI, and respond to user input such as button taps.
ViewController.designer.cs is a generated file, created by the iOS Designer to map the visually-constructed interface to code. Since changes to this file will be overwritten, it should not be modified. Property declarations in this file make it possible for code in the
ViewControllerclass to access, by Name, controls set up in the iOS Designer. Opening ViewController.designer.cs reveals the following code:
namespace Designer { [Register ("ViewController")] partial class ViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton SubmitButton { get; set; } void ReleaseDesignerOutlets () { if (SubmitButton != null) { SubmitButton.Dispose (); SubmitButton = null; } } } }
The
SubmitButton property declaration connects the entire
ViewController class - not just the ViewController.designer.cs file – to the button defined in the storyboard. Since ViewController.cs defines part of the
ViewController class, it has access to
SubmitButton.
The following screenshot illustrates that IntelliSense now recognizes the
SubmitButton reference in ViewController.cs:
This section has demonstrated how create a button in the iOS Designer and access that button in code.
The remainder of this document provides a further overview of the iOS Designer.
iOS Designer basics
This section introduces the parts of the iOS Designer and provides a tour of its features.
Launching the iOS Designer
Xamarin.iOS projects created with Visual Studio for Mac include a storyboard. To view the contents of a storyboard, double-click the .storyboard file in the Solution Pad:
iOS Designer features
The iOS Designer has six primary sections:
- Design Surface – The iOS Designer's primary workspace. Shown in the document area, it enables the visual construction of user interfaces.
- Constraints Toolbar – Allows for switching between frame editing mode and constraint editing mode, two different ways to position elements in a user interface.
- Toolbox – Lists the controllers, objects, controls, data views, gesture recognizers, windows, and bars that can be dragged onto the design surface and added to a user interface.
- Properties Pad – Shows properties for the selected control, including identity, visual styles, accessibility, layout, and behavior.
- Document Outline – Shows the tree of controls that compose the layout for the interface being edited. Clicking on an item in the tree selects it in the iOS Designer and shows its properties in the Properties Pad. This is handy for selecting a specific control in a deeply-nested user interface.
- Bottom Toolbar – Contains options for changing how the iOS Designer displays the .storyboard or .xib file, including device, orientation, and zoom.
Design workflow
Adding a control to the interface
To add a control to an interface, drag it from the Toolbox and drop it on the design surface. When adding or positioning a control, vertical and horizontal guidelines highlight commonly-used layout positions such as vertical center, horizontal center, and margins:
The blue dotted line in the example above provides a horizontal center visual alignment guideline to help with the button placement.
Context menu commands
A context menu is available both on the design surface and in the Document Outline. This menu provides commands for the selected control and its parent, which is helpful when working with views in a nested hierarchy:
Constraints toolbar
The constraints toolbar has been updated and now consists of two controls: the frame editing mode / constraint editing mode toggle and the update constraints / update frames button.
Frame editing mode / constraint editing mode toggle
In previous versions of the iOS Designer, clicking an already-selected view on the design surface toggled between frame editing mode and constraint editing mode. Now, a toggle control in the constraints toolbar switches between these editing modes.
- Frame editing mode:
- Constraint editing mode:
Update constraints / update frames button
The update constraints / update frames button sits to the right of the frame editing mode / constraint editing mode toggle.
- In frame editing mode, clicking this button adjusts the frames of any selected elements to match their constraints.
- In constraint editing mode, clicking this button adjusts the constraints of any selected elements to match their frames.
Bottom toolbar
The bottom toolbar provides a way to select the device, orientation, and zoom used to view a storyboard or .xib file in the iOS Designer:
Device and orientation
When expanded, the bottom toolbar displays all devices, orientations, and/or adaptations applicable to the current document. Clicking them changes the view displayed on the design surface.
Note that selecting a device and orientation changes only how the iOS Designer previews the design. Regardless of the current selection, newly added constraints are applied across all devices and orientations unless the Edit Traits button has been used to specify otherwise.
When size classes are enabled, the Edit Traits button will appear in the expanded bottom toolbar. Clicking the Edit Traits button displays options for creating an interface variation based on the size class represented by the selected device and orientation. Consider the following examples:
- If iPhone SE / Portrait, is selected, the popover will provide options to create an interface variation for the compact width, regular height size class.
- If iPad Pro 9.7" / Landscape / Full Screen is selected, the popover will provide options to create an interface variation for the regular width, regular height size class.
Zoom controls
The design surface supports zooming via several controls:
The controls include the following:
- Zoom to fit
- Zoom out
- Zoom in
- Actual size (1:1 pixel size)
These controls adjust the zoom on the design surface. They do not affect the user interface of the application at runtime.
Properties Pad
Use the Properties Pad to edit the identity, visual styles, accessibility, and behavior of a control. The following screenshot illustrates the Properties Pad options for a button:
Properties Pad sections
The Properties Pad contains three sections:
- Widget – The main properties of the control, such as name, class, style properties, etc. Properties for managing the control’s content are usually placed here.
- Layout – Properties that keep track of the position and size of the control, including constraints and frames, are listed here.
- Events – Events and event handlers are specified here. Useful for handling events such as touch, tap, drag, etc. Events can also be handled directly in code.
Editing properties in the Properties Pad
In addition to visual editing on the design surface, the iOS Designer supports editing properties in the Properties Pad. The available properties change based on the selected control, as illustrated by the screenshots below:
Important
The Identity section of the Properties Pad now shows a Module field. It is necessary to fill in this section only when interoperating with Swift classes. Use it to enter a module name for Swift classes, which are namespaced.
Default values
Many properties in the Properties Pad show no value or a default value. However, the application's code may still modify these values. The Properties Pad does not show values set in code.
Event handlers
To specify custom event handlers for various events, use the Events tab of the Properties Pad. For example, in the screenshot below, a
HandleClick method handles the button's Touch Up Inside event:
Once an event handler has been specified, a method of the same name must be added to the corresponding view controller class. Otherwise, an
unrecognized selector exception will occur when the button is tapped:
Note that after an event handler has been specified in the Properties Pad, the iOS Designer will immediately open the corresponding code file and offer to insert the method declaration.
For an example that uses custom event handlers, refer to the Hello, iOS Getting Started Guide.
Outline view
The iOS Designer can also display an interface's hierarchy of controls as an outline. The outline is available by selecting the Document Outline tab, as shown below:
The selected control in the outline view stays in sync with the selected control on the design surface. This feature is useful for selecting an item from a deeply nested interface hierarchy.
Revert to Xcode
It is possible to use the iOS Designer and Xcode Interface Builder interchangeably. To open a storyboard or a .xib file in Xcode Interface Builder, right-click on the file and select Open With > Xcode Interface Builder, as illustrated by the screenshot below:
After making edits in Xcode Interface Builder, save the file and return to Visual Studio for Mac. The changes will sync to the Xamarin.iOS project.
.xib support
The iOS Designer supports creating, editing, and managing .xib files. These are XML files that respresent single, custom views which can be added to an application's view hierarchy. A .xib file generally represents the interface for a single view or screen in an application, whereas a storyboard represents many screens and the transitions between them.
There are many opinions about which solution – .xib files, storyboards, or code – works best for creating and maintaining a user interface. In reality, there is no perfect solution, and it's always worth considering the best tool for the job at hand. That said, .xib files are generally most powerful when used to represent a custom view needed in multiple places in an app, such as a custom table view cell.
More documentation about using .xib files can be found in the following recipes:
- Using the View .xib Template
- Creating a Custom TableViewCell using a .xib
- Creating a Launch Screen using a .xib
For more information regarding the use of storyboards, refer to the Introduction to Storyboards.
This and other iOS Designer-related guides refer to the use of storyboards as the standard approach for building user interfaces, since most Xamarin.iOS new project templates provide a storyboard by default.
Summary
This guide provided an introduction to the iOS Designer, describing its features and outlining the tools it offers for designing beautiful user interfaces. | https://docs.microsoft.com/en-us/xamarin/ios/user-interface/designer/introduction | CC-MAIN-2021-10 | refinedweb | 2,122 | 52.6 |
What’s in a callback
So we left it where we could post new tweets but then had to manually refresh the page to see the tweet we’d just added.
The last piece of our React puzzle is to update the user interface (list of tweets) automatically when a new one is posted.
React employs a handy concept called callbacks for exactly this kind of requirement.
We can modify
PostNew to invoke a callback when we’ve finished saving the new tweet. We can then react to this callback in List.js and trigger a refresh of the tweets from our API.
Head over to
PostNew.js and update your
handleSubmit handler to look like this:
async handleSubmit(event) { event.preventDefault(); const options = { method: 'POST', body: JSON.stringify(this.state), headers: { 'Content-Type': 'application/json' } }; await fetch('Tweet', options); this.props.onPosted(); }
The only change here is the last line, where we make a call to
this.props.onPosted().
This will invoke whatever function is passed in to our component via
onPosted so let’s go pass something in!
Head over to
List.js.
Now we can pass in a handler for
onPosted and make our
List component run our tweets query again, and update itself accordingly…
First up you’ll want to find the
<PostNew /> line and update it as follows:
<PostNew onPosted={this.handleNewTweet}/>
Then you’ll need to update the rest of the component to look like this…
import React from 'react'; import Tweet from './Tweet' import PostNew from "./PostNew"; export default class List extends React.Component { state = { tweets: [] }; constructor(props){ super(props); this.handleNewTweet = this.handleNewTweet.bind(this); } async componentDidMount() { this.fetchData(); } async fetchData(){ const response = await fetch('Tweet'); const data = await response.json(); this.setState({tweets: data.tweets}); } async handleNewTweet(){ this.fetchData(); } render() { return ( <> <h3>Tweets</h3> <PostNew onPosted={this.handleNewTweet}/> {this.state.tweets.map(tweet => <Tweet text={tweet}/>)} </> ); } }
I’ve extracted the little bit of code needed to retrieve our list of tweets into its own
fetchData method. This way we can still call it from
onComponentDidMount but also call it any other time we need to.
Then I’ve added a function called
handleNewTweet and made sure it also calls
fetchData. It’s this
handleNewTweet function that will be invoked every time we post a new tweet.
And of course, I ran into the javascript
this problem again, so I’ve added a constructor to make sure
handleNewTweet has access to the component via
this and can call
this.fetchData().
And there it is, post a new tweet and the list automatically refreshes accordingly.
Separation of concerns FTW
Now you have a really clean way to model your application as a serious of queries and commands.
I’ve used this approach on several large projects and the good news is this scales; so no matter how complex or large your application becomes, you can nearly always break it down into a number of commands and queries, modelling them as we’ve done here.
The basic rule of thumb is to avoid mixing the two (queries which retrieve data, and commands which change data in some way) so when you’re adding new features try to be clear whether you’re just retrieving data to show in the UI, or actually making a change to the data.
If you are making a change, you’ll typically execute a query (as we did here) to “refresh” the data once you know its changed.
Remember these are the three core concepts in React.js…
- State
- Props
- Callbacks
These are the building blocks of all React.js applications.
State represents the current state of any given component. Changes to that component (entering values in form fields etc) will update that state, and the UI itself can react based on changes to the state.
Props are used to pass information to other components. These components can then render that information, react to it and take further actions when that property changes.
Callbacks are useful for signaling “back up” the component tree, to tell something higher up that something interesting has happened. Components higher up the component tree can handle these callbacks, perform whatever actions they need, then push data back down into their child components (using props).
This is why people talk about state “moving in one direction” with React.js.
The state comes in at one level (our
List component), is pushed down into other components (often via Props), who subsequently raise callbacks which go back up the tree to any components who are registered to handle it.
These components then do something (like refreshing the data from a server) and can push state back down the component tree again.
Next Steps. | https://jonhilton.net/react/summing-up/ | CC-MAIN-2022-05 | refinedweb | 786 | 62.78 |
Model Binding To A List
Download the sample project to play with the code as you read this blog post.
Using the
DefaultModelBinder in ASP.NET MVC, you can bind submitted
form values to arguments of an action method. But what if that argument
is a collection? Can you bind a posted form to an
ICollection<T>?
Sure thing! It’s really easy if you’re posting a bunch of primitive types. For example, suppose you have the following action method.
public ActionResult UpdateInts(ICollection<int> ints) { return View(ints); }
You can bind to that by simply submitting a bunch of form fields each having the same name. For example, here’s an example of a form that would bind to this, assuming you keep each value a proper integer.
<form method="post" action="/Home/UpdateInts"> <input type="text" name="ints" value="1" /> <input type="text" name="ints" value="4" /> <input type="text" name="ints" value="2" /> <input type="text" name="ints" value="8" /> <input type="submit" /> </form>
If you were to take fiddler and look at what data actually gets posted when clicking the submit button, you’d see the following.
ints=1&ints=4&ints=2&ints=8
The default model binder sees all these name/value pairs with the same
name and converts that to a collection with the key ints, which is
then matched up with the
ints parameter to your action method. Pretty
simple!
Where it gets trickier is when you want to post a list of complex types. Suppose you have the following class and action method.
public class Book { public string Title { get; set; } public string Author { get; set; } public DateTime DatePublished { get; set; } } //Action method on HomeController public ActionResult UpdateProducts(ICollection<Book> books) { return View(books); }
You might think we could simply post the following to that action method:
Title=title+one&Author=author+one&DateTime=1/23/1975 &Title=author+two&Author=author+two&DateTime=6/6/2007…
Notice how we simply repeat each property of the book in the form post
data? Unfortunately, that wouldn’t be a very robust approach. One reason
is that we can’t distinguish from the fact that there may well be
another
Title input unrelated to our list of books which could throw
off our binding.
Another reason is that the checkbox input does not submit a value if it isn’t checked. Most input fields, when left blank, will submit the field name with a blank value. With a checkbox, neither the name nor value is submitted if it’s unchecked! This again can throw off the ability of the model binder to match up submitted form values to the correct object in the list.
To bind complex objects, we need to provide an index for each item, rather than relying on the order of items. This ensures we can unambiguously match up the submitted properties with the correct object.
Here’s an example of a form that submits three books.
<form method="post" action="/Home/Create"> >
Note that the index must be an unbroken sequence of integers starting at 0 and increasing by 1 for each element.
The new expression based helpers in ASP.NET MVC 2 will produce the correct format within a for loop. Here’s an example of a view that outputs this format:
<%@ Page Inherits="ViewPage<IList<Book>>" %> <% for (int i = 0; i < 3; i++) { %> <%: Html.TextBoxFor(m => m[i].Title) %> <%: Html.TextBoxFor(m => m[i].Author) %> <%: Html.TextBoxFor(m => m[i].DatePublished) %> <% } %>
It also works with our templated helpers. For example, we can take the part inside the for loop and put it in a Books.ascx editor template.
<%@ Control Inherits="ViewUserControl<Book>" %> <%: Html.TextBoxFor(m => m.Title) %> <%: Html.TextBoxFor(m => m.Author) %> <%: Html.TextBoxFor(m => m.DatePublished) %>
Just add a folder named EditorTemplates within the Views/Shared folder and add Books.ascx to this folder.
Now change the original view to look like:
<%@ Page Inherits="ViewPage<IList<Book>>" %> <% for (int i = 0; i < 3; i++) { %> <%: Html.EditorFor(m => m[i]) %> <% } %>
Non-Sequential Indices
Well that’s all great and all, but what happens when you can’t guarantee that the submitted values will maintain a sequential index? For example, suppose you want to allow deleting rows before submitting a list of books via JavaScript.
The good news is that by introducing an extra hidden input, you can allow for arbitrary indices. In the example below, we provide a hidden input with the .Index suffix for each item we need to bind to the list. The name of each of these hidden inputs are the same, so as described earlier, this will give the model binder a nice collection of indices to look for when binding to the list.
<form method="post" action="/Home/Create"> <input type="hidden" name="products.Index" value="cold" /> <input type="text" name="products[cold].Name" value="Beer" /> <input type="text" name="products[cold].Price" value="7.32" /> <input type="hidden" name="products.Index" value="123" /> <input type="text" name="products[123].Name" value="Chips" /> <input type="text" name="products[123].Price" value="2.23" /> <input type="hidden" name="products.Index" value="caliente" /> <input type="text" name="products[caliente].Name" value="Salsa" /> <input type="text" name="products[caliente].Price" value="1.23" /> <input type="submit" /> </form>
Unfortunately, we don’t have a helper for generating these hidden inputs. However, I’ve hacked together an extension method which can render this out for you.
When you’re creating a form to bind a list, add the following hidden input and it will add the appropriate hidden input to allow for a broken sequence of indices. Use at your own risk!I’ve only tested this in a couple of scenarios. I’ve included a sample project with multiple samples of binding to a list which includes the source code for this helper.
<%: Html.HiddenIndexerInputForModel() %>
This is something we may consider adding to a future version of ASP.NET MVC. In the meanwhile, give it a whirl and let us know how it works out for you.
Technorati Tags: aspnetmvc,modelbinders | http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ | CC-MAIN-2014-41 | refinedweb | 1,016 | 56.45 |
Eric Blake <address@hidden> writes: > Should the extensions module be extended to check for and define > _POSIX_SOURCE, to coax the compiler into admitting that fdopen > exists? I'd be inclined to say "no". Defining _POSIX_SOURCE tends to cause more problems than it cures, because it can disable useful extensions. For example, with Solaris 10 /usr/ucb/cc, it disables SA_RESTART in <signal.h>. Instead, we should advise users not to use /usr/ucb/cc on Solaris. I know of no reason to use that compiler (other than to generate bogus bug reports :-). Anybody who has a working /usr/ucb/cc in a Solaris setup has a working C compiler in some other location (typically /opt/SUNWspro/bin/cc) and should simply use that compiler. Perhaps we could write a gnulib module that detects the mistake of someone attempting to use /usr/ucb/cc on Solaris. > Also, why is extensions.m4 doing this? Should it be using #ifdef instead? > #ifndef __EXTENSIONS__ > # undef __EXTENSIONS__ > #endif No, that's just the template. The undef gets replaced by a define, if __EXTENSIONS__ is needed. It gets left alone otherwise, so it's a noop in that case. | http://lists.gnu.org/archive/html/bug-gnulib/2006-08/msg00002.html | CC-MAIN-2015-40 | refinedweb | 193 | 58.69 |
Overview of DNSSEC
Applies To: Windows Server 2012 R2, Windows Server 2012
Domain Name System Security Extensions (DNSSEC) is a suite of extensions that add security to the Domain Name System (DNS) protocol by enabling DNS responses to be validated. Specifically, DNSSEC provides origin authority, data integrity, and authenticated denial of existence. With DNSSEC, the DNS protocol is much less susceptible to certain types of attacks, particularly DNS spoofing attacks.
The core DNSSEC extensions are specified in the following Request for Comments (RFCs). Additional RFCs provide supporting information.
RFC 4033: "DNS Security Introduction and Requirements"
RFC 4034: "Resource Records for the DNS Security Extensions"
RFC 4035: "Protocol Modifications for the DNS Security Extensions"
In this section
How DNSSEC works
If supported by an authoritative DNS server, a.
The following figure shows DNS resource records in the zone contoso.com before and after zone signing.
For more information about each of these resource records, see the following section, DNSSEC-related resource records..
Note
A non-authoritative DNS server might use recursion or forwarding to resolve a DNS query. This topic refers to the non-authoritative server as a recursive DNS server; however, if the server uses forwarding, then the process used for DNSSEC validation of DNS responses is the same..
Additionally, if the DNS client is DNSSEC-aware, it can be configured to require that the DNS server perform DNSSEC validation.
The following figure shows the validation process.).
For additional information about how DNSSEC data can be added to the DNS query and response process, see the following section, Validation of DNS responses.
DNSSEC-related resource records
The following table shows the new resource record types that are used with DNSSEC.
Addition of DNSSEC-related resource records
With the exception of the DS record, all of these records are added to a zone automatically when it is signed with DNSSEC. The DS record is a special record that can be manually added to a parent zone to create a secure delegation for a child zone. For example, the contoso.com zone can contain a DS record for secure.contoso.com; however this record must either be created in the parent zone, or created in a child zone and then propagated to the parent zone. The DS record is not automatically created when you sign a zone.
NSEC or NSEC3 records are automatically added to a zone during zone signing. However, a signed zone cannot have both NSEC and NSEC3 records. The type of record (NSEC or NSEC3) added to the zone depends on how zone signing is configured. In the previous example, the zone is signed using NSEC3.. A DNS server running Windows Server 2012 or a later operating system also displays configured trust anchors in the DNS Manager console tree in the Trust Points container. You can also use Windows PowerShell or dnscmd.exe to view trust anchors (note: dnscmd.exe is deprecated and might be removed in a future version of Windows Server).
The following example shows the Windows PowerShell cmdlet Get-DnsServerTrustAnchor.
PS C:\> Get-DnsServerTrustAnchor -Name secure.contoso.com TrustAnchorName TrustAnchorType TrustAnchorState TrustAnchorData --------------- --------------- ---------------- --------------- secure.contoso.com. DNSKEY Valid [15952][DnsSec][RsaSha256][AwEAAe3JOsLYe17k... secure.contoso.com. DNSKEY Valid [38431][DnsSec][RsaSha256][AwEAAdsXYyqxjwBc...
To view all the current trust points on a server, you can use the Get-DnsServerTrustPoint cmdlet.
PS C:\> Get-DnsServerTrustPoint TrustPointName TrustPointState LastActiveRefreshTime NextActiveRefreshTime -------------- --------------- --------------------- --------------------- secure.contoso.com. Active 10/11/2013 4:44:21 PM 10/15/2013 11:22:27 AM
For information about how DNSSEC uses these new resource records to validate and secure DNS responses, see the following section.
Validation of DNS responses
The following figure and table provide a simplified illustration of how DNSSEC can be incorporated into the DNS query and response process to provide validation.
In the example, a DNS client computer queries a recursive (caching) DNS server, which in turn queries authoritative DNS servers before returning a response. This example assumes that DNS data is not yet cached on the client or server. If a zone is signed with DNSSEC, and if DNS servers and clients are DNSSEC-aware, then DNSSEC data can be used to validate that DNS responses are genuine.
The following figure shows the recursive DNS query process.
The following table shows the steps in a DNS query and response with optional DNSSEC data.
Including DNSSEC data:
Three important DNSSEC-related flags (bits) that are mentioned in the preceding table and described in the following section are used in a DNS query and response to determine whether or not DNSSEC data is included and whether or not validation was performed. These flags are set by turning on or turning off extended data bits in the DNS packet header. When these flags are turned on, this is referred to as "setting" the bit which corresponds to a value of one (1). Turning a flag off is referred to as "clearing" the bit and corresponds to a value of zero (0).
DO: The DO bit is included in a DNS query and is an abbreviation for "DNSSEC OK". If the DO bit is set (DO=1), then the client is DNSSEC-aware, and it is OK for the DNS server to return DNSSEC data in a response. If the DO bit is not set (DO=0), then the client is not DNSSEC-aware, and the DNS server must not include any DNSSEC data in a DNS response. DNS clients can still be protected by DNSSEC even if they are not DNSSEC-aware. In this context, a DNS client is any computer that sends a DNS query. When a recursive DNS server sends a query to the authoritative DNS server, the recursive DNS server must indicate that it is DNSSEC-aware so that the authoritative DNS server will send DNSSEC data in the response.
AD: The AD bit is included in a DNS response and is an abbreviation for "authenticated data". If the AD bit is set (AD=1), then it means the DNS response is authentic because it was validated using DNSSEC. A non-validating DNSSEC-aware computer, such as one running Windows 8, does not perform DNSSEC validation but can be configured to require that DNS responses are authentic. If the AD bit is not set (AD=0), then the DNS response was not validated, either because validation was not attempted, or because validation failed.
CD: The CD bit is included in a DNS query and is an abbreviation for "checking disabled". If the CD bit is set (CD=1) in a query, then it means a DNS response should be sent whether or not validation was successfully performed. If the CD bit is not set (CD=0), then a DNS response will not be sent if validation was required and failed. If the CD bit is clear (CD=0), this essentially means “checking enabled” and DNSSEC validation can occur. The CD bit might be set (CD=1) in a query because the host is capable of performing DNSSEC validation, such as a recursive DNS server running Windows Server 2012. A non-validating stub resolver, such as a computer running Windows 8 will always set CD=0.
A fourth important flag (bit) that can be present in a DNS packet header is the AA bit. This flag is not new with DNSSEC, but it can be used when DNSSEC is deployed:
- AA: The AA bit is included in a DNS response and is an abbreviation for "authoritative answer". If the AA bit is set, it means that the DNS response is authentic because it came directly from an authoritative DNS server. A client that requires DNSSEC validation (AD=1) will accept the AA bit instead (AA=1, AD=0) if the client directly queries an authoritative server because authoritative responses do not need to be validated. It would be redundant for an authoritative server to validate its own response.
Example DNS queries
The following examples display DNS query results that are performed from a DNS client computer running Windows 8.1 using the Resolve-DnsName cmdlet. The Resolve-DnsName cmdlet was introduced in Windows Server 2012 and Windows 8 and can be used to display DNS queries that include DNSSEC data.
Important
Do not use the nslookup command-line tool to test DNSSEC support for a zone. The nslookup tool uses an internal DNS client that is not DNSSEC-aware.
Example 1: In the following example, a query is sent to a recursive DNS server for an address (A) record in the signed zone secure.contoso.com with DO=0.
PS C:\> Resolve-DnsName finance.secure.contoso.com –type A -server dns1.contoso.com Name Type TTL Section IPAddress ---- ---- --- ------- --------- finance.secure.contoso.com A 2848 Answer 192.168.0.200
In this example, the DO bit was not set because the dnssecok parameter was not included.
Example 2: In the following example, the DO=1 flag is set by adding the dnssecok parameter.
PS C:\> resolve-dnsname -name finance.secure.contoso.com -type A -server dns1.contoso.com -dnssec : {}
When DO=0, the DNS server will not send DNSSEC data in the DNS reply. When DO=1, the client indicates that it is able to receive DNSSEC data if available. Because the secure.contoso.com zone is signed, an RRSIG resource record was included with the DNS response when DO=1.
In both example 1 and example 2, validation is not required for the secure.contoso.com zone because the Name Resolution Policy Table (NRPT) is not configured to require validation.
You can use the Get-DnsClientNrptPolicy cmdlet to view current NRPT rules. For more information, see Get-DnsClientNrptPolicy.
Example 3: In the following example, an NRPT rule is displayed for secure.contoso.com.
PS C:\> Get-DnsClientNrptPolicy Namespace : .secure.contoso.com QueryPolicy : SecureNameQueryFallback : DirectAccessIPsecCARestriction : DirectAccessProxyName : DirectAccessDnsServers : DirectAccessEnabled : DirectAccessProxyType : NoProxy DirectAccessQueryIPsecEncryption : DirectAccessQueryIPsecRequired : False NameServers : DnsSecIPsecCARestriction : DnsSecQueryIPsecEncryption : DnsSecQueryIPsecRequired : False DnsSecValidationRequired : False NameEncoding : Utf8WithoutMapping
In this example, the value for DnsSecValidationRequired is False. This means that DNSSEC validation is not required.
Example 4: After enabling DNSSEC validation for secure.contoso.com, the NRPT displays True for DnsSecValidationRequired. This example only displays the secure.contoso.com namespace, and the DnsSecValidationRequired parameter.
PS C:\> (Get-DnsClientNrptPolicy -NameSpace secure.contoso.com).DnsSecValidationRequired True
If the value of DnsSecValidationRequired is True, then DNSSEC-aware client computers will always send queries with DO=1, even if the dnssecok parameter is not included.
Example 5: When DNSSEC validation is required by the Name Resolution Policy Table (NRPT), the DNSSEC OK bit is automatically set (DO=1) for DNSSEC-aware clients.
PS C:\> resolve-dnsname -name finance.secure.contoso.com -type A -server dns1.contoso : {}
In this example, an RRSIG record is sent in the DNS response in order to fulfill the validation requirements for secure.contoso.com. A valid trust anchor is also configured on the recursive DNS server (dns1.contoso.com).
If a DNS client is not DNSSEC-aware, the NRPT rule does not apply, and queries are sent with DO=0, even if an NRPT rule exists that requires DNSSEC validation.
Example 6: In the following example, the same query is performed as in example 5, but without a valid trust anchor configured on dns1.contoso.com.
PS C:\> resolve-dnsname -name finance.secure.contoso.com -type A -server dns1.contoso.com resolve-dnsname : finance.secure.contoso.com : Unsecured DNS packet At line:1 char:1 + resolve-dnsname -name finance.secure.contoso.com -type A -server dns1.contoso.co ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (finance.secure.contoso.com:String) [Resolve-DnsName], Win32Excepti on + FullyQualifiedErrorId : DNS_ERROR_UNSECURE_PACKET,Microsoft.DnsClient.Commands.ResolveDnsName
In this example, DNS resolution fails with the message DNS_ERROR_UNSECURE_PACKET because validation is required by the NRPT but cannot be performed due to the lack of a valid trust anchor for the secure.contoso.com zone. The Resolve-DnsName cmdlet reports detailed results for the type of failure encountered. If the DNS client attempts to resolve finance.secure.contoso.com in order to connect to this host, for example, to share a file, it fails.
DNSSEC scenarios
Because DNSSEC can be deployed in many different environments with unique server and client settings, it is important to understand how DNS queries and responses are affected.
Consider the following four DNSSEC-related statements. Each statement affects how DNSSEC works in a given scenario:
The finance.secure.contoso.com resource record is correctly signed with DNSSEC.
A recursive DNS server is capable of validating responses to a query for finance.secure.contoso.com.
A DNS client is DNSSEC-aware.
A DNS client is configured to require validation for all queries in the secure.contoso.com namespace.
Let’s examine each of these conditions, and their consequences, in more detail:
DNSSEC signing status: Because DNSSEC signs all records in the zone, this condition refers to the state of the secure.contoso.com zone, and not just the finance.secure.contoso.com resource record. You cannot sign some records and not sign other records; therefore, the DNSSEC status of finance.secure.contoso.com depends on the DNSSEC status of secure.contoso.com.
Signed correctly: The secure.contoso.com zone can be signed in a valid manner, which enables finance.secure.contoso.com to be validated as genuine. To be valid, the zone must be signed with valid, unexpired keys, and all required DNSSEC-related resource records must be present.
Not signed: The secure.contoso.com zone might not be signed, in which case there will be no RRSIG record associated with finance.secure.contoso.com, and DNS responses to queries for finance.secure.contoso.com cannot be validated. If a client requires validation (condition #4 below) in this scenario, then a DNS query that is sent to a recursive DNS server will fail because the DNS client does not accept a non-validated response. Note: If a client directly queries an authoritative server, it does not fail validation because the response is already considered authentic.
Not signed correctly: The secure.contoso.com zone might be signed, but not in a valid manner. For example, one or more DNSSEC signing keys might be expired. After initially signing a zone, the zone must periodically be re-signed with new keys before the signing key validity period expires, in order to maintain a secure DNSSEC operational status. The validity period for DNSSEC signing keys should be short enough to maintain security, but long enough to enable easy administration. DNSSEC in Windows Server 2012 and Windows Server 2012 R2 supports automatic key rollover, providing both security and ease of administration for your DNSSEC-signed zones.
Validation status: A recursive DNS server with a valid trust anchor (public cryptographic key) for the secure.contoso.com zone will be capable of validating a DNS response for the finance.secure.contoso.com resource record. A recursive DNS server must also support the DNSSEC standards and algorithms that are used to sign the zone.
Can validate: If the recursive DNS server supports all cryptographic algorithms used to sign the secure.contoso.com zone, and it has a valid trust anchor that it can use to decrypt the DNSSEC signature that is associated with the signed resource record, then it can validate the finance.secure.contoso.com resource record as genuine.
Cannot validate: A non-DNSSEC aware DNS server is not capable of validation. Similarly, a DNS server that does not currently have a valid trust anchor for the secure.contoso.com zone will not be capable of validating a DNS response for finance.secure.contoso.com. Trust anchors must be updated when a zone is re-signed, for example, during key rollover. DNSSEC in Windows Server 2012 and Windows Server 2012 R2 supports automatic update of trust anchors on key rollover per RFC 5011, “Automated Updates of DNS Security (DNSSEC) Trust Anchors.”
DNSSEC-aware status: The DNSSEC-aware status of a DNS client depends on the operating system that it is running. Note: The Windows DNS Client service in Windows 7 or Windows Server 2008 R2 and later operating systems are DNSSEC-aware, non-validating stub resolvers. Previous Windows operating systems are non-DNSSEC-aware. The DNS client will inform a DNS server whether or not it is DNSSEC-aware when it sends a DNS query.
Both client and server are DNSSEC-aware: If both the client and the server are DNSSEC-aware, then the DNS response from the server to the client will include the DNSSEC authenticated data (AD) flag. If the DNS response is validated with DNSSEC, then AD=1 will be sent. If the DNS response was not validated, then AD=0 will be sent.
The DNS server is not DNSSEC-aware: If the DNS server is not DNSSEC-aware, then no validation is performed, and the AD flag is not set (AD=0) regardless of whether or not the DNS client is DNSSEC-aware.
The DNS client is not DNSSEC-aware: If the DNS client is not DNSSEC-aware, the DNS server will not set the AD flag in its response to the client even if it understands DNSSEC. However, if the DNS server is DNSSEC-aware and it has a trust anchor for the zone, the server will attempt to validate the response from the authoritative server. If the validation fails, it will return a DNS server failure to the DNS client. If the validation succeeds, it will return the query results to the client. In this way, a DNSSEC-aware recursive DNS server can protect non-DNSSEC-aware DNS clients. In this scenario, if the zone is not signed, no validation is attempted and the response is returned normally to the client.
Validation requirement: This setting determines the requirement of a DNSSEC-aware DNS client for DNSSEC data (the AD flag) in a response from a DNS server. Note: In order for the DNS client to require validation, it must be DNSSEC-aware. Non-DNSSEC-aware DNS clients cannot be forced to require DNSSEC validation. If the DNS client is directly querying an authoritative DNS server, the response will always appear to be validated, even if the zone is not signed. This is because authoritative DNS servers always return authentic responses.
Validation is required: If validation is required, the client must receive AD=1 (validation successful) or it will reject the DNS response. If validation was unsuccessful or not attempted (AD=0) then DNS resolution will fail. This is true even if the zone is not signed. Note: This only applies to queries against a recursive, non-authoritative DNS server.
Validation is not required: If validation is not required, the client will accept a response from a non-DNSSEC-aware recursive DNS server. However, if the recursive DNS server is DNSSEC-aware and validation fails, it will return a server failover to the client even if the client does not require validation.
See also
DNSSEC Deployment Planning
Deploy DNSSEC with Windows Server 2012
Appendix A: DNSSEC Terminology
Appendix B: Windows PowerShell for DNS Server
Step-by-Step: Demonstrate DNSSEC in a Test Lab | https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/jj200221(v=ws.11) | CC-MAIN-2019-30 | refinedweb | 3,160 | 55.54 |
BlueCop Wrote:Mighty_Diamond: you can already control all that in XBMC Video settings for subtitles.
I don't plan to support downloading.
Donate to XBMC or adopt a kitty.
BlueCop Wrote:use the install from zip option.
this if from the readme.
use the addon settings to determine the length of time between updates. I would suggest the 10 hour mark. They usually add new videos in the morning.
I am going to take a look at the timers. I want different timers for subscription and queue. queue should have a shorter duration while subscriptions should have a much longer one.
Quote:DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
crawl Wrote:I recently upgraded to Eden b2, and Hulu is now giving me a script fail after I replaced a new librtmp for jTV.
aTV2 Eden b2
xbmc.log:
Looks really weird.. Lots of these errors?
Thanks for any recommendations.. | http://forum.kodi.tv/showthread.php?tid=121023&page=7 | CC-MAIN-2015-40 | refinedweb | 154 | 70.5 |
0 DuffManLight 6 Years Ago Trying to learn recursion. Problem asks to use recursion on non-negative number to insert commas. Ex: 20131 as 20,131. My program adds in an extra comma at end. Any help in pushing me in the correct direction to fix this would be appreciated. Tried to use a 'count' to determine end of number but can not figure it out. input: 546789301 output: 546,789,301, #include "stdafx.h" #include <iostream> using namespace std; void commaInsert(int v, int &count) { if (v <= 0) { count++; cout<<"Count equals: "<<count<<endl; return; //base case } commaInsert(v/1000, count); cout<<(v%1000)<<((count=1)?",":""); return; } int main() { int input = 546789301, count = 0; commaInsert(input, count); cout<<endl; return 0; } assignment c++ homework recursion Edited 6 Years Ago by WaltP: Don't use TEX mode. Just type your question. | https://www.daniweb.com/programming/software-development/threads/261858/homework-ques-use-recursion-to-insert-comma-into-integer | CC-MAIN-2017-09 | refinedweb | 141 | 67.35 |
There have been several questions on the Dynamic Data Forum saying things like IAutoFieldGenerator does not work with Details, Edit and Insert pages. This is because these page template have now moved to FormView which allows for us to have the nice new Entity Templates and this is cool; but leaves us with the issue of having to do custom column generation in two ways one for form view and one for GridView in List and ListDetails pages. So harking back to this post A Great Buried Sample in Dynamic Data Preview 4 – Dynamic Data Futures long ago in a year far far away
So what I am planning to do is add our own MetaModel that we can pass in a delegate to produce a custom list of columns. I am going to implement the Hide column based on page template (HideColumnInAttribute) for now.
The Custom MetaModel
So first things first lets build out custom MetaModel, the only two classes we will need to implement for our custom MetaModel are:
MetaModelMetaModel
MetaTableMetaTable
We need MetaModel because it goes away and get the other classes.
public class CustomMetaModel : MetaModel { /// <summary> /// Delegate to allow custom column generator to be passed in. /// </summary> public delegate IEnumerable<MetaColumn> GetVisibleColumns(IEnumerable<MetaColumn> columns); private GetVisibleColumns _getVisdibleColumns; public CustomMetaModel() { } public CustomMetaModel(GetVisibleColumns getVisdibleColumns) { _getVisdibleColumns = getVisdibleColumns; } protected override MetaTable CreateTable(TableProvider provider) { if (_getVisdibleColumns == null) return new CustomMetaTable(this, provider); else return new CustomMetaTable(this, provider, _getVisdibleColumns); } }
Listing 1 – Custom MetaModel class
So what are we doing here, firstly we have a delegate so we can pass in a methods to do the column generation and we are passing this in through our custom constructor. Then in the only method we are overriding we are returning the CustomMetaTable class, and passing in the delegate if it has been set.
public class CustomMetaTable : MetaTable { private CustomMetaModel.GetVisibleColumns _getVisdibleColumns; /// <summary> /// Initializes a new instance of the <see cref="CustomMetaTable"/> class. /// </summary> /// <param name="metaModel">The entity meta model.</param> /// <param name="tableProvider">The entity model provider.</param> public CustomMetaTable(MetaModel metaModel, TableProvider tableProvider) : base(metaModel, tableProvider) { } /// <summary> /// Initializes a new instance of the <see cref="CustomMetaTable"/> class. /// </summary> /// <param name="metaModel">The meta model.</param> /// <param name="tableProvider">The table provider.</param> /// <param name="getVisibleColumns">Delegate to get the visible columns.</param> public CustomMetaTable( MetaModel metaModel, TableProvider tableProvider, CustomMetaModel.GetVisibleColumns getVisibleColumns) : base(metaModel, tableProvider) { _getVisdibleColumns = getVisibleColumns; } protected override void Initialize() { base.Initialize(); } public override IEnumerable<MetaColumn> GetScaffoldColumns( DataBoundControlMode mode, ContainerType containerType) { if (_getVisdibleColumns == null) return base.GetScaffoldColumns(mode, containerType); else return _getVisdibleColumns(base.GetScaffoldColumns(mode, containerType)); } }
Listing 2 – Custom MetaTable class
In CustomMetaTable we have the default constructor and a custom constructor again we passing the delegate into the custom constructor. Now in the only method we are overriding we either call the base GetScaffoldColumns or our delegate if is has been set. And that’s it as far as the Meta Classes are concerned.
The Attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class HideColumnInAttribute : Attribute { public PageTemplate PageTemplate { get; private set; } public HideColumnInAttribute() { } public HideColumnInAttribute(PageTemplate lookupTable) { PageTemplate = lookupTable; } }
Listing 3 – HideColumnInAttribute
Listing 3 is the HideColumnIn attribute see Dynamic Data - Hiding Columns in selected PageTemplates for details on this attribute.
public static class ControlExtensionMethods { // "~/DynamicData/PageTemplates/List.aspx" private const StringThe page.</param> /// <returns></returns> public static PageTemplate GetPageTemplate(this Page page) { try { return (PageTemplate)Enum.Parse(typeof(PageTemplate), page.RouteData.Values["action"].ToString()); } catch (ArgumentException) { return PageTemplate.Unknown; } } }
Listing 4 – GetPageTemplate extension method.
[Flags] public enum PageTemplate { // standard page templates Details = 0x01, Edit = 0x02, Insert = 0x04, List = 0x08, ListDetails = 0x10, // unknown page templates Unknown = 0xff, }
Listing 5 – PageTemplate enum.
In Listing 4 we have the new improved GetPageTemplate extension method now you don’t have to change each page to inherit DynamicPage you can just call the Page.GetPageTemplate() to find out which page you are on. it required the PageTemplate enum in listing 5.
The Delegate Methods
public static IEnumerable<MetaColumn> GetVisibleColumns(IEnumerable<MetaColumn> columns) { var visibleColumns = from c in columns where IsShown(c) select c; return visibleColumns; }>(); if (hideIn != null) return !((hideIn.PageTemplate & pageTemplate) == pageTemplate); return true; }
Listing 6 – Column generator methods
Now we need to supply our own column generator methods, in Listing 6 we have two methods the first GetVisibleColumns (and the name does not need to be the same as the Delegate) is the one we pass into the MetaModel, and the second IsHidden is where we test to see if the column should be hidden or not.
Adding To Web Application
Now we need to put these into our sample web application.
public class Global : System.Web.HttpApplication { private static MetaModel s_defaultModel = new CustomMetaModel(GetVisibleColumns); public static MetaModel DefaultModel { get { return s_defaultModel; } } // other code ... }
Listing 7 – Adding to Global.asax
So all we have to do is change the default value in Global.asax from
private static MetaModel s_defaultModel = new MetaModel();
to
private static MetaModel s_defaultModel = new CustomMetaModel(GetVisibleColumns);
Now all column generation throughout the site is handled by the GetVisibleColumns method from Listing 6.
[MetadataType(typeof(OrderMetadata))] public partial class Order { internal partial class OrderMetadata { public Object OrderID { get; set; } public Object CustomerID { get; set; } public Object EmployeeID { get; set; } public Object OrderDate { get; set; } [HideColumnIn(PageTemplate.List)] public Object RequiredDate { get; set; } public Object ShippedDate { get; set; } public Object ShipVia { get; set; } [HideColumnIn(PageTemplate.List)] public Object Freight { get; set; } public Object ShipName { get; set; } [HideColumnIn(PageTemplate.List)] public Object ShipAddress { get; set; } [HideColumnIn(PageTemplate.List)] public Object ShipCity { get; set; } [HideColumnIn(PageTemplate.List)] public Object ShipRegion { get; set; } [HideColumnIn(PageTemplate.List)] public Object ShipPostalCode { get; set; } [HideColumnIn(PageTemplate.List)] public Object ShipCountry { get; set; } // Entity Ref public Object Customer { get; set; } // Entity Ref public Object Employee { get; set; } // Entity Set public Object Order_Details { get; set; } // Entity Ref public Object Shipper { get; set; } } }
Listing 8 – sample metadata.
Download
Happy Coding
29 comments:
Hello Steve,
in this solution we lost following:
[HideColumnIn(PageTemplate.Edit, PageTemplate.Insert)]
So, no more multiple restrictions. How can we add more template pages in HideColumIn attribute?!
Functionality we need with Dynamic Data is Hide/Show columns dynamically based on metadata (works perfect with list view but not with edit or insert with your older solution ()!)
Thanx for help,
Denis
Hi Denis, not sure exactly what you want, just drop me an e-mail and I'll see what I can do.
Steve :D
Is Microsoft trying to make this easier for people, or a lot more complex? Is there going to be any end to abandoning old methods and going in for new, unnecessary ones?
Hi,
I am trying to use your sample with my DD web application , but for some reason he is not using my
MetaDatType.cs...
Do you have an idea why?
Hi there yes the usual reason that metadata is not recognised is namespace issues, my e-mail is at the top of the site e-mail me and I'll see what I can do.
Steve :)
Hey Steve,
Thank you for the great post.
I had the same problem as Dennis Brulic (2 June). I wanted to hide columns from two or more actions (e.g. List and Insert) at the same time. Here is my solution but would appreciate any feedback on improving it:
1. Created a 2nd HideColumn Attribute (e.g. for Insert) from Listing 3
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class HideColumnInsertAttribute : Attribute
{
public PageTemplate PageTemplate { get; private set; }
public HideColumnInsertAttribute() { }
public HideColumnInsertAttribute(PageTemplate lookupTable)
{
PageTemplate = lookupTable;
}
}
2. Edited the code from Listing 6. This example handles two actions (List and Insert) but could be edited to handle more:>();
var hideInsert = column.GetAttribute<HideColumnInsertAttribute>();
if (pageTemplate == PageTemplate.Insert)
{
if (hideInsert != null) return !((hideInsert.PageTemplate & pageTemplate) == pageTemplate);
}
if (pageTemplate == PageTemplate.List)
{
if (hideIn != null)
return !((hideIn.PageTemplate & pageTemplate) == pageTemplate);
}
return true;
}
3. Use in metadata as appropriate (see listing 8):
[DisplayName("Field 1")]
[HideColumnIn (PageTemplate.List)]
[HideColumnInsert (PageTemplate.Insert)]
public string field1 { get; set; }
Hope this helps.
Cheers,
Grant
I'll redo this with some ideas I've had since.
Steve :)
How can this be implemented in ListDetails.aspx template which has got both edit and insert forms in it?
this just works ford any page template, as it works at the meta model level
Steve
In the ListDetails.aspx page, I have both Insert FormView and Edit GridView. I want set of columns to be hidden only in the FormView but must be shown in the gridview. Since the code sample given here works against a page template, I'm not sure how this can be implemented in this case.
I'll send you that sample I have if you email me direct
Steve
Hi Steve,
Thank you so much for sharing this with us, it's great!
Like Sachin, I also need to hide certain columns in the FormView but show them in the GridView inside of the ListDetails.aspx page.
Can you please show us how to implement such functionality?
Thank you in advance.
Hi Christian, send me an e-mail and I will explain a method you could use.
Steve
Hi Steve,
Where and how to call the extension methods. My requirement is like I want to show a column in Insert.aspx but not in other pages.
Please provide in detail.
Hi there, that is what this sample will do, there is no extension methods to call you just replce the metsmodel with this one and then add you attribute and it all just works.
Steve
But the problem is I am not able to pass getVisiblecolumns in CustomMetaModel. In Global.asax I am doing like this -
private static MetaModel s_defaultModel = new CustomMetaModel(); //MetaModel();
and in MetaData class -
public class EmployeeMetadata
{
[HideColumnIn(PageTemplate.List)] [UIHint("TextPassword")]
public object Pass{get; set;}
}
And how to pass one more PageTemplate.Edit in HideColumnIn
Please provide in detail.
Thanks
You don't need to pass anything in in Global.asax you just add the attribute to you buddy/metadata classes.
Try downloading and looking at the sameple.
Steve
Steve,
It is not working.
See my req. is I have to show a column in Insert and Edit Page
but not in List and Listdetails.
I am doing same as what you told but it's not working. May be I am wrong somewhere.
If you have any sample for same then please send to viv_bit at yahoo
Can you send me a sample project that uses Northwind and I will test here?
Steve
P.S. my e-mail address is in the top right of the page.
Hi,
I have implemented the solution you provided to hide the columns in specific template. I am getting an error at global.asax
Error "Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable'. 'Where' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?
I am facing this error at method
_____________*****________________
public static IEnumerable GetVisibleColumns(IEnumerable columns)
{
var visibleColumns = from c in columns
where IsShown(c)
select c;
return visibleColumns;
}
_________******_____________
I have written this method in global.asax.cs file.
please help me.
Hi Navneet, not sure where you are getting this error, have you downloaded the sample and tested that?
Steve
Hi Steve,
I don't have northwind DB so that's why not able to run the project completely. I am getting an error at line:-
var visibleColumns = from c in columns. columns variable is providing the issue.
you can get it from here
Northwind
Steve
Hi Steve,
This is the post I pointed to from your blog on the older method of hiding columns.
This code is converting to vb.net well, with one unfortunate exception.
In the global.asax file you have this line of code:
Private Shared s_defaultModel As New CustomMetaModel(GetVisibleColumns()
which is not passing any parameters, but the function in global.asax is expecting a collection of columns:
Public Shared Function GetVisibleColumns(columns As IEnumerable(Of MetaColumn)) As IEnumerable(Of MetaColumn)
Dim visibleColumns = From c In columns Where IsHidden(c) Select c
Return visibleColumns
End Function
- so it won't compile and I don't know what to pass into it. I'm thinking the problem has to do with the delegate, but I don't know how to solve it.
Thanks alot!
John (Don't push yourself to answer this in a hurry, I know you are on the mend!)
Hay, did you ever solved that, i have the same problem?
Hi there I have not solved the issue as there has been no one to do the VB conversion for me I'm a C# coder. It need someone doing a lot of VB to do it and I don't know any experienced VB programmers sorry :(
Steve
Hi there, awesome post here BTW.
I stumbled on it after searching for random things to solve my problem here:
I wonder if you could take a look and suggest a workaround there, seeing as you are very knowledgeable on Dynamic Data :)
Cheers,
Juliano
I posted a reply to the thread on StackOverflow
Steve | http://csharpbits.notaclue.net/2010/02/new-way-to-do-column-generation-in.html?showComment=1345641824746 | CC-MAIN-2019-35 | refinedweb | 2,184 | 56.05 |
277 packages found
Stringify an object/array like JSON.stringify just without all the double-quotes
A string manipulation toolbox, featuring a string formatter (inspired by sprintf), a variable inspector (output featuring ANSI colors and HTML) and various escape functions (shell argument, regexp, html, etc).
import and export tools for elasticsearch
- elasticsearch
- dump
- elasticdump
- import
- export
- transfer
- migrate
- migration
- elasitic
- cluster
- elastic-dump
- elastic dump
Handlebars utility helper to output a navigable, visual representation of data
Stream SQL dump to newline delimited json
Dump Mysql, Postgres, SQLServer, and ElasticSearch databases directly to AWS S3, Google Cloud Storage, or Azure.
Convert an object or array into a formatted string
A nodejs package to quickly dumb DB to file. Supports Mysql, PostgreSQL, MongoDB and SQLite
A Node function to connect into MongoDB, get documents from collection by name and save the content to CSV file. Store your sensitive informations in .env or inject from pipeline are good pratices and this way i did. ### Install ```sh npm i mongo-dump-col
A Promise-based client for the 'Have I been pwned?' service.
A better and pretty variable inspector for your Node.js applications.
putout formatter stores output and dump it on end
Get all the values from a contract in the blockchain, optionally transformed as desired
Dump records from mongo to elastic
httpdumper is a library that will help you debugging your http request.
PouchDB Load - load dumped CouchDB/PouchDB databases on the client
Dumps all values and/or keys of a level db or a sublevel to the console.
Export a PostgreSQL schema as JSON
A nodejs package to quickly dumb DB to file. Supports Mysql, PostgreSQL, MongoDB and SQLite | https://www.npmjs.com/search?q=keywords:dump | CC-MAIN-2022-05 | refinedweb | 278 | 50.57 |
Tax
Have a Tax Question? Ask a Tax Expert
Hi & thanks for using our service. I'll do my best to give you a complete & accurate answer. Please ask me to clarify anything that is not clear.
ok
The interest through the date of death belongs on the decedent's final income tax return and the interest on the account after the date of death is taxable to the beneficiary. The 1099 is issued to the account of the decedent with the decedent's social security number until the account is closed or switched over to the beneficiary. Often, the 1099 figures have to be split between the decedent and the beneficiary by the accountant preparing the income tax returns. Many times, the 1099 that is issued to the decedent is included on the decedent's final income tax return without regard to making any allocation to the periods before & after death, primarily due to the fact that with interest rates so low, the interest allocable to the period after death is not significant.
Since the Personal representative is responsible for filing the decedent's final income tax return, he or she should be able to obtain a copy of the 1099s. However, most likely the 1099s were sent to whatever address was on the account and are probably in the decedents continuing mail which by now should be forwarded to the Personal Representative.
The death was in Nov. & the interest was over $6,000. All beneficiaries shared equally but were sent very different amounts on their 1099s, one $507 another $45, aNOTHER $80. I, as personal represenative, have not recieved a 1099-I to include in the decedants tax filing. Yes, the account was closed in Dec. when all funds were dispersed per POD.
Was there only one account?
I faxed their Estate Accounts Dept. all addresses and information in Dec. & all beneficiaries received their checks, all in the same identical amount.
No, a total of 6 accounts - all divided equally.
One reason there could be different amounts for the beneficiaries could be the timing of the withdrawal of their funds.
It was only within a two - three week period.
Are you the Personal Representative appointed by the Court?
We are not going to probate since there are no other accets. I h
I have been her POA, SS payee, and have been dealing with all of the medical & financial issues for over 8 yrs. We have not gone to court. please answer it; thanks, SEG
I was disconnected when we were talking last night. No, the information was not helpful since it did not answer what I should do. And I DID notify the credit union that there was no probate court etc.
I'm sorry you were disconnected, that's something I can't control; there have been some problems lately in that regard. The whole idea of this "Chat" mode is for us to have a discussion about the issue that is concerning you. Obviously I had no way of knowing if you were disconnected or simply read my comments and were satisfied.
I can see now that you weren't satisfied and rather than just let your "Poor Service" rating stand, I would appreciate the chance to discuss the situation further with you. Perhaps, you didn't receive all of my comments and therefore you were unable to consider them.
I will be available all afternoon today if you come back online, just type something in & I should get an email telling me that you have returned. Hopefully, I can then satisfy you and you will upgrade your rating. I have almost a 100% satisfaction score & I would like to keep it that way.
I had asked you a series of questions & evidently you were disconnected before you could answer them. In case you didn't receive that data, I will repeat it here. Depending upon your answers to those questions, I can better advise you how to proceed.?
Hello?
Thank you for trying to assist me but it is really a question of how to get the credit union to respond and do the correct thing. This "session" has not helped me but it is not your fault. We are not going to probate ..... I intend to submit her tax return (as I have always done) but include the 1310 form. I have her death certificate. The problem remains with the credit union that sent out crazy 1099s to the beneficiaries and have not sent me the proper "official" 1099-I to be filed with her final personal 1040.
I have previously called several times to the credit union, faxed them twice (to different offices) and emailed them. I have also had the beneficiaries attempt to contact them and encouraged them to have their tax advisers also call.
That all being said I think that you should consider returning a portion at least, of the $45 that I spent on this attempt since I really have gained nothing by it.
Well, first of all, I explained why the credit union may not be responding to you. If the decedent had a will, even if there are no assets to pass (no assets in her name alone) under the will, the law actually requires that the will be filed with the Court. Normally, if you are the named executor, or the person in possession of the decedent's property and there are no objections, there is an informal procedure that may be employed (a voluntary administration), where you will be able to be the "Voluntary Administrator" and there are no filings or reports that must be filed with the Probate Court. The fact that you do not want to follow my recommendations, is obviously your prerogative; however when you say that "this session has not helped me", that is your choice. If you followed my advice, your problem would be solved.
As far as a refund is concerned, I can't control that as I will not be compensated as long as your "poor service" rating stands. It is odd that you rated me that way & yet you say "this session has not helped me but it is not your fault". If it isn't my "fault", how does that translate to a "poor service" rating?
All you need to do is to contact "Customer Service" and ask for a refund. Since we offer a satisfaction guarantee, you will receive a full refund or credit to your charge or debit card of any deposit or payment you made. I can't do that for you, as we don't handle the money & I haven't received any part of your deposit as we do not get paid if we receive a "poor service" rating.
I hope you are able to get the information you need, again, since the decedent died in November, it is likely that the decedent's 1099s have been forwarded to the address on file with the bank.
The address on file is MY ADDRESS. Nothing that you have suggested actually applies except for the suggestion of contacting "Customer Service". Thank you. | http://www.justanswer.com/tax/7j5s7-correct-understanding-beneficiaries-payment.html | CC-MAIN-2016-44 | refinedweb | 1,190 | 69.82 |
NAME
mblen - determine number of bytes in next multibyte character
SYNOPSIS
#include <stdlib.h> int mblen (const char *s, size_t n);
DESCRIPTION
If s is not a NULL pointer, the mblen function inspects at most n bytes of the multibyte string starting at s and extracts the next complete multibyte character. It uses a static anonymous shift state only known >= MB_CUR_MAX, if the multibyte string contains redundant shift sequences. If the multibyte string starting at s contains an invalid multibyte sequence before the next complete character, mblen also returns -1. If s is a NULL pointer, the mblen function resets the shift state, only known to this function, to the initial state, and returns non-zero if the encoding has non-trivial.
CONFORMING TO
ISO/ANSI C, UNIX98
SEE ALSO
mbrlen(3)
NOTES
The behaviour of mblen depends on the LC_CTYPE category of the current locale. The function mbrlen provides a better interface to the same functionality. | http://manpages.ubuntu.com/manpages/maverick/pt/man3/mblen.3.html | CC-MAIN-2014-15 | refinedweb | 157 | 57.91 |
Flash CS4 Resources
Using Flash
ActionScript 3.0 and Components
ActionScript 2.0 and Components
Adobe AIR
Flash Lite
Extending Flash
Full-screen
mode allows you to set a movie’s stage to fill a viewer’s entire
monitor without any container borders or menus. The Stage class’s displayState property
is used to toggle full-screen mode on and off for a SWF. The displayState property
can be set to one of the values defined by the constants in the
flash.display.StageDisplayState class. To turn on full-screen mode,
set the displayState property to StageDisplayState.FULL_SCREEN:
stage.displayState = StageDisplayState.FULL_SCREEN;
In Flash Player, full-screen mode can only be initiated through
ActionScript in response to a mouse click (including right-click)
or keypress. AIR content running in the application security sandbox
does not require that full-screen mode be entered in response to
a user gesture.
To exit full-screen mode, set the displayState property
to StageDisplayState.NORMAL.
stage.displayState = StageDisplayState.NORMAL;
In addition, a user can choose to leave full-screen mode by switching
focus to a different window or by using one of several key combinations:
the Esc key (all platforms), Control-W (Windows), Command-W (Mac),
or Alt-F4 (Windows).
To enable full-screen
mode for a SWF file embedded in an HTML page, the HTML code to embed
Flash Player must include a param tag and embed attribute
with the name allowFullScreen and value true,
like this:
<object>
...
<param name="allowFullScreen" value="true" />
<embed ...
</object>
In the Flash authoring tool, select
File -> Publish Settings and in the Publish Settings dialog box,
on the HTML tab, select the Flash Only - Allow Full Screen template.
In
Flex, ensure that the HTML template includes <object> and <embed> tags that
support full screen. also security-related restrictions
for using full-screen mode with Flash Player in a browser. These
restrictions are described in Flash Player security.
The Stage.fullScreenHeight and Stage.fullScreenWidth properties
return the height and the width of the monitor that’s used when going
to full-screen size, if that state is entered immediately. These
values can be incorrect if the user has the opportunity to move
the browser from one monitor to another after you retrieve these
values but before entering full-screen mode. If you retrieve these
values in the same event handler where you set the Stage.displayState property
to StageDisplayState.FULL_SCREEN, the values are
correct.For users with multiple monitors, the SWF content expands
to fill only one monitor. Flash Player and AIR use a metric to determine
which monitor contains the greatest portion of the SWF, and uses
that monitor for full-screen mode. The fullScreenHeight and fullScreenWidth
properties only reflect the size of the monitor that is used for full-screen
mode.For more information, see Stage.fullScreenHeight and Stage.fullScreenWidth in
the ActionScript 3.0 Language and Components Reference.
Stage
scaling behavior for full-screen mode is the same as under normal
mode; the scaling is controlled by the Stage class’s scaleMode property.
If the scaleMode property is set to StageScaleMode.NO_SCALE,
the Stage’s stageWidth and stageHeight properties
change to reflect the size of the screen area occupied by the SWF
(the entire screen, in this case); if viewed in the browser the
HTML parameter for this controls the setting.
You can use the Stage class’s fullScreen event
to detect and respond when full-screen mode is turned on or off.
For example, you might want to reposition, add, or remove items
from the screen when entering or leaving full-screen mode, as in
this example:
import flash.events.FullScreenEvent;
function fullScreenRedraw(event:FullScreenEvent):void
{
if (event.fullScreen)
{
// Remove input text fields.
// Add a button that closes full-screen mode.
}
else
{
// Re-add input text fields.
// Remove the button that closes full-screen mode.
}
}
mySprite.stage.addEventListener(FullScreenEvent.FULL_SCREEN, fullScreenRedraw);
As
this code shows, the event object for the fullScreen event
is an instance of the flash.events.FullScreenEvent class, which
includes a fullScreen property indicating whether
full-screen mode is enabled (true) or not (false).
When
Flash Player runs in a browser, all keyboard-related ActionScript,
such as keyboard events and text entry in TextField instances, is
disabled in full-screen mode. The exceptions (the keys that are
enabled) are:
Selected non-printing keys, specifically
the arrow keys, space bar, and tab key
Keyboard shortcuts that terminate full-screen mode: Esc (Windows
and Mac), Control-W (Windows), Command-W (Mac), and Alt-F4
These
restrictions are not present for SWF content running in the stand-alone Flash
Player or in AIR. AIR supports an interactive full-screen mode that
allows keyboard input.
You
can use the Stage class’s fullScreenSourceRect property
to set Flash Player or AIR to scale a specific region of the stage
to full-screen mode. Flash Player and AIR scale in hardware, if
available, using the graphics and video card on a user's computer,
and generally display content more quickly than software scaling.
To
take advantage of hardware scaling, you set the whole stage or part
of the stage to full-screen mode. The following ActionScript 3.0
code sets the whole stage to full-screen mode:
import flash.geom.*;
{
stage.fullScreenSourceRect = new Rectangle(0,0,320,240);
stage.displayState = StageDisplayState.FULL_SCREEN;
}
When this property is set to a valid rectangle
and the displayState property is set to full-screen
mode, Flash Player and AIR scale the specified area. The actual Stage
size in pixels within ActionScript does not change. Flash Player
and AIR enforce a minimum limit for the size of the rectangle to
accommodate the standard “Press Esc to exit full-screen mode” message.
This limit is usually around 260 by 30 pixels but can vary depending
on platform and Flash Player version.
To
enable scaling, set the fullScreenSourceRect property
to a rectangle object.
stage.fullScreenSourceRect = new Rectangle(0,0,320,240);
To
disable scaling, set the fullScreenSourceRect property
to null.
stage.fullScreenSourceRect = null;
To
take advantage of all hardware acceleration features with Flash
Player, enable it through the Flash Player Settings dialog box.
To load the dialog box, right-click (Windows) or Control-click (Mac)
inside Flash Player content in your browser. Select the Display
tab, which is the first tab, and click the checkbox: Enable hardware
acceleration.
Flash
Player 10 introduces two window modes, direct and GPU compositing, which
you can enable through the publish settings in the Flash authoring
tool. These modes are not supported in AIR. To take advantage of
these modes, you must enable hardware acceleration for Flash Player.
Direct
mode uses the fastest, most direct path to push graphics to the
screen, which is advantageous for video playback.
GPU Compositing
uses the graphics processing unit on the video card to accelerate
compositing. Video compositing is the process of layering multiple
images to create a single video image. When compositing is accelerated
with the GPU it can improve the performance of YUV conversion, color
correction, rotation or scaling, and blending. YUV conversion refers
to the color conversion of composite analog signals, which are used
for transmission, to the RGB (red, green, blue) color model that
video cameras and displays use. Using the GPU to accelerate compositing
reduces the memory and computational demands that are otherwise
placed on the CPU. It also results in smoother playback for standard-definition
video.
Be cautious in implementing these window modes. Using
GPU compositing can be expensive for memory and CPU resources. If
some operations (such as blend modes, filtering, clipping or masking)
cannot be carried out in the GPU, they are done by the software.
Adobe recommends limiting yourself to one SWF file per HTML page
when using these modes and you should not enable these modes for banners.
The Flash Test Movie facility does not use hardware acceleration
but you can use it through the Publish Preview option.
Setting
a frame rate in your SWF file that is higher than 60, the maximum
screen refresh rate, is useless. Setting the frame rate from 50
through 55 allows for dropped frames, which can occur for various
reasons from time to time.
Using direct mode requires Microsoft
DirectX 9 with VRAM 128 MB on Windows and OpenGL for Apple Macintosh,
Mac OS X v10.2 or higher. GPU compositing requires Microsoft DirectX
9 and Pixel Shader 2.0 support on Windows with 128 MB of VRAM. On
Mac OS X and Linux, GPU compositing requires OpenGL 1.5 and several
OpenGL extensions (framebuffer object, multitexture, shader objects, shading
language, fragment shader).
You can activate direct and gpu acceleration
modes on a per-SWF basis through the Flash Publish Settings dialog
box, using the Hardware Acceleration menu on the Flash tab. If you
choose None, the window mode reverts to default, transparent,
or opaque, as specified by the Window Mode setting
on the HTML tab. | http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS2E9C7F3B-6A7C-4c5d-8ADD-5B23446FBEEB.html | CC-MAIN-2014-15 | refinedweb | 1,477 | 63.39 |
. > > make install > [...] > ./perl installperl > /usr/local/bin is not writable by you > make: *** [install.perl] Error 2 > > The error message is located at this line in installperl : > -w $installbin || $nonono || die "$installbin is not writable by you\n" > > But I'm using 'ntea' and made some unsuccessful 'chmod a+w /usr/local/bin' > !! This is driving me crazy !! Call me crazy, but could this be another one of those Adminstrators group NTisms? (I sound like a broken record, I know, but I've been bitten by this thing many times) > I removed the line, and was able to install the perl binaries, libs and > headers (that also what I did before starting this whole discussion with you). > >. here... > ------------------------------- > 2) Perl Modules > > Still using binary mount but no 'binmode' in CYGWIN, I tried to build (did > you too ?) some Perl modules (like DB_File, String-CRC) in /usr/local/src > (which is binary mounted). These modules produce libraries (CRC.a from > CRC.xs -> CRC.c for example) and have to be statically linked to perl.exe, > thus producing a new perl.exe (this is handled automatically by issuing : > make -f Makefile.aperl inst_perl MAP_TARGET=perl.exe). > > - build fails, with that kind of messages : > /usr/local/lib/perl5/5.00502/cygwin32/CORE/cw32imp.h:343: warning: this is > the location of the previous definition > Nope, I didn't try this. I just wanted a basic build. > > meaning that cw32imp.h is included twice or more. Therefore, I disabled the > cw32imp.h inclusion from /usr/local/lib/perl5/00502/cygwin32/CORE/perl.h, > line 1242, and that fixed the problem. > > /* Work around some cygwin32 problems with importing global symbols */ > #if defined(CYGWIN32) && defined(DLLIMPORT) > /* > # include "cw32imp.h" > */ > #endif > > I know, this is really a dirty hack, did you notice the same problem, do > you think that it's worth a patch ? Let's investigate that problem.> > > administrateur [527] /usr/local/src/String-CRC-1.0$ cat > blib/arch/auto/String/CRC/extralibs.all > => it contains (34 bytes) the text '-L/usr/local/lib -ldb' surrounded by a > blank line and followed by many others. > > administrateur [526] /usr/local/src/String-CRC-1.0$ od -x > blib/arch/auto/String/CRC/extralibs.all > 0000000 2d0a 2f4c 7375 2f72 6f6c 6163 2f6c 696c > 0000020 2062 6c2d 6264 0a0d 0a0a 0a0a 0a0a 0a0a > 0000040 0a0a > 0000042 > >. | http://www.sourceware.org/ml/cygwin/1999-03/msg00217.html | CC-MAIN-2014-35 | refinedweb | 389 | 60.82 |
NAME
SYNOPSIS
DESCRIPTION
RETURN VALUE
SEE ALSO
pmem2_get_memmove_fn(), pmem2_get_memset_fn(), pmem2_get_memcpy_fn() - get a function that provides optimized copying to persistent memory
#include <libpmem2.h> typedef void *(*pmem2_memmove_fn)(void *pmemdest, const void *src, size_t len, unsigned flags); typedef void *(*pmem2_memcpy_fn)(void *pmemdest, const void *src, size_t len, unsigned flags); typedef void *(*pmem2_memset_fn)(void *pmemdest, int c, size_t len, unsigned flags); struct pmem2_map; pmem2_memmove_fn pmem2_get_memmove_fn(struct pmem2_map *map); pmem2_memset_fn pmem2_get_memset_fn(struct pmem2_map *map); pmem2_memcpy_fn pmem2_get_memcpy_fn(struct pmem2_map *map);
The pmem2_get_memmove_fn(), pmem2_get_memset_fn(), pmem2_get_memcpy_fn() functions return a pointer to a function responsible for efficient storing and flushing of data for mapping map.
pmem2_memmove_fn(), pmem2_memset_fn() and pmem2_memcpy_fn()2_persist_fn persist_fn = pmem2_get_persist_fn(map); persist_fn(dest, len);
is functionally equivalent to:
pmem2_memmove_fn memmove_fn = pmem2_get_memmove_fn(map); memmove_fn(dest, src, len, 0);
Unlike libc implementation, libpmem2 functions guarantee that if destination buffer address and length are 8 byte aligned then all stores will be performed using at least 8 byte store instructions. This means that a series of 8 byte stores followed by persist_fn can be safely replaced by a single memmove_fn call.
The flags argument of all of the above functions has the same meaning. It can be 0 or a bitwise OR of one or more of the following flags:
pmem2_memcpy_fn memcpy_fn = pmem2_get_memcpy_fn(map); pmem2_drain_fn drain_fn = pmem2_get_drain_fn(map); /* ... write several ranges to pmem ... */ memcpy_fn(pmemdest1, src1, len1, PMEM2_F_MEM_NODRAIN); memcpy_fn(pmemdest2, src2, len2, PMEM2_F_MEM_NODRAIN); /* ... */ /* wait for any pmem stores to drain from HW buffers */ drain_fn();
The remaining flags say how the operation should be done, and are merely hints.
PMEM2_F_MEM_NONTEMPORAL - Use non-temporal instructions. This flag is mutually exclusive with PMEM2_F_MEM_TEMPORAL. On x86_64 this flag is mutually exclusive with PMEM2_F_MEM_NOFLUSH.
PMEM2_F_MEM_TEMPORAL - Use temporal instructions. This flag is mutually exclusive with PMEM2_F_MEM_NONTEMPORAL.
PMEM2_F_MEM_WC - Use write combining mode. This flag is mutually exclusive with PMEM2_F_MEM_WB. On x86_64 this flag is mutually exclusive with PMEM2_F_MEM_NOFLUSH.
PMEM2_F_MEM_WB - Use write back mode. This flag is mutually exclusive with PMEM2_F_MEM_WC. On x86_64 this is an alias for PMEM2_F_MEM_TEMPORAL.
Using an invalid combination of flags has undefined behavior.
Without any of the above flags libpmem2 will try to guess the best strategy based on the data size. See PMEM_MOVNT_THRESHOLD description in libpmem2(7) for details.
The pmem2_get_memmove_fn(), pmem2_get_memset_fn(), pmem2_get_memcpy_fn() functions never return NULL.
They return the same function for the same mapping.
This means that it’s safe to cache their return values. However, these functions are very cheap (because their return values are precomputed), so caching may not be necessary.
If two (or more) mappings share the same pmem2_memmove_fn, pmem2_memset_fn, pmem2_memcpy_fn and they are adjacent to each other, it is safe to call these functions for a range spanning those mappings.
memcpy(3), memmove(3), memset(3), pmem2_get_drain_fn(3), pmem2_get_memcpy_fn(3), pmem2_get_memset_fn(3), pmem2_map_new(3), pmem2_get_persist_fn(3), libpmem2(7) and
The contents of this web site and the associated GitHub repositories are BSD-licensed open source. | https://pmem.io/pmdk/manpages/linux/master/libpmem2/pmem2_get_memmove_fn.3/ | CC-MAIN-2022-05 | refinedweb | 470 | 56.05 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.