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
This program list all files present in a directory/folder in which this executable file is present. For example if this executable file is present in C:\\TC\\BIN then it will lists all the files present in C:\\TC\\BIN. C programming code(Turbo C compiler only) #include <stdio.h> #include <conio.h> #include <dir.h> int main() { int done; struct ffblk a; printf("Press any key to view the files in the current directory\n"); getch(); done = findfirst("*.*",&a,0); while(!done) { printf("%s\n",a.ff_name); done = findnext(&a); } getch(); return 0; } Obviously you will get a different output when you will execute this file on your computer.
http://www.programmingsimplified.com/c-program-list-files-in-directory
CC-MAIN-2017-09
refinedweb
111
66.64
Anbox – Run Android Applications on any Linux System UBports’ Marius Gripsgård has announced the availability of a new project titled Anbox – which will allow its users to run Android applications on top of their current Linux Distros. Work in Progress Anbox is described by its creator as a container based approach to boot a fully functional Android OS on top of a Linux Distro. Right now though, it is limited to Ubuntu. The project utilizes Linux Containers technology to achieve this. Alongside this, it also promises an integration of every Android app into the existing desktop environment of your Linux distro. Thus making them seem like any other application. Additionally, Linux namespaces are used to isolate the Android operating system from the host. “Back in 2015 I started working on a prototype of what I call Anbox today. It was born out of the idea of putting Android into a simple container based on LXC and bridging relevant parts over to the host operating system while not allowing any access to real hardware or user data, said Simon Fels in the announcement.” To provide OpenGL ES for those Android apps that depend on it, Anbox seems to be borrowing pieces of code from the official Android emulator, which it uses to serialize the command stream that’s being sent over to the host machine to be mapped on existing OpenGL or OpenGL ES implementations. Devices Marius sent out a Google+ post as per which it appears, that Android apps will be implemented on various versions of the Ubuntu Phone devices maintained by UBPorts. The first device expected to get this support might be OnePlus One. However, they did point out that the project is still in its developmental stage. And early development stages means bugs and crashes should be expected. Download the application below and start using android apps on your linux machine
http://haxf4rall.com/2017/07/16/anbox-run-android-applications-on-any-linux-system/
CC-MAIN-2017-30
refinedweb
313
50.36
Agenda See also: IRC log <scribe> Scribe: Norm <scribe> ScribeNick: Norm Date: 02 May 2006 Next telcon: 9 May 2006 No regrets given Next scribe: Henry Approve minutes of last telcon -> Approved Approve today's agenda -> VQ takes NDW's action to announce namespaceState-48 Thank you, Vincent! <scribe> New message from Mark Nottingham -> VQ: Issue is currently on the some-day pile. Should we take it up again? <noah> BTW: Noah notes that the HTML agenda at has an erroneous <title>Agenda of 25 April 2006 TAG teleconference</title> DanC: I had an action but no longer recall what it was <noah> The header is correct: <h1>Agenda of 2 May 2006 TAG teleconference</h1> DanC: There's another well-known location thing related to access control in Flash ... Or, at least, I hear there is one. ... How would P3P work without a well-known location? TimBL: Here's how it should work: HTTP head should return a site-metadata header pointing to where to get the stuff DanC: Head and not options? TimBL: Options is web-dav ... Then you read the RDF that you got. <timbl_> HEAD to the / <timbl_> Metadata: /foo.rdf <timbl_> GET /foo.rdf I thought we were going to give this a standard name. The last "standard name" ever required. DanC: That's three round trips for the first access TimBL: Advantage is that you could put the metadata on any request. ... In foo.rdf, you'd get pointers to whatever you wanted Noah: Is this for typical access to a site, or is it just for crawlers? DanC: Current practice is to grab metadata (like /favicon) on every request Scribe observes some confusion about whether or not we're talking about access control here TimBL: When do people need access control? <DanC> (it's just that access control problem is likely more complex than the favico problem. though the favico situation is sorta tolerable, since the Link: header is deployed, to some extent, in that case) TimBL: A responsible JavaScript/Voice browser/etc. client can get the access control to find out if the resource is intended to be available to scripts from that domain TV: This may be easiest if we begin with non-executable content like CSS ... You can link to the CSS files on w3.org from your site, for example ... In the voice browser case, there are dialogs. You need to know if you can use the dialog from another site. So you need to know if it's ok to use and if use puts you at any risk. TimBL: I think there's a third one: even though you're allowed to use it, is it in fact confidential. Will the script that's using your credentials to get it leak it to the outside world. TV: Perhaps we should factor out the credentials. Are they on a per-use basis, or can the client hold onto them forever. TimBL: Whether you've got the rights to use it are covered by access control. The hairy thing is when a script written by one person is used by a second person to access data from a third person. ... In original in HTTP there was a method: thing and a public: thing to try to provide some information about what was public. <timbl_> Public: GET DanC: The use case that sticks in my mind is that American Airlines uses Fedex to ship. They're happy with fedex going into their site to get data, but they're not happy to have the public do it. TV: Fedex needs a token. TimBL: Tokens can be leaked so it's hard to control. TV: Everybody today is using tokens and timing them. Noah: The broader solutions are to use things like Kerberos. Fairly simple things can only be expected to go so far. Norm: So, would having site metadata help? DanC: There is already metadata, the question is do we want to do it better. ... I think you can no longer use some URIs because, for example, using /flash.xml may give scripts access to things ... Maybe we should advise that well-known locations involve trademarks <DanC> 1/2 ;-) Vincent: Should we separate access control and siteData-36? I'm not sure if Mark wants more progress on site metadata or simply on access control. <timbl_> b DanC: I'd love to review some solutions TimBL: Do you think the header idea is too difficult to roll out? DanC: Not hard, but round trips are the most expensive thing. Going from two to three is not something I can advise. Noah: Is it the number of round trips or the timing? ... I think what I'm hearing is that today the browser is going to hit both the data and the metadata (favicon). DanC: The P3P case is the screw case, you can't get the data until you have the access control. Noah: But in the non-P3P case, it sounds like I'm already doing two round trips. ack. one sec. Can someone scribe for me! I'm back. Sorry DanC: There's a link in the head that you can avoid the well-known location Norm: Yes, if you have the link, the request for the well-known location is not made Noah: Isn't the status quo two round trips anyway? DanC: Well, the headers <noah> From Wikipedia: <noah> <link rel="icon" href="" type="image/x-icon" /> <noah> <link rel="shortcut icon" href="" type="image/x-icon" /> <DanC> NDW reports 1st-hand experience making /favico.ico 404s go away by use of <link rel="icon" ... /> <noah> See: DanC: I can answer Mark and say we're noodling on it, if you have any ideas, let us know. TimBL: Are we noodling on it? What are we going to do? DanC: I can see some options and I don't know which ones are better than the others TimBL: We should collect some use-case scenarios and then see how they play out. DanC: Are you volunteering? TimBL: Nope, I think we should co-opt Mark NOTE TO SCRIBE, CLEAN THAT UP Maybe we can get some discussion going on www-tag <DanC> (for the record, you just continue my action.) VQ: What to do about actions? DanC: If there's a draft he was working on, I'd like a pointer <DanC> ah... <- DanC: With that pointer, I'm happy to drop his action VQ: I suggest we drop his action. Any objections? <scribe> Dropped. VQ: I'll drop it and make sure we don't lose the link to what Tim did. The action to DanC is continued <noah> See note I just sent at: VQ: For the rest of the agenda, I tried to make an update on the draft findings <noah> Gives status of (non)progress on metadataInURI and schemeProtocols VQ: When we discussed this last month, we were expecting to make progress by the end of April Noah: I promised I'd be done, but I haven't finished yet. ... I'll try real hard for two weeks from now, definitely three. ... A few minutes review might be useful. ... Recently, we've had a couple of emails, especially from Roy <noah> Roy's email: <noah> I had used as an example: <noah> Infer: Noah: I said, look, I think people who read this URI on the side of a bus infer that this is about chapter 2 of a book and that the obvious edit would give us chapter 1 ... There's no absolute gaurantee that this works unless the provider has made that promise. <timbl_> identifier vs metadata Noah: Roy said you're conflating the identifier with the metadata <timbl_> connected question is semantics on identifier Noah: I'm guessing that this thing lives in a structured world and has siblings and that is metadata TimBL: I've heard this discussed under the rubric "semantics of identifiers" Noah: I'm not sure it's decidable whether I did this for one reason or another. <DanC> (this always reminds me of 4th grade English grammar class where we learned when to use "which" vs "that". ) Noah: People infer connections in a way that wouldn't come up with UUIDs, whether it's named by chapter numbers or chapter titles. TV: People are able to infer things from titles or names that they wouldn't be able to infer from UUIDs HT: Any story that doesn't make note of the redundancy of human-readable URIs is missing something Noah: Is it metadata? <DanC> (why do we care whether it's "metadata" or not? the point is that it's redundant and hence enhances reliability.) TV: I don't know, but it's useful information. <DanC> (oh.) HT: The other property that readable URIs have that UUIDs don't is that I am able to determine whether or not I think I got the right thing back. Noah: It's useful to name things in ways that promote certain kinds of inference. ... I tried that and got back "bad example, that's not what we mean by metadata" <DanC> (interesting point about surprise or not; I make it a habit to quote other stuff along with a URI so that the consumer can treat the URI as completely opaque and use the _other_ stuff in my citation to confirm that they got to the right place.) Noah: One case is where I structure the identifier itself to promote certain kinds of inference. ... To me it makes sense to go there. ... I think it's commonly what we see; even the .jpg case is like that, even though we want to warn people that you can't rely on that. ... If I've warranted something about an identifier, then you can rely on it. But even if I don't warrant it, you can be in the realm of guessing and find useful stuff. ... Suppose I'm a publisher. I can just makeup opaque IDs. TV said, no you're losing something when you do that. There's no gaurantee, but it's useful. ... So the question is, to what extent do you want to describe this to resource owners. <Zakim> DanC, you wanted to reiterate a point about freedom of choice and how it's constrained by dictionaries and encyclopedias whether people like it or not <DanC> Discussion of chapter3 vs. "chapter title" <DanC> no, norm, both of those are restrictive. Scribe believed that's what was being discussed DanC: It might be nice to say "before you pick a URI that's based on the title, consider that you might want to change the title without breaking everyone's links" Noah: I'll see if I can come up with a story for the next draft VQ: This is for Noah again. Noah: I don't think we ever agreed to publish anything on this topic Norm: I still need to tidy up the loose ends with Jonathan Norm will be prepared to give an updated status report next week HT: The bug is still bumping along the bottom ... I'll get back to it next month. DanC: I reported something the XQuery names -> Norm: There's a bug in the QT bugzilla to fix that, to make the "/" go away. That will happen on the next round of publication. <DanC> That's the address of the compare function. DanC: The extra slash is a bug, right? Norm: Yes <noah> Would you get back RDDL or regular HTML? <DanC> GET /2005/xpath-functions <DanC> id="compare" You'll get HTML back, probably with RDDL in it. <noah> Thanks. DanC: From one set of specs you'll learn that that URI identifies an HTML element. ... You'll also be able to determine that it identifies an XQuery function. ... So it identifies both, or the URI is ambiguous, or... Noah: This came up in SOAP. There was a side discussion just like this. Does the fragment identify the documentation subsection or the artifact. ... I'm puzzled about why that ambiguity is either not there or is benign. DanC: I think it's darned useful. That is, it's useful to have a URI for the compare function because I want to use it. And it's nice when I can stick it in a browser and see the right thing. ... I'm trying to figure out how to wedge this into web architecture. Noah: The other thing is whether we do connect to get back RDF or RDDL> TimBL: My model of this originally was that the semantics of the fragid is determined by the content type. ... So if you do conneg then you have to be careful that the fragids all mean the same thing. <DanC> (indeed, my wedge involves changing the XHTML media type to say that authors can "opt out" of the section-of-the-document meaning) TimBL: I don't believe that the query function is an anchor, those are distinct ideas. ... Either we say that really identifies the function and the HTML display is some sort of fallback. I think that's weak because of the huge amount of HTML that's out there. ... If you put an rdf:ID on the node instead of an xml:id, then it would be reasonable to say that that identifies the concept not the element <noah> So, this seems to sort of work if the RDF is in the documentation page, but not if the RDF is standalone, right? TimBL: You could build completely consistent documents this way. <noah> Furthermore, it sort of implies that we don't have a first class name for the function itself (or it's a different name we haven't yet discussed.) TimBL: There's a push to put RDF in HTML so the ability to have both in the same document may be reasonable. Norm: Do I put both rdf:ID and xml:id, or is rdf:ID supposed to move the browser display? TimBL: If you give a URI that identifies something with the rdf:ID, then the browser should switch to a "data view" DanC: That undercuts everything I said before TimBL: It's very hairy to tie these things together in a good way DanC: Only philosophically. ... We should find some way to explain what's actually going on TimBL: If you don't fix it philosophically, then the TAG just has to clean up all the corner cases later one. DanC: that's really cheap compared to asking every web document to change <Zakim> noah, you wanted to discuss resources and representations Noah: To me, the questionable part of the architecture is secondary vs. primary resources. I think it'd be easier to say that the resource is the function and the page you get back is a representation of it. ... In the case of secondary resources, the story has a lot of texture, but it smacks of when there is a primary resource, the secondary resource is grounded in that representation. ... Now it seems like we're struggling to say how we exract the abstract thing <ht> Everybody get dropped? No :-/ <ht> Weird, I can't hear anyone -- will try again Broader discussion of primary vs. secondary resources Noah: We seem to have different web mechanisms available for what we call primary and secondary resources ... Partly I'm not 100% happy with where we landed on the namespace document. ... I don't tend to think of a namespace as a document, for example. I can ask questions about the document that don't make sense about the collection of names. TimBL: You're not happy with the namespace URI identifying the namespace document. Noah: Yes. ... On a common-sense way, I'd like to say that the namespace (which may be an information resource) and the namespace document are different things. ... I'm not convinced that that's a better place to be <Zakim> ht, you wanted to wonder about context of use HT: I was opposed to this in the httpRange-14 discussion, but maybe it's the right answer here. ... Taking as a starting point that there's something right about current practice, let's make a story that explains current use. ... These things are ambiguous (that is, URIs with fragids in namespace documents). It's context of use which determines which of those you're talking about. <timbl_> I believe "use disambiguates" works fine in natural langauge and leads to a hopeless mess in logic. <noah> To be clear: I'm OK with the HTML or RDDL coming back as a representation of the namespace resource -- the tougher question is whether the resource itself is the documentation, or the namespace itself. I'm a bit on the fence, but still inclined (unlike Tim) to view it as the namespace itself. <noah> By the way, I think the namespace is an information resource, but it's not quite the same as the info resource that is the documentation about the resource. HT: If it's in an HTML anchor, it's the document, if it's somewhere else, it's the resource. ... We don't have a place to talk about that in the architecture, but maybe we need to think about going there. TV: Why is the fragment identifier there? ... I have a protocal, then a host, then a whole bunch of hierarchical structure. ... In the HTML case, the fragid took you to a place in the document ... CGI did it in a completely different way. If I had a/b/c/d, then if "b" was executable, c/d got passed to "b" ... HTML forms never leveraged that structure, but the advantage is that you didn't have to have a different identifier on the client and the server. ... Maybe "#" was a mistake. Maybe we should have said "myhomepage.html/chapter1" and who cares if chapter1 is a section or a separate file. ... the "#" is a sort of wart that was there for jumping to IDs. ... Any time you have a special case like that, there will be lots of corner cases. ... I'm not saying that we should remove "#" but we should think about how we might "do it right" ... For a lot of cases, there's no reason to distinguish between the client and server side. DanC: The client and server could work it out TV: That would also give you an interesting way of allowing the mobile space to different things with the same URIs. Noah: Let's say you did that. Now, how does the client know how to act on the hierarchical URI? ... If you knew the media type of the document returned, then you might now. But that raises complications because it ties the resolution to the interpretation of another representaiton. <DanC> (wierd post-hoc answer to "maybe # was a mistake" is: well, nothing stopped anybody from undoing the mistake ala TV's thought experiment, and they didn't, so maybe # wasn't a mistake.) Noah: There's the possibility, for example, that fragments of different sizes might be in different media types VQ: We need to stop here, but we can discuss this further next week <DanC> (we did access control, to my satsifaction) <noah> Um, I'm not at all sure # was a mistake, but good or bad it's pretty well baked into HTML and browsers. I don't think we can infer a lot from the fact that most of us are still using # to name HTML fragments, except that it's what works. Adjourned This is scribe.perl Revision: 1.127 of Date: 2005/08/16 15:12:03 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/todays'/today's/ Succeeded: s/public/available to scripts from that domain/ Succeeded: s/reserved names/well-known locations/ Succeeded: s/From wikipedia/From Wikipedia/ Succeeded: s/usfeul/useful information/ Succeeded: s/infernece/inference/ Succeeded: s/represntation/representation/ Succeeded: s/BTW:/By the way,/ Succeeded: s/exmaple/example/ Found Scribe: Norm Inferring ScribeNick: Norm Found ScribeNick: Norm Present: Ed T.V. Vincent Norm Henry Noah Dan Tim Regrets: Dave Agenda: Found Date: 2 May 2006 Guessing minutes URL: People with action items: WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output]
https://www.w3.org/2006/05/02-tagmem-minutes
CC-MAIN-2021-31
refinedweb
3,401
69.92
C++ Pointer to an ArrayPritesh C++ Pointer to an Array : #include <iostream> using namespace std; int main () { // an array with 5 elements. double arr[5] = {10,20,30,40,50}; double *ptr; ptr = arr; // output each array element's value cout << "Print Array Elements : " << endl; for ( int i = 0; i < 5; i++ ) { cout << "*(ptr + " << i << ") : "; cout << *(ptr + i) << endl; } return 0; } Output : Print Array Elements : *(ptr + 0) : 10 *(ptr + 1) : 20 *(ptr + 2) : 30 *(ptr + 3) : 40 *(ptr + 4) : 50 Pictorial representation of the array is shown below – Explanation : - In the above example we have printed the elements of the array using the pointer. - Pointer is special type of variable which stores the address of the variable. - The base address of the array is assigned to the pointer variable using following statement. ptr = arr; Now consider the program in which we have assigned the starting address of array to pointer variable. Now we know that starting address of array is nothing but the address of first element Main Logic behind Calculation : Consider that we need to calculate the value of *(ptr + 4). It can be evaluated as – *(ptr + 4) = Value at (ptr + 4) = Value at (ptr + 4 * Size of Data Type) = Value at (ptr + 4 * 4) = Value at (ptr + 16) = Value at (1000 + 16) = Value at (1016) = 50 In the above calculation we have added 4 to pointer variable. Why we multiplied 4 with size of data type ? See Re-commanded article
http://www.c4learn.com/cplusplus/cpp-pointer-array/
CC-MAIN-2019-39
refinedweb
242
53.44
> Sorry for being picky, but while your derivative factory > function follows the mathematical definition, it is not the > "best" way to do it numerically. The preferred way is: > > def derivative(f): > """ > Factory function: accepts a function, returns a closure > """ > def df(x, h=1e-8): > return (f(x + h/2) - f(x - h/2))/h > return df > > This is best seen by doing a graph (say a parabola) and drawing > the derivative with a large "h" using both methods near a local > minimum. > > André Hey good to know André and thanks for being picky. Fresh from yesterday's example, I posted something about *integration* to a community college math teacher list last night, which I think is maybe closer to your better way (which I hadn't seen yet). === def integrate(f,a,b,h=1e-3): """ Definite integral with discrete h Accepts whatever function f, runs x from a to b using increments h """ x = a sum = 0 while x <= b: sum += h*(f(x-h)+f(x+h))/2.0 # average f(x)*h x += h return sum >>> def g(x): return pow(x,2) # so this is what we want to investigate >>> integrate(g,0,3,h=1e-4) # h = 0.0001, close to 9 8.9995500350040558 >>> integrate(f,0,3,h=1e-6) # h = 0.000001, even closer to 9 8.9999954998916039 def defintegral(intexp, a, b): return intexp(b) - intexp(a) >>> def intg(x): return (1./3)*pow(x,3) # limit function >>> defintegral(intg, 0, 3) # exactly 9 9.0 === The post (which includes the above but is longer) hasn't showed up in the Math Forum archives yet, or I'd add a link for the record. Maybe later. Kirby
https://mail.python.org/pipermail/edu-sig/2005-March/004593.html
CC-MAIN-2016-30
refinedweb
286
60.65
quick ellie setup for playing with json decoders A few examples that are interesting for visualization a dagre graph layout with mini map and neibor highlighting list of graph visualization libs popto.js seemed very interesting. the filtering may be usefule to model on, however it seems very tied to neo4j which has licensing issues. wine and cheese is a very good demo of what cytoscape.js is capable of. Planning to look at lunr.js and text search provided in this example Generally while pacer is mostly a joy to use to manipulate graphs and prototype things it has not had any updates in about a year and I fear it may be dead. Gremlin looks ok on the surface but in practice using the groovy repl seems extra painful and the syntax is a bit obtuse. Tinkergraph is fast when using indexes and pacer, however it does not support transactions which makes some multithreading tasks very hard. if you know the id or can infer it you can make pacer go quite a lot faster. using pacer’s bulk_job also helps with thread safety a bit. cytoscape has a java application and a javascript library. Both assume you know enough about your graph to filter it before you view it. I needed something that lets me explore a graph without loading the whole thing. I decided to use the cytoscape.js library for this. linkurious.js has a very nice interface, but it is a “service” and they want money :( Cayley seems to have created lots of buzz but it all seems very golang specific. The server fell over quite quickly when trying to use httppoison and elixir spawned processes to load data. Seems that loading requires me to drop into go, or to write out nquads. nquads are also hard to conceptualize alongside a property graph. There may be some great perf benefits but the overhead to understnad them preveneted me from digging in. the UI provided by cayley is oddly d3 for query shape and sigma for results. It has limited interactivity and control over style. I found this helpful: [] pacer table of what returns an enum pacer rubydocs for subgraph import Html exposing (text,div,br) import Json.Encode import Markdown type alias R = List(String,String) t = ("a","b") r = [t,t] s = "foo" enc = encPair t encPair : (String,String) -> Json.Encode.Value encPair r = let (a,b) = r in Json.Encode.object [(a, Json.Encode.string b)] encLst : R -> Json.Encode.Value encLst lst = List.map (\x -> encPair x) lst |> Json.Encode.list jMark : String -> String jMark s = "\n\n```" ++ s ++ "```" main = div [] [ text <| "Json Encoding" , Markdown.toHtml [] (jMark (Json.Encode.encode 2 enc)) , br [] [] , Markdown.toHtml [] (jMark (Json.Encode.encode 2 (encLst r))) ] import Html exposing (text, p) import Html.Attributes exposing (..) main = p [ contenteditable True ][ text "Hello, World! click to edit" ] import Html exposing (..) import Html.App as App import Html.Attributes exposing (..) import Html.Events exposing (..) import Http import Json.Decode as Json import Task main = App.program { init = init "cats" , view = view , update = update , subscriptions = subscriptions } -- Parent Stuff -- MODEL type alias Model = { topic : String , gifUrl : String , child : ChildModel } init : String -> (Model, Cmd Msg) init topic = let childMsg = childGet in ( Model topic "waiting.gif" child_init , Cmd.batch [getRandomGif topic, Cmd.map ChildProxy childGet] ) -- UPDATE type Msg = MorePlease | FetchSucceed String | FetchFail Http.Error | ChildGet | ChildProxy ChildMsg update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of MorePlease -> (model, getRandomGif model.topic) FetchSucceed newUrl -> ({model | gifUrl = newUrl}, Cmd.none) FetchFail _ -> (model, Cmd.none) ChildGet -> let cmd = childGet mapped_cmd = Cmd.map (\x -> ChildProxy x) cmd in (model, mapped_cmd) ChildProxy proxy_msg -> let (child_model, child_msg) = child_update proxy_msg model.child in ({model | child = child_model}, Cmd.none) -- VIEW view : Model -> Html Msg view model = let child_stuff = App.map (\x -> ChildProxy x) (child_view model.child) --child_stuff = App.map (\x -> x) (child_view model.child) in div [] [ h2 [] [text model.topic] , button [ onClick MorePlease ] [ text "More Cats!" ] , button [ onClick ChildGet ] [ text "More Coffee!" ] , br [] [] , img [src model.gifUrl] [] , child_stuff ] -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- HTTP getRandomGif : String -> Cmd Msg getRandomGif topic = let url = "" ++ topic in Task.perform FetchFail FetchSucceed (Http.get decodeGifUrl url) -- Child Stuff --Model type alias ChildModel = {txt : String, gifUrl : String} child_init : ChildModel child_init = {txt = "init", gifUrl = "waiting.gif"} --Update type ChildMsg = Go | Win String | Fail Http.Error child_update : ChildMsg -> ChildModel -> (ChildModel,Cmd Msg) child_update msg model = case msg of Go -> let --cmd = Task... x = 1 in --(model, cmd) (model, Cmd.none) Win newUrl -> ({model | txt = "won", gifUrl = newUrl}, Cmd.none) Fail _ -> ({model | txt = "did not win"}, Cmd.none) --View child_view : ChildModel -> Html ChildMsg child_view model = div [] [ text <| "Child: " ++ model.txt , hr [] [] , text <| "Url: " ++ model.gifUrl , br [] [] , img [src model.gifUrl] [] ] --HTTP childGet : Cmd ChildMsg childGet = Task.perform Fail Win (Http.get decodeGifUrl "") -- Shared Stuff decodeGifUrl : Json.Decoder String decodeGifUrl = Json.at ["data", "image_url"] Json.string import Html exposing (text,div,hr) import Json.Decode --| this is our test json string. it uses """ syntax for multi line strings jsonString = """ [ { "key" : "bar" } ] """ --| This is for our json object type alias type alias LstItem = {key: String} --| This alias defines a simple list of json objects [{"key":"value"}] type alias Lst = List LstItem --| this defines a decoder for the Json objects in our list. decoder = Json.Decode.object1 LstItem (Json.Decode.at ["key"] Json.Decode.string) --| This defines a decoder function to process a list decodeLst : Json.Decode.Decoder Lst decodeLst = Json.Decode.list decoder --| this function actually runs the decoder and produces a Result doDecodeLst : Json.Decode.Decoder a -> String -> Result String a doDecodeLst decodeLst raw_string = Json.Decode.decodeString decodeLst raw_string --| this one runs the decoder and processes the Result into an empty list or --| the decoded list and disregards any errors maybeDecodeLst : Json.Decode.Decoder (List LstItem) -> String -> List LstItem maybeDecodeLst decodeLst raw_string = case Json.Decode.decodeString decodeLst raw_string of Err str -> [] Ok lst -> lst --| the main program, in this case a view. main = div [] [ text "decoding json" , text "the first version creates a result: " , text <| toString (doDecodeLst decodeLst jsonString) , hr [] [] , text "the second version creates a record: " , text <| toString (maybeDecodeLst decodeLst jsonString) , hr [] [] , text "the third version creates an error by using the wrong decoder: " , text <| toString (doDecodeLst decoder jsonString) ] - recursion and unnesting import Html exposing (text,div,hr) import Dict import String main = let unnested = unnest p Dict.empty "" path = [":parent","child1"] pathString = String.join ":" path found = Dict.get pathString unnested updated = if found == Nothing then False else True in div [] [ text "Recurse! ->" , text (toString p) , hr [] [] , text "Unnest! ->" , text (toString unnested) , hr [] [] , text <| " path string: " ++ pathString ++ " ... " , text (toString found) , hr [] [] , text <| " updated: " ++ (toString updated) ] --unnest : Response -> String unnest : Response -> Dict.Dict String Response -> String -> Dict.Dict String Response unnest comment dict path = case comment of NoChild rec -> dict ParentResponse rec -> let newPath = path ++ ":" ++ rec.name newDict = Dict.insert newPath comment dict com = rec.response in unnest com newDict newPath nest : Dict.Dict String Response -> Response nest dict = p type Response = ParentResponse { name : String , b : Bool , s : String , response : Response } | NoChild { name : String , b : Bool , s : String , response : Bool } p : Response p = ParentResponse { name = "parent" , b = False , s = "" , response = c1 } c1 : Response c1 = ParentResponse { name = "child1" , b = False , s = "" , response = c2 } c2 : Response c2 = ParentResponse { name = "child2" , b = False , s = "" , response = c3 } c3 : Response c3 = ParentResponse { name = "child3" , b = False , s = "" , response = c4 } c4 : Response c4 = NoChild { name = "child" , b = False , s = "" , response = True } and… import Html exposing (text,div,hr) import Dict main = div [] [ text ("Hello, World!" ++ (toString record) ++ (toString dict)) , hr [] [] --, text (toString (recIt record)) , text (toString (recIt record)) , hr [] [] , text "Tuples: " , text (toString tpls) , hr [] [] , text "put_in: " --, text (toString (put_in tpls)) , text (toString (put_in list3d ["name", "name2"])) , text "todo: you were going to try to pattern match out a match on your update of the nested path" ] record = { foo = ("String","foo") ,bar = {t = "Int",v = "1"} } record2 = { nofoo = {t = "Bool", v = "True"} } -- name, type, value tpls = [ ( "foo", "Bool", "True") --, ( "bar", "List", -- ("baz", "Bool", "False") -- ) ] niltpl = ("foo", "String", ("","","string var")) nesttpl = ("bar", "Nest", ("baz", "String", " nested var")) moretpls = [ niltpl , nesttpl ] type alias Item = (String, String, String) type alias ItemList = (String, String, Item) type alias SuperItem = (String, String, MaybeString) --type Thing = Item | ItemList type MaybeString = String | Item type alias ThreeDeep = ( String, String, ( String, String, ( String, String, String) ) ) threedeep = ("name", "type", ("name2", "type", ("", "value depth2", "") ) ) threedeep2 = ("name", "type", ("name2", "type", ("name3", "type", "value depth 3") ) ) threedeep3 = ("name", "type", ("", "value depth 1", ("", "", "") ) ) list3d = [ threedeep, threedeep2, threedeep3 ] put_in : List ThreeDeep -> List String -> List String put_in lst path = --["foo"] let -- map list to find first path map x = 1 in -- return something ["foo"] --put_in : List SuperItem -> List String -> List String --put_in tpl names = --["foo"] --recFun : dict = Dict.fromList [ ("key", { name = "foo"}) , ("key2", { name = "1"}) , ("key", { name = "same key"}) ] type Splay = A | B splay : Splay -> String splay input = case input of A -> "out" B -> "out2" recIt record = case record of {foo} -> {hasFoo = True} --{foo, bar} -> {hasFoo = False} please ignore my code rage’ed profile name [elixir1.2@stink rel]$ aws iam get-user --profile fuckyou A client error (AccessDenied) occurred when calling the GetUser operation: User: arn:aws:iam::[REDACTED]:user/[REDACTED] is not authorized to perform: iam:GetUser on resource: arn:aws:iam::[REDACTED]:user/[REDACTED] I recently made a terrible assumption that source ~/.bashrc would actally clean out old env varriables. This lead to 20 minutes of going down the wrong path to try to troubleshoot why my aws cli was getting a permission denied. Lots of time could have been solved via the magical whoami command the above command essentially uses the calling api to fetch the arn and tries to get info about it. I found this post very helpful in getting phoenix 1.2 working with react: I was unable to get bower working, and followed the above blogs instruction wiht some success. Hope i get time to do an update. I added the following to get reflux working. I have to include everythign everywhere, not sure why. npm install --save reflux bootstrap I bought this esata device: I was dissapointed to find my machine completely puked when i hooked it up. After hours of research I discovered a bunch of posts saying it was not possible so I gave up. In the search of a card that would provide this function I found this card which seemed cheap and ready to work. Reading the reviews I saw a trend of people pissed off about going off to have to download the driver. The driver in the page here was called asmedia106x… so i figured if it worked for their card, I might as well try it since I had a asmedia 1061 controller in my motherboard. After a reboot or two it was working like a charm! Moral of the story: esata connectivity sucks for older controllers, but it apparently is all in the driver. This quick tutorial has only been tested with the following component versions. Beware trying to get this working with other versions. Phoenix is not yet 1.0 and it may change enough to make this no longer work. Git Repo: [] Elixir 1.05 and Phoenix 0.16.1 components: Bower components for reflux 0.2.7, react 0.13.3 The first post described how to use react.js and reflux to coordinate react components. This post will describe how to wire in server state through phoenix sockets. The great thing about this approach is that you largely remove the drudgery of creating a REST CRUD api, and just send json down to your javascript as events. The dataflow is in one direction, which simplifies our design. To demonstrate this we will be adding a few key components. The first will be an Elixir Agent to hold our state. The second will be to integrate our Reflux store with Phoenix sockets. We will track clicks to our buttons, and who’s using the system. shows the basic flow of data. An elixir agent is essentially a server process that will hold state in memory. It can leverage supervision, and be run as an application. The Elixir docs for Agent can be found here. Our agent will provide functions to: I also subbed out broadcasting and messages, which we will ignore for now. our start_link function initializes our state. In this case it is simply a map with default attributes: an empty list for users, a zero user count, an empty list for messages, and a zero count for hits. We simply pass a function which returns the map, and a name, which gets compiled to the module name Elixir.LogAgent or in Elixir just LogAgent. def start_link do map = %{users: [],user_count: 0, msgs: [],hits: 0} Agent.start_link(fn -> map end, name: __MODULE__) end Def simply calls Agent.get with our module name, and it uses function shorthand, or partial application to return the state. def get_user_count do Agent.get(__MODULE__,&Map.fetch(&1,:user_count)) end We could also write this more verbose def get do Agent.get(__MODULE__,fn(state) -> # last arg is returned state end) end This grabs a user and puts it into our state map. One flaw to be fixed here is the fact that we don’t check to see if the user is already logged in. I If you are unfamiliar with Elixir or Erlang, the syntax for adding a user to our list may be confusing. This is called a “cons cell”, and it allows you to reference a list as a head and a tail. When used on the left side of “=” it interpolates the first element of a list into the variable on the left of the “|”, and the rest of the list to the right. [head|tail] = [1,2,3,4,5] head is now 1, and tail is now [2,3,4,5]. this is because “=” is not an assignment operator like most languages, but a pattern match. When used on the right side of “=”, or bare you prepend head to your list. # bare iex(7)> element = 1 1 iex(8)> list = [2,3,4] [2, 3, 4] iex(9)> [element|list] [1, 2, 3, 4] # right side of "=" iex(10)> list = [1|[1,2,3]] [1, 1, 2, 3] Back to our Agent… def login(user) do # get the current state s = get() # increment our user counter new_state = Map.put(s,:user_count,s.user_count + 1) IO.puts inspect new_state # add our user to our users list new_state = Map.put(new_state,:users,[user|new_state.users]) IO.puts inspect new_state # store the update Agent.update(__MODULE__,fn state -> new_state end) # stub to broadcast a change event bcast end The rest of the agent is pretty straight forward if you understand the partial application syntax. Step one here is to look at our endpoint, and ensure we have our sockets mapped correctly. lib/reflux_eventbroker_react_phoenix_elixir/endpoint.ex defmodule RefluxEventbrokerReactPhoenixElixir.Endpoint do use Phoenix.Endpoint, otp_app: :reflux_eventbroker_react_phoenix_elixir # commenting this out caused me all kinds of problems. Seems to be some leftover assumptions this exists. socket "/socket", RefluxEventbrokerReactPhoenixElixir.UserSocket # this plumbs our socket path to our Socket functions in web/channels/pub_chat_socket.ex socket "/status",Reflux.PubChatSocket # SNIP web/channels/pub_chat_socket.ex Phoenix web sockets break things into sockets and channels. Sockets allow you to manage connections and authenticate a particular websocket path. They also allow you to manage the transport. defmodule Reflux.PubChatSocket do require Logger use Phoenix.Socket # Defines our channel name, and what Elixir module will be used to control it, PubChannel in this case channel "all",PubChannel # Defines the transport, and if we need to check the host origin. Check origin is useful if you want to limit access to your sockets to certain hosts transport :websocket, Phoenix.Transports.WebSocket, check_origin: false # connect parses our connection parameters from our client. using phoenix.js this is socket.connect(params); # we also use Phoenix.Socket.assign/3 to embed our user and pass into the socket struct, which gets passed along to out channel. def connect(params, socket) do Logger.info "PARAMS: \n " <> inspect params socket = assign(socket, :user, params["user"]) socket = assign(socket, :pass, params["pass"]) {:ok,socket} end # id allows us to broadcast to all users with a particular id. I'm not using this in this revision. def id(socket) do Logger.info("id called" <> inspect socket, pretty: true) "users_socket:#{socket.assigns.user}" end end So now we have our channel “all” mapped to our channel logic. web/channels/pub_channel.ex Channels use the behaviour pattern. Behaviours allow us structure and composition. They are most heavily used in OTP patterns like GenServer. Behaviours generally lean heavily on pattern matching in function definition, which is worth of discussion for folks new to Elixir. Take the following definitions defmodule Foo do #1 def bar(:atom) do "got an atom" end #2 def bar({a,b}) do "got a 2 tuple with variables a and b assigned the arg's tuple values" end #3 def bar(%{foo: foo} = arg) do "got a map with a key of :foo, interpolated into the variable 'foo', and the full map assigned to 'arg'" end #4 def bar(%{"foo" => foo} = arg) do "foo key was a binary" end #5 def bar(any) do any end end Elixir will take any call to Foo.bar(arg) and try to see if the argument fits a definition. This works top to bottom. The last case #5 will match any call to Foo.bar/1. Having a catch all can be useful in debugging to detect and crash when you have unexpected input. Example #1 will only match for Foo.bar(:atom). Example #2 will only match a 2 element tuple. Example #3 is much more interesting and powerful. Elixir map pattern matching allows you to look inside the argument and use different function definitions based on the keys of the map. In this case we will only match #3 if we use a map as an argument, and that map has a key of :foo. If we want access to the rest of the map we can use the arg variable. We can pass any map containing the key :foo %{foo: 1,bar: 2} will match, but %{“foo” => 1} will match #4 because the key is a binary (string). When you are serializing data to javascript it is best to use binaries as strings. Binaries also have very powerful pattern matching capabilities you may wan to explore. For phoenix channels we need join/3, and handle_in at a minimum. def join("all",payload,socket) do # socket.assigns.user is assigned in our Socket user = socket.assigns.user # register the login event with our Agent LogAgent.login(user) Logger.info "User #{user} logged in: payload: #{inspect p}" # we can't broadcast from here so we call to handle_info send self,:status_update # return ok, and a "welcome" message to the client joining {:ok,"welcome",socket} end In this commit I have a defunct catchall def join, below I’ve fixed it to catch any joins with the wrong channel name. We could provide additional authentication checks in our first def join, and catch issues here. def join(any,s,socket) do Logger.error("unkown channel: #{inspect any} for assigns #{inspect socket.assigns}") {:error, %{reason: "unauthorized"}} end Next is handle_info which broadcasts to all clients who have joined our “all” channel def handle_info(:status_update,socket) do Logger.info "handle_info :status_update" # broadcase!/3 sends an event "status_users" with the current state from our LogAgent # it wouldn't be a bad idea to throttle this for a large number of clients broadcast! socket, "status_users", LogAgent.get # we don't need a reply since we just used broadcast {:noreply, socket} end I have added a few events in a number of handle_in/3 definitions. :status_update, “status_users”,”ping”,”hit”, and any_event They all work pretty much the same, any_event is a catchall for errors. Hit does the most work for our use case. Notable here is the use of send. This is generically the way Elixir processes communicate between each other. In this case we use self() which returns the current PID, and matches to def handle_info(:status_update,socket). You can read more about send here def handle_in("hit",p,socket) do Logger.info "Hit from #{socket.assigns.user}" # update our state LogAgent.hit # call the broadcast for all connected users send self,:status_update {:noreply,socket} end Finally for our Channel we need to handle clients leaving. We define terminate/2 to update our state and user count def terminate(reason,socket) do # this test for assigns.user should never happen if our socket is doing it's job if socket.assigns.user != nil, do: LogAgent.logout(socket.assigns.user) Logger.info("terminated: #{inspect socket.assigns}") # I added this because I had some client terminations not notify, need to dig into why. The messaging should # be asynchronus, so there is a chance the state is not updated when we call :status_update :timer.sleep(50) # broadcast to all connected clients send self,:status_update :ok end Now that we have our server all wired up to talk to clients, we can dig into the client code. Reflux will be managing all data from the server, and the react components will send their updates to the server which end up propagating back down to reflux to update our state. First we add a new action called “hit” export default Reflux.createActions([ "swap", "hit" ]); Next we update our reflux store to connect to phoenix web/static/js/stores/TheStore.js import Actions from "../Actions"; export default Reflux.createStore({ // binds our onSwap and onHit functions listenables: Actions, init() { this.test = true; // no logging //this.socket = new Phoenix.Socket("/status") // This creates our socket and sets up logging as an option this.socket = new Phoenix.Socket("/status",{logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }}) // lazily create a semi unique username var r = Math.floor((Math.random() * 1000) + 1); this.me = "me"+r // these are our auth params which get sent to both connect/2 in our phoenix socket and join/3 in our phoenix channel this.auth = {user: this.me,pass: "the magic word"} // this maps our params to our socket object this.socket.connect(this.auth) // callbacks for varrious socket events this.socket.onOpen(this.onOpen) this.socket.onError(this.onError) this.socket.onClose(this.onClose) // configure our channel for "all" this.user_chan = this.socket.channel("all") console.log("chan", this.user_chan) // bind a function to any message with an event called "status_users" this.user_chan.on("status_users",data => { console.log("chan on hook",data); // blindy push data from server into our state this.onUpdate(data) }) // this is what actually joins the "all" channel. When the server responds "ok" and the join is successful we can // drive other events, we just log it here. this.user_chan.join(this.auth).receive("ok", chan => { console.log("joined") }) // callback for any errors caused by our join request .receive("error", chan => { console.log("error",chan); }) }, // pass our init() to React's state getInitialState(){ return this; }, onOpen(thing){ console.log("onOpen",thing, this) }, onClose(){ console.log("onClose") }, onError(){ console.log("onError") }, onUpdate(update){ console.log("update",update); console.log("this",this); // trigger is what will push our new state to React this.trigger(update) }, // This is bound by our Actions.js. it pushes a message to handle_in("hit","hit",socket) which increments a hit counter // this is triggered in our onClick handler for BtnA and BtnB onHit(){ this.user_chan.push("hit","hit") }, // our old swap action onSwap(x){ console.log("switch triggered in: ",x) console.log("TheStore test is",this.test) this.trigger({test: !x}) } }) We add a new component to handle our user status data web/static/js/components/UserStatus.js import TheStore from "../stores/TheStore" export default React.createClass({ // wire in our reflux store mixins: [Reflux.connect(TheStore)], // initial values in case the server is not connecting getInitialState(){ return({user_count: 0, hits: 0, users: []} ) }, render: function() { var doItem = function(item){ return (<span> name: {item} </span>) } return ( <div className="panel panel-default"> <div className="panel-heading"> Status: me: {this.state.me} -- hits: <span clasName="badge">{this.state.hits}</span> </div> <div className="panel-body"> Current Users: {this.state.users.map(doItem)} <span className="badge">{this.state.user_count}</span> Hits: <span className="badge">{this.state.hits}</span> </div> </div> ); } }); Finally we can update our BtnA and BtnB components. They are very much the same, so I’ll only walk through one. import Actions from "../Actions" import TheStore from "../stores/TheStore" export default React.createClass({ mixins: [Reflux.connect(TheStore)], getInitialState(){ return {"name":"BtnA"}; }, handleClick(){ console.log(this.state.name,"clicked",this.state.test); Actions.swap(this.state.test) // This triggers our onHit function in TheStore.js which pushes our event up to phoenix Actions.hit(); }, render(){ return ( <button className="btn btn-danger" onClick={this.handleClick}> This is {this.state.name}: val: {this.state.test.toString()} </button> ) } }) That should be it! A working example can be found at this fiddle demonstrates a react.js component that takes an object as an argument and creates a set of content editable spans for the values, and labels them with the keys. a bit of quick annotation below. Essentially i use 2 props, name and value for each key/value pair. Only the value is editable. // this is our object, please excuese the vulgarity. I was tired when I wrote this. var node1 ={ owner: "i am the owner", where: "right here bitch", name: "Joe Super Fucking AWESOME"} // this is our main component which manages the changes to the content in our contentEditable spans var ContentEditable = React.createClass({ render(){ return( <span id="contenteditable" onInput={this.emitChange} onBlur={this.emitChange} contentEditable > {this.props.item} </span> ) }, emitChange(){ var html = this.getDOMNode().innerHTML; // only fire if the html changes if (this.props.onChange && html !== this.lastHtml) { this.props.onChange({ // emit both the value of the change, and the key, as name here target: { value: html, name: this.props.name } }); } this.lastHtml = html; } }); var Item = React.createClass({ getInitialState(){ return {result: ""} }, // this is where we'd do something with the update handleClick(event){ console.log("click",this.state) }, // mostly debuggin output to see how thing react to changes handleChange(event){ console.log("change",this.state); var x = this.state[event.target.name]; console.log("x",x,event.target.name); var o = {} o[event.target.name] = event.target.value; this.setState(o); }, render(){ var keys = Object.keys(this.props.i) return(<div> {keys.map(function(key){ var item = this.props.i[key] return( <li> <label>{key}:</label> <ContentEditable name={key} item={item} onChange={this.handleChange} /> </li> );},this)} <button onClick={this.handleClick} > Pretend to send to a server or something </button> <div>result<pre>{JSON.stringify(this.state,null, 2)}</pre></div> </div>) } }); var MyDiv = React.createClass({ //mixins: [Reflux.connect(TheStore)], render(){ return ( <div> This holds our item! <br /> <div> <ul> <Item i={node1} /> </ul> </div> </div> ) } }) React.render(<MyDiv />, document.getElementById('container')); AWS has a great feature that allows you to bind multiple virtual network interfaces (ENI) to a single instance. This allows you do several things, like migrate an IP between two hosts. I wanted to be able to run a dev server on another IP without having to fire up another instance. The ENI guide is a good place to start. Head over the AWS console and create a new ENI, ensure it is setup in the AZ you plan to use. Once it is created you can then bind it to an instance by right clicking on the new ENI and assigning it to the instance. If you need to map DNS, next go create a new EIP (Elastic IP), right click to associate it to your instance and select the ENI you just created EIPs are free as long as they are in use, so ensure you don’t leave them sitting around unbound. Now you shoule have 2 interfaces, and you can check like this: $ ifconfig -a eth0 Link encap:Ethernet HWaddr 06:F0:45:89:00:01 inet addr:10.1.0.34 Bcast:10.1.1.255 Mask:255.255.254.0 inet6 addr: fe80::4f0:45ff:fe89:1/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:9001 Metric:1 RX packets:11229516 errors:0 dropped:0 overruns:0 frame:0 TX packets:10642366 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1340181266 (1.2 GiB) TX bytes:4072465916 (3.7 GiB) eth1 Link encap:Ethernet HWaddr 06:D0:99:9B:B1:85 inet addr:10.1.1.221 Bcast:10.1.1.255 Mask:255.255.254.0 inet6 addr: fe80::4d0:99ff:fe9b:b185/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:9001 Metric:1 RX packets:1697 errors:0 dropped:0 overruns:0 frame:0 TX packets:519 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:109796 (107.2 KiB) TX bytes:1332985 (1.2 MiB) Assuming you are using a VPC, you need to be sure you don’t use your public IP’s or EIP addresses. AWS uses 1:1 NAT in VPC and your instance knows nothing about your public addresses. Next you need to take a look at your config/#{Mix.env}.exs Below is my dev version (config/dev.exs), note the ip option 4 tuple, and that it is a tuple and not 10.1.1.221, but uses commas. This ip option is what gets passed to ranch and will bind your IP address. Ensure you change these for each env you need to adjust. config :reflux_eventbroker_react_phoenix_elixir, RefluxEventbrokerReactPhoenixElixir.Endpoint, http: [ip: {10,1,1,221},port: 8080], debug_errors: true, code_reloader: true, cache_static_lookup: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch"]] Fire up mix phoenix.server to ensure it works. When you are all done and everything is working you can run [ec2-user@ip-10-1-0-34 ~]$ sudo service iptables save iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ] This works for phoenix 0.16.1, not sure if it will continue to function this way. just add this as a 2ns arg to your new socket. var socket = new Phoenix.Socket("/status",{logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }}) This helps if your chan.on(“foo”,… is not working and you want to see what is happening under the covers more detail in the phoenix.js source code this demonstrates a very cool conversion of a word document to markdown. The best part of poking this for me was learning that markdown supports embedded images. This makes it easy to take a screenshot, paste into word, and then use this to convert it to markdown, including the pasted image. It doesn’t account for anything, things like the conversion of “2nd” in word can throw it for a loop. Being a terrible speller, and not taking the time to figure out how to spellcheck with vim, makes this a good tool for me. There is a heroku app here that you can use to play with it. This quick tutorial has only been tested with the following component versions. Beware trying to get this working with other versions. Phoenix is not yet 1.0 and it may change enough to make this no longer work. Git Repo: Elixir 1.05 and Phoenix 0.15.0 components: Bower components for reflux 0.2.7, react 0.13.3 I’ve been working with phoenix quite a bit lately for brng.us and idgon.com and thought to explain the asset pipeline for javascript build tool neophytes like myself. React shares nicely until you start to break things up and isolate them (a good practice). This is a great blog post discussing how to get your components talking, but if you are isolating it doesn’t work. Reflux provides a nice model which can help you decompose your app, and manage events. Firstly I just want to say .js is a ghetto, and I look forward to a day where browsers can support more languages than just .js Phoenix has a very nicely automated setup for dealing with this mess. It uses brunch and inotify to detect and dynamically compile your assets. The pipeline looks something like this: You may want to look at my ec2 setup here if you don’t already have erlang, elixir, brunch, phoenix all installed. Also for reference is my repo for this tutorial. The first commit adds the files we need and creates a bower.json Then run bower install The next commit adds the changes we need for our brunch config to include the new bower_components If you run mix phoenix.server you should see the default phoenix app page, and notice that brunch is picking through your static files and compiling them for you. If you open your dev tools in your browser you should see the following. Our first step is to create a few conventional directories to store our reflux stores and our react components. Now we need to make a few react components to play with. You may want to use the react fiddle here to familiarize yourself with react. You can see the fiddle I used here. To componentize this we will break it into 3 thing React components and 2 reflux object. Here is the commit which I will break down below. I’m not sure if this is needed, but this removes your bower_components from your babel conversions. - ignore: [/^(web\/static\/vendor)/] + ignore: [/^(web\/static\/vendor)|(bower_components)/] web/static/js/Actions.js we just setup an action for Reflux to listen to. +export default Reflux.createActions([ + "swap" +]); web/templates/page/index.html.eex I removed the standard template and add a target div for React to bind to <div id="mydiv"> our crap should go here </div> Finally comes all our js code. We have the following components TODO: add graphviz app.js -> Actions.js -> stores/TheStore.js -> MyDiv.js -> components/BtnA.js -> components/BtnB.js Bower and brunch do all of the magic to include our js components into our app.js aggregated file. We only have to import the components we created above. app.js initializes React to target the div “mydiv” in our index.html.eex template. It also pulls in our code from the import MyDiv statement. web/static/js/app.js // this is for phoenix and it's live code reloading, or web socket connections import {Socket} from "phoenix" // pulls MyDiv.js into scope import MyDiv from "./MyDiv"; React.render( <MyDiv />, document.getElementById("mydiv") ); BtnA.js and BtnB.js are almost identical. They simply render a div with a button and a button label. They import our Actions and bind them to an event handler which calls Action.swap. web/static/js/components/BtnA.js +import Actions from "../Actions" // TheStore.js is our Reflux store +import TheStore from "../stores/TheStore" + // create our react object, this exports the filename as the export name, in this case BtnA +export default React.createClass({ // this mixin ties the state and events to our react component + mixins: [Reflux.connect(TheStore)], // we simply initialize state.name with the name of the component to be // printed to the console + getInitialState(){ + return {"name":"btna"}; + }, // this binds to the button onClick event + handleClick(){ + console.log(this.state.name,"clicked",this.state.test); + Actions.swap(this.state.test) + }, // render gets called when the component is created or the state is updated + render(){ + return ( + <button onClick={this.handleClick}> This is BtnA </button> + ) + } +}) The mixins line does all of the magic. It binds the functions of the mixin to the react object, so we could call this.onSwap(arg) directly. It also does the work of calling the lifecycle methods from reflux [init, preEmit, should Emit]. With reflux you can use Reflux.listenTo(store,”onEventToListen”), however we are using Reflux.connect which will update our components state to whatever the reflux store transmits (via this.trigger({stateKey: newState}). This can be limited to a state key if you want to filter on specific state keys. In our case we are listening to every event. Connect also will initialize the state of the component it is connected to via the Reflux’s getInitialState function. The initiliazation now looks like this TODO: add graphviz TheStore.init -> TheStore.getInitialState -> BtnA.getInitialState TheStore initializes to {test: true}, and that ends up merged with our BtnA state with a result of {test: true,name: “btna”} To fire up the app cd into the root directory (with the mix.exs) and run mix phoenix.server Go ahead and click either button. In the console you can see that clicking the button will change each components state for the state key “name”. Now that you can see how to componentize react and use reflux stores to broker events between your components, you can start to see how you might move away from having to talk to a REST API. Once you tie in Phoenix’s sockets, you can now just push all of your events down to your client, and per the name, have it react. Next up I will be writing about how to take this to the next level. References: Good examples for React: # dev tools to compile and build sudo yum groupinstall "Development Tools" sudo install ncurses-devel udo yum install java-1.8.0-openjdk-devel sudo yum install openssl-devel # install erlang wget tar -zxvf otp_src_18.0.tar.gz cd otp_src_18.0 ./configure make make install # get inotify wget tar -zxvf inotify-tools-3.14.tar.gz cd inotify-tools-3.14 ./configure make sudo make install # you may need to tweak inotify per if you get errors # elixir mkdir elixir cd elixir wget unzip Precompiled.zip rm Precompiled.zip # add it to your path now # get phoenix mix local.hex mix archive.install # install node sudo yum install nodejs npm --enablerepo=epel # install brunch sudo npm -g install brunch # make phoenix app without ecto mix phoenix.new phorechat --no-ecto # some effort to get port 80 forwarded, used iptables rules # ignore the fail2ban stuff sudo service iptables status Table: filter Chain FORWARD (policy ACCEPT) num target prot opt source destination Chain OUTPUT (policy ACCEPT) num target prot opt source destination Table: nat Chain PREROUTING (policy ACCEPT) num target prot opt source destination 1 REDIRECT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 redir ports 8080 Chain INPUT (policy ACCEPT) num target prot opt source destination Chain OUTPUT (policy ACCEPT) num target prot opt source destination 1 REDIRECT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 redir ports 8080 Chain POSTROUTING (policy ACCEPT) num target prot opt source destination # winsplit md5: b7417d3e1db10db8e6c19caf69dfcc88 I found an intact copy of 11.04 on majorgeeks.com. Winsplit development has been stopped, but it still works great for Windows 8. Their site appears to be tyring to sell some other product, vs sharing the open source version. Assuming you have the AWS CLI installed, and if you are using Amazon Linux, it is installed by default, this is how you can copy a directory to S3 with public read permissions set. aws s3 cp build s3://blog.brng.us/ --recursive --grants read=uri= This is useful for my Obelisk blog which creates static html files from markdown. The docs for aws cp can be found here About this blog: This blog will discuss technology associated with my idgon.com project. I am using Elixir and Phoenix for my backend, and React.js and Reflux for my front end. I have a library called Trabant to experiment with graph database persistence for Elixir. The views expressed on this blog are my own, and are not that of my current employer. About Me: I am a hobbyist programmer interested in distributed computing. I dabble in Elixir, Ruby, and Javascript. I can't spell very well, and I enjoy golf.
http://blog.brng.us/
CC-MAIN-2017-39
refinedweb
6,643
67.04
NLP Analysis of the President’s Tweets on Trade (With Some Inspiration From Russians by Sting) In Europe and America, There’s a growing feeling of hysteria. Markets are catching up to the staying power of the trade war. As I wrote on May 23rd here: Investors continue to assume that what President Trump says and does on trade will be two different things. Actual events have proven otherwise, and global markets have not yet figured this out. We are on the verge of an upshift in geopolitical tension that will impact all markets.Complexity Everywhere, May 23, 2019 Conditioned to respond to all the threats, In the rhetorical tweets of the President; Mister Trump says, “We will trade with you”. Don’t take my word for it, take his. Since launching his Twitter account in 2009, the President has tweeted/retweeted more than 39,000 times. I built an NLP language model trained on over 97% of his tweets as well as a sentiment classifier to determine the positive or negative sentiment of any tweet (achieving about 85% accuracy in training). The models employ ULMFiT, a state-of-the-art NLP transfer learning method developed by Jeremy Howard and Sebastian Ruder, that is fully implemented in the fast.ai library. I don’t subscribe to this point of view, His tweets say it would be an ignorant thing to do. I then took the ~690 tweets that included the words China, Chinese, or President Xi and ran them through the classifier. A staggering 97% of 413 tweets prior to Election Day in 2016 had negative sentiment, down to 62% since then. Of note, ALL 21 tweets about these topics during the 2016 campaign were negative. Read more about the model in the NLP Model Detail section below; full code can be found here. Further, here is a word cloud of the most frequent words in President Trump’s tweets about China (excluding the words China, Trump, President, Trade, Russia, Mexico, Chinese). The four most common words are US, Now, Will, and Tariff. It is up to you to decide if the President’s pre- Election Day tweets are more or less representative of his core beliefs. I believe they are more. Negative China sentiment seems like good politics – the campaign clearly went all-in on negative with the Presidency on the line. And with the 454 days until the election, the President is focused on politics, not markets. Believe me when I say to you, Mr. Trump does not love a trade deal too. How can I save my White House joy, from 2020’s deadly toy? A trade war is good politics. I wrote in January, May, and June about a global battle being waged between Freedom and Autocracy. The President, despite being attacked for his own supposed autocratic instincts, has successfully framed himself at the center of this debate, on the side of Freedom. This message will continue to resonate in the heartland, even in places affected by the trade war. There is monopoly on China sense, On either side of the political fence. Don’t expect any help from leading Democratic candidates. The President has successfully boxed the Democratic candidates into a corner. How do you think a “Let’s Play Nice With China” slogan will do in Wisconsin? A combination of true belief in fairness and cold political calculus will likely push the Democratic challengers to produce even tougher platforms on China. There is such thing as a winnable war, We don’t believe the narrative anymore. Two trends in the economy are sure to factor into the President’s re-election strategy. Both support a protracted battle. First, reports of companies pulling production out of China has increased in recent months, see here, here, and here. This will embolden the White House and the campaign to double-down. Second, the impact of job losses in key sectors such as farming may not matter to Trump’s reelection strategy. About 54% of farming jobs are in the 3 Pacific states, all of which will vote blue in 2020. In terms of the President’s Rust Belt firewall, Pennsylvania, Ohio, Wisconsin, and Michigan house only 5% of the country’s farming jobs. [table id=23 /] This topic requires more in-depth analysis and its own future post. We share the same biology, regardless of ideology. Cycles matter, and perhaps there is nothing new under the sun. As discussed in my 2019 Outlook here, public sector confidence is in a down cycle and the prevailing global order (established post-WW2 about 75 years) is undergoing a transition to a multi-polar framework. During this shift, the risk of a miscalculated move by a frustrated public sector actor is VERY HIGH. Perhaps that is a protracted trade war or overreach in Hong Kong or Kashmir. Incidentally, all of this is occurring in alignment with the end of a long-term debt cycle, which typically lasts about the same length of time, per Ray Dalio. It is thus no surprise that major political and societal events also have a 72-75 year rhyme to them, as I wrote about here. There is now historical precedent, To understand the words from the mouth of the president. Mr. Trump says he will protect you, Do you subscribe to this point of view? Believe me when I say to you, Mr. Trump does not love a trade deal too. Trade War NLP Model Details Data Pre-Processing I leveraged this great function built by Ronald Wahome to clean up the raw tweet data. It removed hashtags, punctuation, whitespace, tickers, etc. I also went through and removed all retweets of non-English language tweets. def processTweet(tweet): # Remove HTML special entities (e.g. &) tweet = re.sub(r'\&\w*;', '', tweet) #Convert @username to AT_USER tweet = re.sub('@[^\s]+','',tweet) # Remove tickers tweet = re.sub(r'\$\w*', '', tweet) # To lowercase tweet = tweet.lower() # Remove hyperlinks tweet = re.sub(r'https?:\/\/.*\/\w*', '', tweet) # Remove hashtags tweet = re.sub(r'#\w*', '', tweet) # Remove Punctuation and split 's, 't, 've with a space for filter tweet = re.sub(r'[' + punctuation.replace('@', '') + ']+', ' ', tweet) # Remove whitespace (including new line characters) tweet = re.sub(r'\s\s+', ' ', tweet) # Remove single space remaining at the front of the tweet. tweet = tweet.lstrip(' ') # Remove characters beyond Basic Multilingual Plane (BMP) of Unicode: tweet = ''.join(c for c in tweet if c <= '\uFFFF') return tweet Language Model In addition to fast.ai, this article by Prashant Rao was helpful in completing this analysis. As discussed in the ULMFiT paper and on fast.ai, the first step is: “The LM is trained on a general-domain corpus to capture general features of the language in different layers.”Howard, J, Ruder, S. Universal Language Model Fine-tuning for Text Classification (arXiv:1801.06146) ULMFiT achieves this by training on the Wikitext-103 (Merity et al., 2017b), which contains 28,595 preprocessed Wikipedia articles and 103 million words. The theory, like in all transfer learning, is to avoid expensive computation and leverage a pre-trained model to analyze one’s own particular corpus. That leaves you to fine-tune the pre-trained model on your target data, and train a classifier (using the language model). Tokenization and Numericalization After reading the cleaned tweets into a Pandas dataframe, the first step is to create a DataBunch suitable for training. The primary decisions here are to select the minimum word frequency, 2, and a maximum vocabulary size of 60,000. The model applies tokenization and numericalization (see here for more on these steps) to any word that appears at least twice in the corpus, and caps the total vocabulary at 60,000 words. Note that characters like spaces are assigned unique tokens (e.g. space = xxmaj) data_lm = TextLMDataBunch.from_csv(path, 'ttat.csv', max_vocab = 60000, min_freq=2) Find the Optimal Learning Rate I employ fast.ai’s learning rate finder tool, which deploys an optimization function to identify at what learning rate our modeled loss begins to diverge. I prefer using a learning rate at a steep point in the curve below. learn = language_model_learner(data_lm, AWD_LSTM, drop_mult=0.3) learn.lr_find() learn.recorder.plot(skip_end=15) Fine Tune the First Layer Per ULMFiT and fast.ai, I first trained the last layer of the model, having selected 1e-3 as the max learning rate. “Instead of using the same learning rate for all layers of the model, discriminative fine-tuning allows us to tune each layer with different learning rates. We empirically found it to work well to first choose the learning rate ηL of the last layer by fine-tuning only the last layer and using ηl−1 = η l/2.6 as the learning rate for lower layers.”Howard, et al (arXiv:1801.06146) # Run one epoch on last layer learn.fit_one_cycle(1, 1e-3, moms=(0.8,0.7)) Unfreeze all Layers and Train ULMFiT also employs Slanted Triangular Learning Rates (SLTR) behind the scenes, based on the following rationale: …we would like the model to quickly converge to a suitable region of the parameter space in the beginning of training and then refine its parameters. Using the same learning rate (LR) or an annealed learning rate throughout training is not the best way to achieve this behavior. Instead, we propose slanted triangular learning rates (STLR), which first linearly increases the learning rate and then linearly decays it…”Howard, et al (arXiv:1801.06146) learn.unfreeze() learn.fit_one_cycle(10, 1e-3, moms=(0.8,0.7)) Classifier Model I now save the language encoder weights for use in the classification model learn.save_encoder('ft_enc') The classification model takes as input 100 tweets from the President, hand-labeled for positive or negative sentiment. I am operating on the notion that a small dataset can produce good results, given ULMFiT’s success. Prepare Data and Build Learner As before, I build a DataBunch and a learner object. I also make sure to load the encoder weights. data_clas = TextClasDataBunch.from_csv(path, 'tr_ch_tw_train.csv', vocab=data_lm.train_ds.vocab, bs=8) learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5) learn.load_encoder('ft_enc') Train the Classifier As proposed in ULMFiT, the key here is to train the classifier in stages. The paper presents two key concepts. First, they propose Concat Pooling which is accomplished behind the scenes in the model: “As input documents can consist of hundreds of words, information may get lost if we only consider the last hidden state of the model. For this reason, we concatenate the hidden state at the last time step hT of the document with both the max-pooled and the mean-pooled representation of the hidden states over as many time steps as fit in GPU memory.”Howard, et al (arXiv:1801.06146) The second concept is Gradual Unfreezing, where layers are unfrozen in sequence. “Rather than fine-tuning all layers at once, which risks catastrophic forgetting, we propose to gradually unfreeze the model starting from the last layer as this contains the least general knowledge (Yosinski et al., 2014): We first unfreeze the last layer and fine-tune all unfrozen layers for one epoch. We then unfreeze the next lower frozen layer and repeat, until we finetune all layers until convergence at the last iteration.”Howard, et al (arXiv:1801.06146) So that is what I do while also applying the discriminative fine-tuning proposed in the paper. learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7)) learn.freeze_to(-2) learn.fit_one_cycle(1, slice(2e-2/(2.6**4),1e-2), moms=(0.8,0.7)) learn.freeze_to(-3) learn.fit_one_cycle(1, slice(5e-3/(2.6**4),5e-3), moms=(0.8,0.7)) learn.unfreeze() learn.fit_one_cycle(2, slice(1e-3/(2.6**4),1e-3), moms=(0.8,0.7)) I ended up with about 85% accuracy. From here, I read in the complete set of Tweets that referenced the words China, Chinese, or President Xi and ran them through the classifier to produce the sentiment output. test = pd.read_csv(path/'final_china - output.csv') test_pred = test test_pred['sentiment'] = test_pred['text'].apply(lambda row: str(learn.predict(row).
https://www.complexityeverywhere.com/believe-me-when-i-say-to-you-i-hope-you-love-a-trade-war-too/
CC-MAIN-2021-10
refinedweb
2,026
55.95
Hello, I am somewhat I newbie to C++ programming and I require some help with this. I am writing a simple organizer program but I run into a problem: I run it and it gives me the main menu, and I enter an option, but then it just blows off the option number and gives me the next function in the code. Here is the code: life.cpp main.cppmain.cppCode:#include <iostream.h> #include "menu.cpp" using namespace std; int main() { int answerget; startmenu(); cin >>answerget; if (answerget = "1") contactsmenu(); if (answerget = "2") notepadmenu(); if (answerget = "0") cout << "\nGood Bye\n"; return 0; } Can anyone help me out?Can anyone help me out?Code:void startmenu() { cout << "\nWelcome to Life V.00001"; cout << "\n Select option number:"; cout << "\n[1]Contacts"; cout << "\n[2]Notepad"; cout << "\n[0]Quit\n"; } void contactsmenu() { int contactmget; cout << "\n CONTACTS--"; cout << "\n\n[A]List Contacts"; cout << "\n[B]Add Contact"; cout << "\n[C]Edit Contact"; cout << "\n[Q]MainMenu\n"; cin >> contactmget; if ( contactmget = 0) startmenu(); } void notepadmenu() { int notepadmget; cout << "\n NOTEPAD--"; cout << "\n\n[1]New File"; cout << "\n[2]Open File"; cout << "\n[0]MainMenu\n"; cin >> notepadmget; if ( notepadmget = 0) startmenu(); }
http://cboard.cprogramming.com/cplusplus-programming/68106-help-cin-cplusplus.html
CC-MAIN-2015-40
refinedweb
204
58.62
On Wed, 1 Mar 2000, Manoj Kasichainula wrote: > > > This has been brought up before, but I think that before 2.0 goes out, > > > we should replace the regex library. There are two good alternatives > > > that I know of: PCRE, and the new HS regex libs. I'm partial to PCRE, > > > because it is visibly maintained right now (there's now a 3.0 > > > version), and because there are actual tarballs of the package that I > > > know of. AFAIK, the new hsregex is only in Tcl tarballs. > > So, there has been no strenuous objection to this idea. So if there > are no objections, I'll replace (when I get around to it :) the > hsregex in 2.0 with PCRE and mandate that it is always compiled in; +1 > with ap_ wrappers to prevent namespace collision with system libs. -0 Only if necessary. Please avoid wrappers if PCRE is already namespace-protected (it appears that it is). Throwing an extra layer wouldn't seem to add anything. Cheers, -g -- Greg Stein,
http://mail-archives.apache.org/mod_mbox/httpd-dev/200003.mbox/%3CPine.LNX.4.10.10003011623250.20577-100000@nebula.lyra.org%3E
CC-MAIN-2018-13
refinedweb
169
84.27
Dear Seniors & Guruz, I am planning to buy a vehicle when I return (In Sha Allah) to Pakistan next year, that will be used as primary vehicle in Islamabad/Lahore/Chakwal and on M2. Previously I kept 93 Pajero Automatic and I prefer jeeps to cars. Please guide me to select a balance between Reliability, Power, Economy, Comfort, Speed, Parts and Price and recommend a vehicle in budget between 15-25L. I like Pajero, LC and Surf. I am told that Land cruiser is heavy on fuel and surf is not comfortable for everyday family use and their top speed (although I am never intended to go beyond 135 but 140+? is it practical/possible in case of need/emergency on highways for 4x4s there?). I thank you guys for valuable feedback in anticipation. I am expecting someone to respond, seems everyone is busy! These days buying any good suv is pretty hard in 15 so i will leave that as assume the max budget which is 25. In 25 you can get 2006-8 Vigo, 96-2000 Prado and 96-2003 Surf, the 2000+ models are good for motorway due to their less cabin noise. you can find a 2.7 litre 2003 surf or go with 1kz prado vigo is good as well be it being a dalla is bit bumpy.. Dear qwertypoiu, Thanks for your advice but what about comfort, milage/economy, speed etc??? Vigo is not for family/rough ride, prado would be very heavy on fuel and surf again is I think not very comfortable as compared to LC/Pajero?
https://www.pakwheels.com/forums/t/compromise-4x4-recommendation-please-power-economy-comfort-speed-price/232364
CC-MAIN-2017-30
refinedweb
265
70.02
Related Tutorial Learning the Basic Components works a lot like React, implementing JSX, state, and props. Of course, React Native is built on Native components, instead of HTML elements. Therefore, if you are familiar with normal React, it will be easy to pick up React Native, as long as you can understand the different components used. In this guide, we will look through the basic Native components that React Native uses. Unlike React for the web, React Native requires you to import each component in your project - after all, each component is setup to work both in Android and iOS. This is the reason we use React Native, not to mention being able to write everything in JavaScript. To import each component, we will simply add it to our imported object: import { Text, View } from "react-native"; Text and View are the two most basic building blocks of any React Native application. They are the best place for anyone to start when learning React Native. Text and View As you can guess, <Text></Text> is a wrapper for any text in your page. This component is similar to a <p> tag in HTML. Now, similar to a <div></div> tag, you would wrap your <Text></Text> in a <View></View>. That’s right, <View> acts very similar to <div>, and the basic idea is that it is a container perfect for dividing up and styling your page. Here is the basic set up of a React Native page: import React from "react"; import { View, Text } from "react-native"; export default class App extends React.Component { render() { return ( <View> <Text> Hello World! </Text> </View> ); } } Both <Text> and <View> components have style props where you can set colors, sizes, etc. However, there are some important distinctions to keep in mind. Although View does work similarly to a div element, you can’t wrap any text in it, like this <View>this text doesn't work</View> (not that you should with a div element anyway). That would cause an exception and that is why we use the <Text> component. Speaking of the <Text> component, you can wrap another component inside it like this: <Text style={{ color: red }}> <Text style={{ fontSize: 24 }}>Here is the first text </Text> <Text style={{ fontSize: 14 }}>And the second text.</Text> </Text> // comes out as 'Here is the first text And the second text' When <Text> is wrapping <Text>, the nested text will come out on the same line, assuming there is enough space. However, if the two <Text> components were wrapped in a <View>, they would appear on separate lines. TextInput This component is somewhat like an <input> HTML element, but as its name would indicate, it’s only for a text input. Instead of using onChange callback, you can use onChangeText to detect changes to the text in the <TextInput> component. You can use onChange, but it returns an object: { nativeEvent: { eventCount, target, text} }. Other than that, there are plenty of cool features on this component. You can set which keyboard pulls up on the phone with keyboardType (such as keyboardType='email-address'), toggle the auto-correct feature, set the textContentType for the phone to autofill the text (like your password on your keychain), and so much more. Button And Alert The <Button /> component is the first component I noticed that had major differences from its sibling (the HTML <button> element). The React Native <Button /> has an onPress() prop, as opposed to anything click-related. It also has a title prop for the text which goes inside it. Finally, it doesn’t have a style prop, but only a color prop. That last point is a pretty big difference. Now you can (and would) wrap it in a View and style it with that wrapper. That is a common way to deal with some limitations on React Native components and you will likely find yourself using View to wrap other components all the time. What I find myself using more often is a component we will cover a little later - <TouchableOpacity >. What I also found interesting about this basic Button component is that on the iOS platform, it only shows up as the text in the title - with no background. Therefore, the color prop will only change the text color, though on Android it will change the background color of the button. Here is a quick example of a Button component. <Button onPress={() => Alert.alert("button pressed!")} Note: we are using Alert which is also imported from the React Native core. This will show an alert on top of our screen, similar to a web alert(). Image and ImageBackground The <Image /> component is pretty similar to a HTML img tag. However, there are a few differences, such as changing the src prop to source. Also, the source itself operates differently: for local images, you import them with require, like this <Image source={require('path/to/local/image)} />. Also, in the source prop, you can use the URI like this: <Image source={{uri: ''}} style={{height: 100, width: 100, resizeMode: contain}}. Notice the uri is an object, so it needs another set of curly braces, just like inline styles. There are plenty of other props to check out here, but a common one to use is resizeMode. This determines how to resize your image and to fit your image within a parent View component. The ImageBackground component is similar to the <Image /> component as it receives the same props, but the main distinction here, is that it can have child elements. The <Image /> component is self-closing. The thing about ImageBackground is, is that it’s pretty basic and a better solution to setting a background image might be to either build your own component or simply set an Image as absolute with lower opacity and behind everything. The Touchables One thing you’ll notice in React Native is that many of the components we have covered do not have all the props you would normally implement in a web app. The <Image /> component does not have an onPress prop and the <Button /> component doesn’t have a style prop. Any Touchable component can really help here. For instance, you can wrap any image component in a Touchable: <TouchableHighlight onPress={this.pressHandle}> <Image /> </TouchableHighlight> The TouchableHighlight in the above example acts like a container for the image with a function when pressed, including a built-in animation. You could also just add View and Text components within a Touchable component to act just like a <Button />, but with customizable style. Now there are a few different Touchable components such as: - TouchableHighlight: when pressed, darkens the background. - TouchableOpacity: when pressed, dims the opacity of the button. - TouchableNativeFeedback: Android-only ripple effect. - TouchableWithoutFeedback: a press without any feedback/effect. These animations happen when pressed. The Touchable components also have their own unique props which you can customize to your own liking. ScrollView, SafeAreaView and FlatList So far we’ve looked at all the basic building blocks of a React Native app. However, there are plenty more, and one thing you will quickly find is that a phone screen won’t automatically scroll if the content height or width exceeds the screen size. This may surprise you, when you have everything wrapped in a View component, the overflow will be hidden. That’s where the simple implementation of ScrollView comes in. The ScrollView component is the basic component to enable scrolling. However, FlatList also enables scrolling, but it has a much greater capacity than ScrollView. Now, the basic setup of ScrollView is giving boundaries to the scrollable-view, which would most likely be the screen height and width. Like an image, you can wrap ScrollView to give it these boundaries. Normally, you can use a normal View component for this, but if you have an iPhone X, you may find that your View goes up behind the rounded corners or sensor cluster. The SafeAreaView will take care of this, giving adequate padding so the entire screen will be visible. Either way, to stretch the entire screen, you can simply set the style of the parent view to flex: 1. This setup with ScrollView will work when the height of all your elements is determined locally - as in, the height of your page will always be set the same. If there is data coming in that affects the dimensions of the content, it may be difficult to determine the dimensions of the ScrollView. There are ways to compensate for that, but an even bigger limitation to ScrollView is that it will render everything all at once. Imagine your Facebook account rendering every story at once - it would never load! FlatList is similar to ScrollView, but it uses lazy-loading, so that only the items which are currently on the screen will render. Of course, FlatList requires data to be passed to it. More specifically, it requires an array of data to be passed. Then, FlatList loops over that array and renders each one when on screen. If an item goes off the screen, when the user scrolls away, FlatList dumps that item and recreates it the next time it appears on the screen (state is lost). ScrollView, on the other hand, doesn’t dump and reload, but renders them all at once at the beginning. Here is an example of each: <SafeAreaView style={{ flex: 1 }}> <ScrollView>// content in here to fill the page</ScrollView> </SafeAreaView> <SafeAreaView style={{ flex: 1 }}> <FlatList data={dataArray} renderItem={( { item } // item would represent one element in the dataArray ) => <IndividualComponent prop={item.prop} />} keyExtractor={item => item.id} /> </SafeAreView> Now, you wouldn’t ever want to nest FlatList inside a ScrollView or vice-versa. That isn’t good practice and it would give you an error anyhow. The important thing to keep in mind with FlatList is that the renderItem prop is fixed to take these parameters in its function: renderItem={({item, index, separators}) => {}}. Also, the item is always from the array you pass into the data prop - which can only take in a plain array. A few other important things about FlatList - keyExtractor takes care of React’s need to set a unique key on each element, just like setting a key prop on each of the components rendered by FlatList. Also, if the dataArray updates because of state or another prop, the FlatList wouldn’t re-render as it is setup in the example above. In order to have it update, you could set the extraData prop to watch what would update (e.g. extraData={this.state}). Wrap Up That concludes the basic components of React Native. As you can see, they are much more particular than you might be used to. For more information on the components here, check out the official docs.
https://www.digitalocean.com/community/tutorials/react-react-native-basic-components
CC-MAIN-2020-34
refinedweb
1,797
61.36
Deploy Your Facebook Messenger Bot with Python When done right, interacting with a computer through human language is incredibly powerful and also quite fun. Messaging and Voice-Controlled devices are the next big platforms, and conversational computing has a big role to play in creating engaging augmented and virtual reality experiences. There are a number of unique challenges to building these kinds of programs, such as: how can I make my chatbot available to the outside world? In this tutorial, you'll go through the steps required to deploy a chatbot on Facebook Messenger, which has over 1 Billion active users. You can reach an enormous audience with just a few lines of code. There are 3 main steps to get this done. You need to: - create a server which listens to messages from Facebook (using flask) - define a function for sending messages back to users (using requests) - forward a httpsconnection to your local machine (using ngrok) If you want to know more on how to turn human language into machine instructions, check out the Building Chatbots in Python DataCamp course. Note that what you won't cover in this post is how to your bot can understand what people are saying and respond appropriately. To learn more about that you should have a look at Rasa NLU, Rasa Core, and the DataCamp course that was just mentioned. Wrap Your Chatbot in a http Server The first step is to create a http server which listens to messages sent by Facebook, gets a response to that message, and eventually sends the response back to the user on Facebook. We will use flask to create this server. The basic idea is the following: - Create a flaskapp that listens for messages sent to localhost:5000/webhook. When messages are sent on Facebook they will arrive as httprequests to this URL. - The listen()function handles these httprequests and checks that they contain a valid Facebook message - If the message is valid, the get_bot_response()function is called and the response is sent back to Facebook Messenger In addition, you will create a function called verify_webhook() that handles the initial authentication between Facebook and your app. The final script looks like this (save it under server.py): from flask import Flask, request app = Flask(__name__) FB_API_URL = '' VERIFY_TOKEN = ''# <paste your verify token here> PAGE_ACCESS_TOKEN = ''# paste your page access token here>" def get_bot_response(message): """This is just a dummy function, returning a variation of what the user said. Replace this function with one connected to chatbot.""" return "This is a dummy response to '{}'".format(message) def verify_webhook(req): if req.args.get("hub.verify_token") == VERIFY_TOKEN: return req.args.get("hub.challenge") else: return "incorrect" def respond(sender, message): """Formulate a response to the user and pass it on to a function that sends it.""" response = get_bot_response(message) send_message(sender, response) def is_user_message(message): """Check if the message is a message from the user""" return (message.get('message') and message['message'].get('text') and not message['message'].get("is_echo")) @app.route("/webhook") def listen(): """This is the main function flask uses to listen at the `/webhook` endpoint""" if request.method == 'GET': return verify_webhook(request) if request.method == 'POST': payload = request.json event = payload['entry'][0]['messaging'] for x in event: if is_user_message(x): text = x['message']['text'] sender_id = x['sender']['id'] respond(sender_id, text) return "ok" In the above script the VERIFY_TOKEN and PAGE_ACCESS_TOKEN variables aren't defined yet - so you will have to set these. The VERIFY_TOKEN can be any string, it is used as a kind of password to let facebook know that this server wants to receive messages. It is a good idea to use a long random string. You can do this quickly by running openssl rand -base64 32 in your terminal. Don't worry about the PAGE_ACCESS_TOKEN just yet - you will see how to get it below! Send Messages Back to Users Next, you will write a function that that sends a response back to Facebook Messenger using a python library called requests. In particular, you use the post() method, which creates a HTTP POST request. A POST request is the typical way to send information to a server. Your function should look like this: import requests def send_message(recipient_id, text): """Send a response to Facebook""" payload = { 'message': { 'text': text }, 'recipient': { 'id': recipient_id }, 'notification_type': 'regular' } auth = { 'access_token': PAGE_ACCESS_TOKEN } response = requests.post( FB_API_URL, params=auth, json=payload ) return response.json() Expose a https Endpoint and Connect a Facebook Page The url localhost:5000 only works for requests created on the same computer as the running server. So you need to let facebook know how to reach your flask server. To do this, first install ngrok. Go to this page and install the version for your operating system. If you're on Mac and have homebrew, the quickest way to install ngrok is with brew cask install ngrok. Start the ngrok server in your terminal with ngrok http 5000. This will set up a https endpoint to get forwarded to your machine on port 5000, for example. Note that if you quit ngrok and restart, this URL will change. Create a Facebook App and Page The next step is to create an app and a page on Facebook. There is good documentation available from Facebook but you'll walk through the main steps here. To create the app go here and - click on My Apps -> Add a New App and enter a name - you will be redirected to the dashboard for the app - under Products, find Add a Product and click on Messenger -> Set Up To create the page, you have to: - go the settings for Messenger, scroll down to Token Generation and click on the link to create a new page for your app Once you have created a page, go back to the Token Generation settings and select this page from the drop-down menu. Copy the Page Access Token into the placeholder for PAGE_ACCESS_TOKEN in server.py above. Start your bot server Now that you have everything set up, it's time to start your chatbot server! In a separate terminal tab, run FLASK_APP=server.py flask run Set up the webhook Finally, you need to register your webhook on the Facebook developers page. - Go to the Messenger tab in Products again and scroll down to Webhooks, click on Setup Webhooks - Under the Callback URL enter in your ngrok URL, for example,. It is important that your flaskapp is running at this point, because the verify_token()will be called on the next step - In the Verify Token field, you put the value you specified in your server.pyfile - In Subscription Fields make sure messagesand messaging_postbacksare ticked Click Verify and Save to perform the authentication Important: Go back to Products -> Messenger, and under Select a page to subscribe your webhook to the page events select your page and click Subscribe. You're done! Your bot is now ready to send and receive messages via Facebook Messenger. Right now, your get_bot_response() function is still pretty simple, and doesn't feel like a real chatbot yet! To learn all about building chatbots, check out the Building Chatbots in Python DataCamp course, as well as the Rasa NLU and Rasa Core python libraries.
https://www.datacamp.com/community/tutorials/facebook-chatbot-python-deploy
CC-MAIN-2022-05
refinedweb
1,207
59.94
Java Constructor plays an important role in code development. A constructor looks like a method but without any return type. Moreover, the name of the constructor and class name should be the same. The advantage of constructor is it is called implicitly when an on object is created. That is, we write a constructor but we never call explicitly. It is automatically called (ofcourse, an object should be created). The same thing in case of methods, a method should be defined and called explicitly with an object. Now let us see how to create a Java constructor. public class Employee { public Employee() // defining a constructor { System.out.println("OK 1"); } public static void main(String args[]) { Employee emp1 = new Employee(); // creating object to call the constructor Employee emp2 = new Employee(); Employee emp3 = new Employee(); } } public Employee() The above statement defines a Java constructor. Observe, the class name and constructor name are same. Just to know that constructor is called, a println() statement is given. Employee emp1 = new Employee(); Employee emp2 = new Employee(); Employee emp3 = new Employee(); In the main() method, three objects emp1, emp2 and emp3 are created. Each object calls the constructor and prints OK 1. That is, three times the Java constructor is called and OK 1 is printed three times. Employee emp1 = new Employee(); In the above statement, the last word Employee() denotes a constructor. It infers, to create an object, compulsorily constructor is to be called. Note: Do not try to call a constructor like a method. emp1.Employee() raises compilation error.
https://way2java.com/oops-concepts/java-tutorial-constructor-creation-example/
CC-MAIN-2020-50
refinedweb
256
58.08
Anyone who has used Haskell in a professional setting knows that the String situation is kind of a mess. While in many ways the language is progressing at a rapid pace and is only ever getting more compelling for commercial use, the String situation is still regarded by many people as the largest problem in the langauge . And for good reason, an efficient textual type is absolutely essential for most work and it’s use needs to be streamlined and language-integrated for a overall positive experience writing industrial Haskell. Let us a consider a logical assessment of why the String Situation exists, how far we can get with workarounds and what’s next. See the accompanying Git project for prototype code: String The String type is very naive, it’s defined as a linked-list of Char pointers. type String = [Char] This is not only a bad representation, it’s quite possibly the least efficient (non-contrived) representation of text data possible and has horrible performance in both time and space. And it’s used everywhere in Haskell. Even posterchild libraries for Haskell (Pandoc, etc) use it extensively and have horrible performance because of it. Around 2005-2007 several more efficient libraries were written, that included Bytestring and Text and both have different use-cases. Both are orders of magnitude more efficient and have become the ubiquitous in “Modern Haskell”. Combined with the recent -XOverloadedStrings language extension we have a partial solution for routing around the problem. {-# LANGUAGE OverloadedStrings #-} import qualified Data.Text as T -- From overloaded string literal. foo :: T.Text foo = "bar" Unfortunately conversion between the efficient string types and String is /(O(n)/) and involves a deep copy. They’re still not used ubiquitously, and every introductory book on the subject still uses String instead of the modern libraries because it’s provided by default. So why is String still used? Because it’s too convenient and it has special powers from being wired-in to the compiler. Banishing String You can get pretty far working in a subset of the Prelude and blessed libraries that have nearly removed old historical cruft like String and banished the ugly parts of the Prelude. However one will end up using String in few noticeable dark corners. - Show instances - Read instances - Pretty printers - FilePath - Third party libraries written before 2007. Older core libraries are getting slowly phased out, this is a social problem not a technology problem. This seems to be going in the right direction on it’s own. FilePaths are not hard to swap out and not a huge concern. Show typeclasses and Pretty printers are the probably the singularly biggest source of continued [Char] usage and what we’ll concern ourselves with here. Show The Show class is really useful, and automatically deriving show much boilerplate is part of the reason Haskell is so much fun to write. However it’s current status poses a bit of a problem transitioning to modern types for several reasons: - It’s abused to write custom pretty printers. - It’s relation to the Read class is problematic. - It’s constrained to use [Char]and forces that choice on downstream users, who end up forced to use it in places it shouldn’t be used. So what is Show class really, it’s so successful that a lot of people actually never look at it’s internals. The guts of it is a function called showPrec which is a overloaded CPS’d function which composes together a collection of string fragments for specific implementations of the Show typeclass. type ShowS = String -> String class Show a where showsPrec :: Int -> a -> ShowS show :: a -> String showList :: [a] -> ShowS {-# MINIMAL showsPrec | show #-} Together with the Read class we get a textual serializer and deserializer for free with the laws governing that relation being: read . show = id GHC can almost always derive this automatically and the instance is pretty simple. Using -ddump-deriv we can ask GHC to dump it out for us. λ> :set -ddump-deriv λ> data List a = Nil | Cons a (List a) deriving (Show) instance Show a => Show (List a) where showsPrec _ Nil = showString "Nil" showsPrec a (Cons b1 b2) = showParen (a >= 11) $ showString "Cons " . showsPrec 11 b1 . showSpace . showsPrec 11 b2 showList = showList__ (showsPrec 0) The emergant problem this is that there are an enormous number of pathological Show instances used in practice, and you don’t need to look even beyond the standard library to find law violations. This coupled with the fact that Read instance is really dangerous, it’s use of a very suboptimal String type means that it’s inefficient and opens up security holes and potential denial-of-service attacks in networked applications. Show should really only to be used for debugging the structure of internal types and used at the interactive shell. For serializing structures to text in a way that differs from Haskell’s internal representation we need a pretty printer. Pretty Printers The correct way of writing custom textual serializes is through the various pretty-print combinator libraries that stem from Wadler’s original paper A prettier printer . There are some degrees of freedom in this design space, but wl-pprint-text is a good choice for almost all use cases. Using the underlying Data.Text.Lazy.Builder functions is also a sensible choice. So for example if we have a little λ-calculus… data Expr = Var Text | Lit Lit | App Expr Expr | Lam Text Expr data Lit = LInt Int | LBool Bool We can write down a pretty printer quite simply using the provided combinators. See the gist here for the full example. class Pretty a where pretty :: Int -> a -> Doc instance Pretty Lit where pretty _ (LInt n) = int n pretty _ (LBool b) = bool b instance Pretty Expr where pretty _ (Var x) = text x pretty p (Lit x) = pretty p x pretty p e@(App _ _) = let (f, xs) = viewApp e in let args = sep $ map (pretty (p+1)) xs in parensIf (p>0) $ pretty p f <+> args pretty p e@(Lam _ _) = let body = pretty (p+1) (viewBody e) in let vars = map text (viewVars e) in parensIf (p>0) $ "//" <> hsep vars <+> "." <+> body ppexpr :: Expr -> Text ppexpr x = PP.displayT (PP.renderPretty 1.0 70 (pretty 0 x)) So that’s how it should be done. In practice to do this you’d have to setup a cabal/stack project, install 11 dependencies, write a new typeclass, and write this little joy of a import preamble masking several functions that conflict in the Prelude namespace. import Data.Monoid import Data.Text.Lazy (Text) import Data.Text.Lazy.IO as TL import Text.PrettyPrint.Leijen.Text hiding ((<$>), (<>), Pretty(..)) import qualified Text.PrettyPrint.Leijen.Text as PP This kind of sucks. It’s the right thing to do, but it’s kind of painful and it’s certainly not intuitive for newcomers. Abusing Show and String is easier, worst practices should be hard but in this case they are much easier than doing the correct thing. Progress :: String → Text GHC has had the capacity to support custom Preludes for a while and this is a very wise design choice. For all the historical brokenness of certain things, there are very few technological hurdles to replacing them with modern sensible defaults. The question then remains how close can we come to replacing Show with a Text-based equivalent. The answer is about 80% before surgery is required on GHC itself. The translation of a Text-based show prototype is just one module. Instead of concatenating Strings we use the Text.Builder object to build up a Text representation. The ShowS function now just becomes a Builder transformation. import Data.Text.Buildable (build) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TB type ShowS = TB.Builder -> TB.Builder class Show a where showsPrec :: Int -> a -> ShowS show :: a -> TL.Text show x = TB.toLazyText (shows x "") The various builtin types have builder objects implemented by Buildable that efficiently render to Text. instance Show Integer where showsPrec _ n f = build n <> f instance Show Float where showsPrec _ n f = build n <> f instance Show Double where showsPrec _ n f = build n <> f instance Show Bool where showsPrec _ True = showText "True" showsPrec _ False = showText "False" For constructors with parameters there is a very mechanical translation that is exactly like how deriving Show works for String. con0 :: Text -> ShowS con0 = showText con1 :: Show a => Text -> Int -> a -> ShowS con1 con p x = showParen (p > appPrec) $ showText con . showsPrec appPrec1 x instance Show a => Show (Maybe a) where showsPrec _ Nothing s = con0 "Nothing" s showsPrec p (Just x) s = con1 "Just " p x s Since it’s easy to generate the boilerplate instances, we can use Generics to auto-derive the instance for any sum/product type expressible in Haskell and have a DefaultSignature for showsPrec . class Show a where showsPrec :: Int -> a -> ShowS show :: a -> TL.Text default showsPrec :: (Generic a, GShow (Rep a)) => Int -> a -> ShowS showsPrec i x = gshowsPrec Pref i (from x) show x = TB.toLazyText (shows x "") And then some ugly (but mechanical) builder munging gives us an exact copy of GHC’s show format. The little known -XDeriveAnyClass can be used to derive any other class that has an empty minimal set or uses DefaultSignatures and Generic instances to implement methods. class GShow f where gshowsPrec :: Type -> Int -> f a -> ShowS basic :: f a -> Bool basic _ = False instance GShow U1 where gshowsPrec _ _ _ = id basic _ = True instance Show c => GShow (K1 i c) where gshowsPrec _ i (K1 fp) = showsPrec i fp instance (GShow f, Constructor c) => GShow (M1 C c f) where gshowsPrec t i c@(M1 fp) | conIsRecord c = showString (conName c) . showChar ' ' . showBraces (gshowsPrec Rec i fp) | otherwise = case conFixity c of Prefix -> showParen (i > appPrec && not (basic fp)) $ showString (conName c) . if basic fp then id else showChar ' ' . gshowsPrec t appPrec1 fp Infix _ m -> showParen (i > m) $ showBraces (gshowsPrec t m fp) instance (GShow f, Selector c) => GShow (M1 S c f) where gshowsPrec t i c@(M1 fp) = case t of Pref -> gshowsPrec t i fp Inf _ -> gshowsPrec t i fp Rec -> showString (selName c) . showText " = " . gshowsPrec t i fp instance (GShow f) => GShow (M1 D c f) where gshowsPrec t i (M1 fp) = gshowsPrec t i fp instance (GShow f, GShow g) => GShow (f :+: g) where gshowsPrec t i (L1 fp) = gshowsPrec t i fp gshowsPrec t i (R1 fp) = gshowsPrec t i fp instance (GShow a, GShow b) => GShow (a :*: b) where gshowsPrec t@Rec n (a :*: b) = gshowsPrec t n a . showText ", " . gshowsPrec t n b gshowsPrec t@Pref n (a :*: b) = gshowsPrec t (n+1) a . showChar ' ' . gshowsPrec t (n+1) b gshowsPrec t@(Inf s) n (a :*: b) = gshowsPrec t n a . showText s . gshowsPrec t n b And there we have it, a fixed show function that is drop-in compatible with the existing format but uses Text… show :: Show a => a -> Text … and has automatic deriving. data List a = Nil | Cons a (List a) deriving (Generic, Print.Show) We can even go so far as to tell GHCi to use our custom function at the Repl by adding the following to our projects .ghci file. import Print :set -interactive-print=Print.print However GHC’s defaulting mechanism has a bunch of ad-hoc specializations for wired-in classes that don’t work for user-defined clases. If we type in an under-specified expression for Show, GHC will just splice in a show dictionary for the unit type Show () if it can’t figure out an appropriate dictionary. λ> print Nothing ==================== Simplified expression ==================== bindIO (ghciStepIO $fGHCiSandboxIOIO (print ($fShowMaybe $fShow()) (Nothing))) (/ (it :: ()) -> returnIO (: it ([]))) For our implementation: λ> print Nothing <interactive>:3:1: No instance for (Show a0) arising from a use of ‘print’ The type variable ‘a0’ is ambiguous Note: there are several potential instances: instance (Show a, Show b) => Show (Either a b) -- Defined at Print.hs:233:10 instance Show a => Show (Maybe a) -- Defined at Print.hs:229:10 instance Show Int16 -- Defined at Print.hs:160:10 ...plus 27 others In the expression: print Nothing In an equation for ‘it’: it = print Nothing There’s currently no way to do this for a custom Show type. This implementation also requires a Generic instance and several language extensions. This is the hard limit to how far we can go in “user space”. Implementation What we can prototype with Generics today is not hard to translate over into a builtin deriving mechanism inside the compiler tomorrow. In fact we can create a compatibility layer so close the existing Show class deriving that we reuse all of it’s logic sans the type changes. module Print ( Show(showsPrec, show), ShowS, showChar, showText, showList, showList__, showParen, shows, ) where Right now in GHC there is a hasBuiltinDeriving that checks if the derived class is one of the blessed “builtins” that has a prescription for deriving a class instance for it. The blessed classes include: If the public interface for generating a Text-Show instance recycled the same structure as String version, we could very easily write gen_ShowText_binds and plug this into the compiler to derive a new (distinct) text Show that wouldn’t break compatibility. However, at the moment text isn’t in GHC’s boot libraries and can’t be made into wired-in type which would be necessary to add the new deriving mechanism to TcGenDeriv.hs . So that’s as far as we can go in 2016, there’s probably a fairly clear path to removing Stringy-Show if text were to at some point become accessible to GHC internals. 评论 抢沙发
http://www.shellsec.com/news/26479.html
CC-MAIN-2018-09
refinedweb
2,307
58.52
Removes a layer from the stack. Syntax #include <prio.h> PRFileDesc *PR_PopIOLayer( PRFileDesc *stack, PRDescIdentity id); Parameters The function has the following parameters: stack - A pointer to a PRFileDescobject representing the stack from which the specified layer is to be removed. id - Identity of the layer to be removed from the stack. Returns The function returns one of the following values: - If the layer is successfully removed from the stack, a pointer to the removed layer. - If the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function returns NULLwith the error code PR_INVALID_ARGUMENT_ERROR. Description PR_PopIOLayer pops the specified layer from the stack. If the object to be removed is found, PR_PopIOLayer returns a pointer to the removed object The object then becomes the responsibility of the caller. Even if the identity indicates the top layer of the stack, the reference returned is not the file descriptor for the stack and that file descriptor remains valid. In other words, stack continues to point to the top of the stack after the function returns.
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_PopIOLayer
CC-MAIN-2019-22
refinedweb
181
53.21
United Technologies Corp (Symbol: UTX). So this week we highlight one interesting put contract, and one interesting call contract, from the June 2018 expiration for UTX. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $105 strike, which has a bid at the time of this writing of $2.48. Collecting that bid as the premium represents a 2.4% return against the $105 commitment, or a 4% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Turning to the other side of the option chain, we highlight one call contract of particular interest for the June 2018 expiration, for shareholders of United Technologies Corp (Symbol: UTX) looking to boost their income beyond the stock's 2.4% annualized dividend yield. Selling the covered call at the $125 strike and collecting the premium based on the $2.74 bid, annualizes to an additional 4% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 6.4% annualized rate in the scenario where the stock is not called away. Any upside above $125 would be lost if the stock rises there and is called away, but UTX shares would have to climb 6.5% from current levels for that to occur, meaning that in the scenario where the stock is called, the shareholder has earned a 8.9% return from this trading level, in addition to any dividends collected before the stock was called. Top YieldBoost UTX.
http://www.nasdaq.com/article/one-put-one-call-option-to-know-about-for-united-technologies1-cm876467
CC-MAIN-2017-47
refinedweb
259
61.77
We were a family of four (two adults and two teenagers) that stayed during the recent October half term break. We stayed in number 1 lodge (I think there are not far off 30 lodges on site) which was a 3 bedroom lodge with a hot tub. We arrived at approximately 4pm which is the usual check in time for the lodges and were welcomed by a very friendly team of people and nothing was too much trouble for them. The lodge itself was superb and very spacious. Even though we had suffered a week of relatively bad weather we still managed to get out into the hot tub every day of the trip - these were checked at least 2 or 3 times a day. The attention to detail and cleanliness of the lodge could not be faulted with pretty much every facility available you'd expect at home. There was a lovely welcome pack available to us on arrival with some local chocolates, water, bread/milk/butter and dishwasher tablets and washing up liquid etc. Free wifi is available via a voucher from reception. Beware if you do rely on a mobile phone signal as there was none on site and the surrounding area is a bit patchy. Perhaps this is something that can be addressed for the future (although I understand there are some who would prefer to keep the modern conveniences away from them while on holiday!) The surrounding area was beautiful and it was literally a two minute walk to the nearby Mullion Cove harbour which was quite old fashioned and frozen in time somewhat. There was a small cafe in the harbour which looked lovely but we didn't find the time to try it and a chocolate factory and shops another 5 mins walk up the road from the site. The village of Mullion could also be walked to in around 10-15 mins and had a couple of decent pubs and various shops for convenience goods. Probably the nearest larger supermarket was in Helston around a 15 min drive from the site. We managed to find a lovely Thai takeaway who delivered for free to the site nearby (order over the phone/wifi) if you like that sort of thing. We did chat to the manager on site who was very friendly and accomodating and mentioned a couple of things to perhaps improve the lodges but these were minor issues - lack of shaver socket and perhaps a little bit more privacy/light blocking from our particular master bedroom when the owners of the adjacent lodge left their outside lights on a few nights we were there which caused my wife who is a light sleeper to lose a bit of sleep - but other than that I would say this is a perfect relaxing site and we would love to return (perhaps during better weather) and I hope the owners keep up the great work and keep improving the site as it stands. - Official Description (provided by the hotel): - Mullion cove lodge park is located nestled above the picturesque harbour of Mullion cove. We have 28 lodges available to hire for 3,4 and 7 nights. The lodges range from 1 - 4 bed rooms and premier units have hot tubs. We allow pets in selected lodges also.On a self catering basis we offer our guests a home from home experience with all the mod cons you would expect. The kitchens are equipped with washer dryers as well as dishwashers. Central heating throughout and panoramic full length glass patio windows help achieve a warm feel to the lodge. Mullion cove has fantastic walking routes and is nestled within easy reach of local pubs and shops. Wifi is available free of charge to guests and parking is also free. ... more less - Reservation Options: - TripAdvisor is proud to partner with Booking.com and Priceline so you can book your Mullion Cove Lodge Park reservations with confidence. We help millions of travelers each month to find the perfect hotel for both vacation and business trips, always with the best discounts and special offers. - Also Known As: - Mullion Cove Lodge Park Cornwall
https://www.tripadvisor.com/ShowUserReviews-g528860-d5001546-r183675346-Mullion_Cove_Lodge_Park-Mullion_Cornwall_England.html
CC-MAIN-2017-22
refinedweb
694
64.44
Agenda See also: IRC log, previous 2008-02-14 Ralph: Shane has been working on the /vocab namespace document ... he's given me a draft ACTION: [DONE] Shane send response to Diego and Ed review comments when new editors' draft is up [recorded in] ACTION: Ben to add status of various implementations on rdfa.info [recorded in] [CONTINUES] ACTION: Ben to email mailing list to think about last substantive issue on tracker: [recorded in] [CONTINUES] ACTION: Manu write 2 new tests for img[@src] as subject [recorded in] [CONTINUES] ACTION: Michael to create "Microformats done right -- unambiguous taxonomies via RDF" on the wiki [recorded in] <msporny> just FYI, #78-#83, #87 PASS using Ivan and my latest implementations. <msporny> so you don't have to worry about syntax issues in those test cases. <markbirbeck> #78 is fine. <markbirbeck> Minor points that they are easier to read if everything is in the same order in all blocks (HTML, N3, RDF and SPARQL) but that's my only comment. Ralph: Ben was happy with test 78 on 7-Feb RESOLUTION: Test 78 accepted <msporny> Ben's replies to test cases 85-87 <markbirbeck> #79 is good, too. <markbirbeck> Again, minor point... <markbirbeck> ...don't see what the super-abbreviation gains in the N3 block. :) <markbirbeck> Makes it slightly harder to read when comparing with the HTML. <markbirbeck> But minor point again. Manu: we don't believe the N3 yet; focus on the SPARQL <msporny> N3 is generated by Ivan's parser, plus it's informative, no need to pay attention to it yet. Manu: N3 in test 79 looks correct, though it's unreadable as is RESOLUTION: Test 79 accepted <markbirbeck> #80 looks lovely. :) (Ben was happy with 80 on 7-Feb too ) RESOLUTION: Test 80 accepted <markbirbeck> #81 is very smart...and seems right to me. <markbirbeck> #82 also looks ok to me. <markbirbeck> Minor point is that in the SPARQL in other tests, the square bracket syntax has generally been used, whilst here we're using "_:a" and "_:b". <markbirbeck> Minor point again, though. [some discussion of what "substantive change" means] <markbirbeck> (Compare to #83, for example.) <msporny> mark, be sure to skip #84, #85, and #88 <markbirbeck> #83 is good. <markbirbeck> ok Ralph: Ben was happy with 81 and wanted to check his implementation RESOLUTION: Test 81 accepted Ralph: Ben was fine with 82 after typo fixes Manu: Ivan has written some SPARQL using the '[...]' syntax where we've been using bnode syntax Manu: we might want to update test 83 to use bnode syntax RESOLUTION: Test 82 accepted Manu: let's rewrite 83 to use named bnodes ... skip 84 and 85 for now due to syntax errors <msporny> correct, mark - #86 is our first FALSE test for the SPARQL. <markbirbeck> On #86, we might want to make the query check for { <> ?p <mailto:ivan@w3.org> } <markbirbeck> The rule is that @rel="foobar" should generate nothing, not just that it shouldn't generate anything in the XHTML vocab namespace. <markbirbeck> (And obviously in #86 we're testing for 'no matches', as opposed to a match.) <markbirbeck> I'm not quite following #87...is there a similar test without the colon prefix? I.e., is this to test that that we support two means of expressing the same predicates? <ShaneM> there is a similar test without a colon Ralph: did we want our tests to allow implementations to produce "additional" triples <markbirbeck> Either way, minor point would be that in general the items are in alphabetical order, which makes it handy for double-checking...so perhaps the few stray ones could be put into order. Manu: yes, but not in the default graph ... we haven't said that we test [only] for triples in the default graph Ralph: in that case I like Mark's suggestion to use ?p in the SPARQL ... so there's NO relationshp between #somebody and ivan Manu: that makes sense to me <markbirbeck> (Still on #87...) Secondly, we might consider using <base> in the test, so that we're not tied to where these tests are being run from, and to abbreviate the SPARQL. <msporny> SPARQL for test #86: <msporny> ASK WHERE { <msporny> <> ?p <mailto:ivan@w3.org> . <msporny> } <msporny> That test should return FALSE. <markbirbeck> And third (on #87) we might consider adding an item that is not in the list of vocab values, since this is *allowed* when using the ":foo" syntax. RESOLUTION: test 86 accepted with change to ?p <msporny> Mark, shouldn't that be a separate test? <markbirbeck> That's all from me...I'll try to keep an eye out if you need me for anything else. <msporny> testing ":foo" syntax? <msporny> thanks :) <markbirbeck> Good point. <markbirbeck> Yes, could be. <msporny> I think we should make that a separate test... <markbirbeck> Basically, whilst @rel="foo" should *fail*, @rel=":foo" should *succeed*. Shane: remember, :foo _always_ uses /vocab#; there's no way to change the CURIE prefix Manu: should we test @rel="foo" to insure that the code isn't using the same branch as @rel=":foo" ? ... i.e. to test a misunderstanding of the document ACTION: Manu create unit test to make sure that rel=":foo" generates a triple. [recorded in] Ralph: do we have a test for @rel="foo" ? Manu: yes, test 86 ... test 87 is missing stylesheet ... as do tests 76, 77 ACTION: Manu let Michael know that Test 76, 77, and 87 are missing stylesheet. [recorded in] Ralph: for those cases in test 87 where the reserved word plausibly has a reasonable value, we should use it ... thought that's a nit ... so how about just a comment noting that these test values are not semantically reasonable RESOLUTION: test 87 accepted, after realphabetizing -> Michael re: implementor's call Ralph: the "call" that I think Michael is asking about is the "Candidate Recommendation" transition ... CR is a "call for implementation" ... we should document how we'd like implementers to report their implementation experience ... this can go in the SOTD of the CR draft Ralph:I believe issue 6 has a specified answer but I want to gather definitive pointers before declaring it closed. ACTION: Manu write a response to Christian Hoertnagl for issue 7 [recorded in] Ralph: we've chosen to defer RDF Container support RESOLUTION: issue 8 is POSTPONED Ralph: we resolved this last telecon [adjourned]
http://www.w3.org/2008/02/21-rdfa-minutes.html
CC-MAIN-2013-48
refinedweb
1,062
71.75
30 November 2009 By clicking Submit, you accept the Adobe Terms of Use. Experience building Flex applications is recommended. Intermediate In this article I present some of the basics for getting started with Test Driven Development (TDD) using Flash Builder 4 and FlexUnit. As Flash applications become more dynamic and complex, they become more difficult to maintain and scale, particularly when business requirements change throughout the course of development. These challenges are significant and they are common in all types of development, including mobile, web, and desktop applications. Consider a scenario in which you need to make changes to a large application to meet new business requirements. How do you know if the small changes you made broke other parts of the application? How can you ensure that the code is bullet-proof, especially if you are not the person who wrote it? For software engineers, this problem is neither new nor confined to a specific platform. Java and ASP developers have been challenged with the same issues and have found Test Driven Development (TDD) a useful technique for creating applications that can be easily maintained. Flash has grown a long way from a small animation tool. The Adobe Flash Platform now comprises an ECMAScript-compliant programming language as well as methodologies common to other programming languages that are necessary for building large dynamic applications. In fact, Adobe and many other companies have found that TDD solves many of the challenges that developers face in their development cycles every day. I have noticed that while many developers have heard of TDD, they are reluctant to use TDD because they are unfamiliar with it and afraid that using TDD will increase development time. In my personal experience, I have found that using TDD correctly doesn't increase development time when used on projects for which it is appropriate. In fact, TDD can reduce development time and simplify application maintenance. I've also found that I can use FlexUnit on existing applications and apply TDD methods to any framework out there in some way or another. It is important to note that TDD is applicable even when there is a separate Quality Assurance (QA) department that performs formal testing. TDD helps developers deliver more solid code, enabling QA to focus on other tasks, including testing the user interface and creating the use cases that they need to test. So what is TDD anyway? Test Driven Development is a software development technique in which programmers writing failed test that will define the functionality before writing the actual code. Note that using FlexUnit you often write the test after writing the code since many times you will be adding tests to existing code. In Extreme Programming teams work on the development of dynamic projects with changing requirements and a development cycle that includes TDD for writing the test before the code itself. Note that TDD is not the complete development cycle; it is only part of the Extreme Programming (XP) development paradigm. Preparing the tests before writing the code helps a development team to demonstrate their work in small steps, rather than making the customer or other stakeholders wait for the complete result. Moving in small increments also makes it easier to accommodate changing requirements and helps ensure that your code does what it needs to do, and nothing more. It is important to mention that the focus of the TDD technique is to produce code and not to create a testing platform. The ability to test is an added benefit. TDD is based on the idea that anything you build should be tested and if you are unable to test it, you should think twice about whether you really want to build it. The TDD process consists of six simple steps (see Figure 1): FlexUnit is a unit testing framework for Flex and ActionScript 3.0 applications and libraries. It offers functionality similar to JUnit, a Java unit testing framework. FlexUnit is used in many internal Adobe projects and is open source. Flash Builder 4 provides integrated FlexUnit support, and allows you to create the scaffolding of the test unit automatically, saving you time, eliminating the need to create the same classes over and over again, and ensuring the use of best practices. There are two versions of FlexUnit: FlexUnit 0.9 (also referred to as FlexUnit 1) and FlexUnit 4 (also referred to as FlexUnit 4). This article covers FlexUnit 4. To use FlexUnit in previous versions of Flex Builder you had to download the FlexUnit SWC file and include it in your project. Flash Builder 4 includes five SWCs automatically once you create tests. The following SWCs will be added under your project's Referenced Libraries: These SWCs include all the APIs for FlexUnit 0.9, FlexUnit 4, the test runner, and other libraries. The SWCs are maintained as part of the Flex 4 SDK so there is no need to download FlexUnit or add them manually. They will be added automatically once you add the tests. In this section you will use Flex Builder 4 with FlexUnit 4 to create a test suite and test case. To illustrate how to use FlexUnit in Flash Builder, I will use a simple application that calculates numbers. Follow these steps to create the application and add a test suite: A test suite is a composite of tests. It runs a collection of test cases. During development you can create a collection of tests packaged into test suite and once you are done, you can run the test suite to ensure your code is still working correctly after changes have been made. Note: Although in Extreme Programming you are encouraged to write tests before creating the code (and ideally that's how you should work), in real life there are many times where you will find yourself writing the tests after the code. Such decisions are made case by case, and it is OK to adjust the methodology to fit your workflow. Flash Builder 4 added the following class under the flexUnitTests folder: package flexUnitTests { [Suite] [RunWith("org.flexunit.runners.Suite")] public class CalculatorTestSuite { } } The Suite metadata tag indicates that the class is a suite. The RunWith tag instructs the test runner to execute the tests that follow it using a specific class. FlexUnit 4 is a collection of runners that will run a complete set of tests. You can define each runner to implement a specific interface. You can, for example, specify a different class to run the tests instead of the default runner built into FlexUnit 4. Create the Test Case class: Note: In FlexUnit 1 you can choose to generate setUp() and tearDown() stubs. These stubs are called automatically when the test case starts (setUp) and ends (tearDown). They can be used to set up information and events before the test starts and clear information and events to ensure you don't have any memory leaks. In FlexUnit 4 you can define these methods using the metadata tags [Before] and [After], as you will see later in this article. In the next dialog box (see Figure 5) you select the methods you would like to test. additionMethod. You are ready to start writing test code. Open CalculatorLogicTester.as and notice that the test method for additionMethod has been created for you. In FlexUnit 1, each method you create must start with "test", to enable the test runner to recognize the method. As a result, the method name was changed to testAdditionMethod. In FlexUnit 4, method names do not need to start with "test"; instead they are recognized by the [test] metadata, so feel free to refactor the method names. Here is the generated code: package flexUnitTests { public class CalculatorLogicTester { [Before] public function setUp():void { } [After] public function tearDown():void { } [BeforeClass] public static function setUpBeforeClass():void { } [AfterClass] public static function tearDownAfterClass():void { } } } Lastly, remember to add the test case you would like to test into the CalculatorTestSuite test suite. Add the line in bold below to CalculatorTestSuite.as: package flexUnitTests { [Suite] [RunWith("org.flexunit.runners.Suite")] public class CalculatorTestSuite { public var calculatorLogic:CalculatorLogicTester; } } Build the project. To run the application, follow these steps: As you can see, the test failed because you had the following code in CalculatorLogicTester.as: Assert.fail("Test method Not yet implemented"); Edit additionMethod() to return zero since we are not writing the code yet. Make the method static and the class final as shown below: package com.elad.calculator.utils { public final class CalculatorLogicHelper { public static function additionMethod(value1:Number, value2:Number):Number { return 0; } } } Also update the testAdditionMethod stub to produce a fail result: var result:Number = CalculatorLogicHelper.additionMethod(5,5); Assert.assertEquals(result,10); The assertEquals method will fail because the method additionMethod code hasn't been implemented yet. Run the application and see the fail result (see Figure 10). A message shows the problem (Error: expected: <10> but was <0>) and the failed method (testAdditionMethod). Under the application folder structure you can find the files CalculatorLogicTester.as, CalculatorTestSuite.as, and FlexUnitCompilerApplication.mxml (see Figure 11). Take a look at FlexUnitApplication.mxml: <!-- This is an auto generated file and is not intended for modification. --> <s:Application xmlns: <fx:Script> <![CDATA[ import flexUnitTests.CalculatorLogicTester; public function currentRunTestSuite():Array { var testsToRun:Array = new Array(); testsToRun.push(flexUnitTests.CalculatorLogicTester); return testsToRun; } private function onCreationComplete():void { testRunner.runWithFlexUnit4Runner(currentRunTestSuite(), "CalculatorApplication"); } ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <flexui:FlexUnitTestRunnerUI </flexui:FlexUnitTestRunnerUI> </s:Application> As you can see there is a GUI called FlexUnitTestRunnerUI, which is similar in functionality to the FlexUnit TestRunner class in FlexUnit 0.9. Essentially, the application adds the entire test and runs the test in the UI. In FlexUnitApplication.mxml you can see that FlexUnit uses the FlexUnit 4 runner: private function onCreationComplete():void { testRunner.runWithFlexUnit4Runner(currentRunTestSuite(), "CalculatorApplication"); } However, the framework is flexible, so developers can create and use their own runners, but still use the same UI. In fact, currently there are runners for FlexUnit 1, FlexUnit 4, Fluint, and SLT. The test runner in FlexUnit is a UI component that will create an instance of the test suite and allow you to add all the tests you would like to run. The test runner will also display the test information in your browser. Note: There is currently a test runner for Flex applications but not for pure ActionScript applications. You can, however, create a Flex project to test your pure ActionScript code or use Ant tasks. See for more information. In addition to the files you see in the Project Navigator there are more under the surface, including: These classes handle tasks such as the binding, styles, and definitions for FlexUnit. Note: The bin-debug/generated package holds all files that get created by the MXMLC compiler and are normally invisible to you. To see them, select the project, then right-click and select Properties. Under Flex Compiler in Additional Compiler Arguments add the following option: -keep-generated-actionscript or -keep-generated-actionscript=true. You are now ready to proceed with step 3 of the TDD process. Now that the test failed you can write code to pass the test. The code you write should be the minimum code to get the test to pass. Add additionMethod() to return the sum of two numbers: Create the utility class by following these steps: package com.elad.calculator.utils { public final class CalculatorLogicHelper { public static function additionMethod(value1:Number, value2:Number):Number { var retVal:Number = value1+value2; return retVal; } } } Now without any changes to the testAdditionMethod test method it passes and you will get a green light, meaning the test has succeeded (see Figure 12). Now that your test passed you can refactor the code in order to get it ready for production. For instance, you may add a design pattern to replace a block of if..else statements. In this case there is nothing to refactor since the code is so simple. You can continue to create the unit tests for the subtraction, multiplication, and division methods. The complete code is below: package com.elad.calculator.utils { public final class CalculatorLogicHelper { public static function additionMethod(value1:Number, value2:Number):Number { var retVal:Number = value1+value2; return retVal; } public static function subtractionMethod(value1:Number, value2:Number):Number { var retVal:Number = value1-value2; return retVal; } public static function multiplicationMethod(value1:Number, value2:Number):Number { var retVal:Number = value1*value2; return retVal; } public static function divisionMethod(value1:Number, value2:Number):Number { var retVal:Number = value1/value2; return retVal; } } } The complete unit test class code is in the CalculatorLogicTester.as file included with the sample files for this article. So far you have used only the assertEquals assertion method in the test cases. There are, however, many other assertion methods (see Table 1). Table 1. Available assertion methods in FlexUnit 1 and FlexUnit 4. To use an assertion method, pass a string message and two parameters to compare. The string is the message to be used if the test fails. For example: assertEquals("Error testing the application state", state, 1); If you omit the message string, you'll get the default message. In the editor, type Assert. to see code hints for the available assertion methods. In addition to the standard assertions FlexUnit 4 supports new methods thanks to the Hamcrest library, which is based on the idea of matchers. Each matcher can be set to match conditions for your assertions. Here is an example taken from Drew Bourne's project that tests whether one number is close to (within a specified threshold) of another number: package org.hamcrest.number { import org.hamcrest.AbstractMatcherTestCase; public class CloseToTest extends AbstractMatcherTestCase { [Test] public function comparesValuesWithinThreshold():void { assertMatches("close enough", closeTo(1, 0.5), 1.5); assertDoesNotMatch("too far", closeTo(1, 0.5), 1.6); } [Test] public function hasAReadableDescription():void { assertDescription("a Number within <0.1> of <3>", closeTo(3, 0.1)); } } } Now that you have a class that can handle all the basic operations of a calculator and you have test cases for the methods, you can implement a simple calculator application (see Figure 13). Take a look at the sample code in CalculatorApplication.mxml, which uses the utility class. The FlexUnit 4 framework is based on metadata tags. So far you've seen [Suite], [Test], and [RunWith]. Here are some other common metadata tags: [Ignore] - Causes the method to be ignored. You can use this tag instead of commenting out a method. [Before] - Replaces the setup() method in FlexUnit 1 and supports multiple methods. [After] - Replaces the teardown() method in FlexUnit 1 and supports multiple methods. [BeforeClass] - Allows you to run methods before a test class. [AfterClass] - Allows you to run methods after a test class. The calculator example was intentionally simple to help you get up to speed with TDD. This section covers a practical overview of FlexUnit metadata that you can use on more complex projects. To begin, create a new FlexUnit 4 Test Case class and name it FlexUnitTester. Copy the code from the FlexUnitTester.as sample file into the new class. The method following the Before metadata will be run before every test, and the method following After tag will be run after every test: [Before] public function runBeforeEveryTest():void { // implement } [After] public function runAfterEveryTest():void { // implement } The following example demonstrates the expected attribute of the Test metadata. The rangeCheck method creates a new Sprite object. The code will produce a successful test, because the child at index 1 doesn't exist and thus the code causes an exception during runtime. [Test(expected="RangeError")] public function rangeCheck():void { var child:Sprite = new Sprite(); child.getChildAt(1); } Here is another example that shows an expected assertion error. The testAssertNullNotEqualsNull Test expects an AssertionFailedError error. The test will fail, because the assertEquals method will succeed (since null equals null). [Test(expected="flexunit.framework.AssertionFailedError")] public function testAssertNullNotEqualsNull():void { Assert.assertEquals( null, null ); } In FlexUnit 1 you had to comment out code to ignore a method that you didn't want to test any more. The Ignore metadata tag makes it easier to skip a method. [Ignore("Not Ready to Run")] [Test] public function methodNotReadyToTest():void { Assert.assertFalse( true ); } If you want to set the order of Test, Before, or After methods, you can add the order attribute, like this: [Test(order=1)] public function checkMethod():void { Assert.assertTrue( true ); } If you've worked with FlexUnit 1 in the past, you know that it isn't always easy to create asynchronous tests and test event driven code. I often found myself modifying existing classes just to accommodate FlexUnit or creating tests in a hackish way. One of Fluint's biggest advantages is the ability to accommodate multiple asynchronous events. FlexUnit 4 incorporated Fluint functionality to support enhanced asynchronous tests, including asynchronous setup and teardown. This feature can be used by every test stub. To see this feature in action, create a new Test Case Class, name it AsynchronousTester, and copy in the code from the AsynchronousTester.as sample file. This example tests a service call. The testServiceRequest() function makes a service call to retrieve an XML file that is included with the project. The test sets a timeout to specify the amount of time to wait before it fails. The ResultEvent fires before the timeout is reached and the test succeeds. In the second test, testFailedServiceRequest(), the service request asks a file that doesn't exist. Since the check is for the fault event the test passes, as expected. The last test is for a scenario in which multiple asynchronous calls are made. FlexUnit 4 introduces the concept of theories. A theory, as the name suggests, allows you to create a test to check your assumptions about how a test should behave. This type of test is useful when you have to test a method that can return large or even unbounded values. The tests take parameters (data points) and these data points can be used in conjunction with each test. You can use this functionality to check if the results are within a specified range. To see how it works, create a new Test Suite Class, name it FlexUnit4TheorySuite, and copy in the code from FlexUnit4TheorySuite.as, which includes the following: [Theory] public function testNumber( number:Number ):void { assumeThat( number, greaterThan( 0 ) ); assertThat( number, instanceOf(Number) ); } In this case, the theory checks that the number is greater than zero and verifies the variable type. Although it may be disputable if UI testing is part of TDD, in FlexUnit 4 you have the ability to create tests that can check user interfaces and MXML components. FlexUnit 4 includes the concept of sequences, and you can create sequences that include all the operations you would like to perform on a UI. The FlexUnit4CheckUITester.as sample file shows an example of this functionality. The setUp method creates a component that holds a button. Next, instead of adding the component to the view, it calls UIImpersonator.addChild(). The testButtonClick method is a simple async test that sets a handler and dispatches a mouse event. The handler handleClickEvent simply checks the event string type. The second test, testButtonClickSequence, includes a sequence that sets the button's label name. Next, SequenceWaiter instructs the sequence to wait until the button click event is dispatched. Before the event is dispatched, the code calls addAssertHandler( handleButtonClickSqEvent, passThroughData ). The handleButtonClickSqEvent method handles the event and compares the button label of the test with the pass through data. This article covered unit testing and Test Driven Development using Flash Builder 4 and FlexUnit, including some of the new features in the FlexUnit 4 framework. There has been a great deal of interest in TDD (and unit testing in general) recently, because it leads to applications that are easier to scale and maintain and less prone to errors. After learning how to create FlexUnit test suites and test cases, I hope you are inspired to use TDD on your mobile, web, and desktop Flash applications, and write better, more scalable, and more reusable code. For more information on TDD and FlexUnit, see chapter 14 of AdvancED Flash on Devices: Mobile Development with Flash Lite and Flash 10 and chapter 2 of AdvancED Flex 4. For more information on integrating FlexUnit with Continuous Integration (CI) server see FlexUnit4AntTasks. You may also want to check out my article on InsideRIA and the FlexUnit 4 feature overview.
http://www.adobe.com/devnet/flex/articles/flashbuilder_tdd.html
CC-MAIN-2015-06
refinedweb
3,404
54.73
![if gte IE 9]><![endif]> This morning I was working with a web handler request that needs to receive data with a content type of "application/x-www-form-urlencoded". I thought this would be pretty easy, and it was ... until I noticed that I am missing the last character. I am being sent a string that looks normal enough -> field1=AB&field2=CD I am parsing the data from the poRequest:Entity using the command lcData = CAST(poRequest.Entity,OpenEdge.Core.Memptr):GetString(1). Using that command, the value in lcData shows as "field1=AB&field2=C". Notice the 'D' is missing. Originally the data was coming from a .Net HttpClient call. I made the same call using Postman, using x-www-form-urlencoded as the body type, and I receive the same result. To get around the issue for today, I decided to go old school and get the value off of WEB-CONTEXT:FORM-INPUT. When getting the data from there, the full string is retrieved (including the 'D'). Am I doing something wrong in my assignment? Is there a 'better' way to get 'x-www-form-urlencoded' data from the poRequest that I've missed? ContentLength sometimes lies (or isn't 100% accurate). Try def var body as class OpenEdge.Core.Memptr. body = CAST(poRequest:Entity,OpenEdge.Core.Memptr). body:GetString(1,body:Size). This is a bug in the Memptr's GetString() method. It's fixed in 11.7.3. The fix adds the "+ 1" below. /** Returns a string/character representation from a given start position, for the remainder of the data. @param int64 The start potision @return longchar The character/string data requested */ method public longchar GetString(input piStartPos as int64): return GetString(piStartPos, this-object:Size - piStartPos + 1). end. Ok. That being the case, do you think adding poRequest:ContentLength like this CAST(poRequest:Entity,OpenEdge.Core.Memptr):GetString(1,poRequest:ContentLength) would be reliable? Thanks Peter. That appears to work as well. Just to note, the AS Memptr is not old-school MEMPTR, but AS OpenEdge.Core.Memptr. Indeed - I updated my reply to reflect that.
https://community.progress.com/community_groups/openedge_development/f/19/t/38373
CC-MAIN-2018-30
refinedweb
354
60.11
On 17 May 2017 at 18:38, Stephan Houben stephanh42@gmail.com wrote: Hi Sven, But even given that (and I am only speaking for my team), I haven't even seen a use-case for namedtuples in a year. Every time we considered it, people said: "please make it its own class for documentary purposes; this thing will tend to grow faster than we can imagine". Using namedtuple doesn't stop the class from being its "own class". Typical use case: class Foo(namedtuple("Foo", "bar "baz"), FooBase): "Foo is a very important class and you should totally use it.""" def grand_total(self): return self.bar + self.baz And the right (modern) way to do this is from typing import NamedTuple class Foo(NamedTuple): """Foo is a very important class and you should totally use it. """ bar: int baz: int = 0 def grand_total(self): return self.bar + self.baz typing.NamedTuple supports docstrings, user-defined methods, and default values. -- Ivan
https://mail.python.org/archives/list/python-ideas@python.org/message/2VP2AWEJX5YF7JQCLF3T46TZ5LGZAC6L/
CC-MAIN-2020-29
refinedweb
161
63.7
Django is a Python based framework that takes care of a lot of web development hassle. Thank you Adrian Holovaty and Simon Willison. “The web framework for perfectionists with deadlines” It is the easiest back-end framework I have ever had to use so far because it basically does all the heavy-lifting for me; saving me a lot of time and frustration. cause who wouldn’t want a breezy time at work. To properly understand its foundations, I went through the django documentation and followed the practical tutorial there. Another hands-on tutorial I found quite detailed is the Django-girls tutorial. I highly recommend one of these first, or both if you are new to django. Django is a full-stack framework meaning it covers everything in web development; the database, HTML templating and application logic. It’s also pretty easy to learn as you go along. You don’t have to know every nitty-gritty detail in order to work with it. Talk about being warm and beginner friendly Disclaimer: This article assumes you know a little about Django or have began using it. It’s not a how-to beginner guide. Here are my top 3 features: 1.Admin Interface So Django creates an admin interface for your application and you don’t have to lift a single finger. I MEAN!!!. Type the address in your browser and you should see a page like this. Create admin user credentials: You will obviously need user credentials to login as an admin, so create one using the command : Windows: python manage.py createsuperuser in the root of your project. Now to register your app with django’s admin, you have to register the app in the ‘your-app/admin.py’ file like so: from django.contrib import admin from .models import Question admin.site.register(Question) Remember to replace Question with your own model name. To login, use the username and password created with the superuser command. All the Create, Update, Delete actions are readily available in the admin interface. How convenient is that?!? 2. Decorators Decorators can be used to restrict access to views. Django has popular in-built decorators like l ogin_required, has_permission etc. These aren’t the only ones, but I will use login_required for an illustration. Pretend we have an app called blog. For a user to be able to Write, Edit or Delete an article, they should have an account in the app. The model file : models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser class Post(models.Model): author = models. ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) coverimage = models.ImageField(upload_to = 'images/', blank=True, null=True) text = models.TextField() created_date =models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) defpublish(self): self.published_date = timezone.now() self.save() def__str__(self): returnself.title views.py: from django.shortcuts import redirect from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.contrib.auth.decorators import login_required from .models import Post @login_required def post_new(request): if request.method =="POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'articles/post_edit.html', {'form': form}) @login_required def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method =="POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'articles/post_edit.html', {'form': form}) This app has 2 methods; create a new post and edit one. The login_required decorator at the top ensures that a User is logged in before the create and edit methods can be executed. The entire background process automated in just one line. Bliss 🙂 I found this extremely helpful when I wanted more information on view decorators. 3. Django Crispy Forms I mentioned how to use this in my July Favorites and it goes without saying, I love it, especially when I’m having a lazy coding day. “Forms have never been this crispy” Django automates many programming processes. For some, this is heaven sent, but for others who may prefer being in control of the development, Django may not be the best option. Personally, I think it’s a great choice to use when building something complex in a tight deadline. To learn more about Django, visit. He breaks down Django into bits and explains each concept in great detail and takes you from start to finish. <Lulu>
http://techwithlulu.com/index.php/2019/08/03/django-features-that-save-on-time-and-programming-headaches/
CC-MAIN-2019-51
refinedweb
777
53.37
INCLUDES, AUTOLOAD, BYTECODE CACHES and OPTIMIZATION The Problem ----------- HTML Purifier contains a number of extra components that are not used all of the time, only if the user explicitly specifies that we should use them. Some of these optional components are optionally included (Filter, Language, Lexer, Printer), while others are included all the time (Injector, URIFilter, HTMLModule, URIScheme). We will stipulate that these are all developer specified: it is conceivable that certain Tokens are not used, but this is user-dependent and should not be trusted. We should come up with a consistent way to handle these things and ensure that we get the maximum performance when there is bytecode caches and when there are not. Unfortunately, these two goals seem contrary to each other. A peripheral issue is the performance of ConfigSchema, which has been shown take a large, constant amount of initialization time, and is intricately linked to the issue of includes due to its pervasive use in our plugin architecture. Pros and Cons ------------- We will assume that user-based extensions will be included by them. Conditional includes: Pros: - User management is simplified; only a single directive needs to be set - Only necessary code is included Cons: - Doesn't play nicely with opcode caches - Adds complexity to standalone version - Optional configuration directives are not exposed without a little extra coaxing (not implemented yet) Include it all: Pros: - User management is still simple - Plays nicely with opcode caches and standalone version - All configuration directives are present Cons: - Lots of (how much?) extra code is included - Classes that inherit from external libraries will cause compile errors Build an include stub (Let's do this!): Pros: - Only necessary code is included - Plays nicely with opcode caches and standalone version - require (without once) can be used, see above - Could further extend as a compilation to one file Cons: - Not implemented yet - Requires user intervention and use of a command line script - Standalone script must be chained to this - More complex and compiled-language-like - Requires a whole new class of system-wide configuration directives, as configuration objects can be reused - Determining what needs to be included can be complex (see above) - No way of autodetecting dynamically instantiated classes - Might be slow Include stubs ------------- This solution may be "just right" for users who are heavily oriented towards performance. However, there are a number of picky implementation details to work out beforehand. The number one concern is how to make the HTML Purifier files "work out of the box", while still being able to easily get them into a form that works with this setup. As the codebase stands right now, it would be necessary to strip out all of the require_once calls. The only way we could get rid of the require_once calls is to use __autoload or use the stub for all cases (which might not be a bad idea). Aside ----- An important thing to remember, however, is that these require_once's are valuable data about what classes a file needs. Unfortunately, there's no distinction between whether or not the file is needed all the time, or whether or not it is one of our "optional" files. Thus, it is effectively useless. Deprecated ---------- One of the things I'd like to do is have the code search for any classes that are explicitly mentioned in the code. If a class isn't mentioned, I get to assume that it is "optional," i.e. included via introspection. The choice is either to use PHP's tokenizer or use regexps; regexps would be faster but a tokenizer would be more correct. If this ends up being unfeasible, adding dependency comments isn't a bad idea. (This could even be done automatically by search/replacing require_once, although we'd have to manually inspect the results for the optional requires.) NOTE: This ends up not being necessary, as we're going to make the user figure out all the extra classes they need, and only include the core which is predetermined. Using the autoload framework with include stubs works nicely with introspective classes: instead of having to have require_once inside the function, we can let autoload do the work; we simply need to new $class or accept the object straight from the caller. Handling filters becomes a simple matter of ticking off configuration directives, and if ConfigSchema spits out errors, adding the necessary includes. We could also use the autoload framework as a fallback, in case the user forgets to make the include, but doesn't really care about performance. Insight ------- All of this talk is merely a natural extension of what our current standalone functionality does. However, instead of having our code perform the includes, or attempting to inline everything that possibly could be used, we boot the issue to the user, making them include everything or setup the fallback autoload handler. Configuration Schema -------------------- A common deficiency for all of the conditional include setups (including the dynamically built include PHP stub) is that if one of this conditionally included files includes a configuration directive, it is not accessible to configdoc. A stopgap solution for this problem is to have it piggy-back off of the data in the merge-library.php script to figure out what extra files it needs to include, but if the file also inherits classes that don't exist, we're in big trouble. I think it's high time we centralized the configuration documentation. However, the type checking has been a great boon for the library, and I'd like to keep that. The compromise is to use some other source, and then parse it into the ConfigSchema internal format (sans all of those nasty documentation strings which we really don't need at runtime) and serialize that for future use. The next question is that of format. XML is very verbose, and the prospect of setting defaults in it gives me willies. However, this may be necessary. Splitting up the file into manageable chunks may alleviate this trouble, and we may be even want to create our own format optimized for specifying configuration. It might look like (based off the PHPT format, which is nicely compact yet unambiguous and human-readable): Core.HiddenElements TYPE: lookup DEFAULT: array('script', 'style') // auto-converted during processing --ALIASES-- Core.InvisibleElements, Core.StupidElements --DESCRIPTION-- Blah blahThe first line is the directive name, the lines after that prior to the first --HEADER-- block are single-line values, and then after that the multiline values are there. No value is restricted to a particular format: DEFAULT could very well be multiline if that would be easier. This would make it insanely easy, also, to add arbitrary extra parameters, like: VERSION: 3.0.0 ALLOWED: 'none', 'light', 'medium', 'heavy' // this is wrapped in array() EXTERNAL: CSSTidy // this would be documented somewhere else with a URL The final loss would be that you wouldn't know what file the directive was used in; with some clever regexps it should be possible to figure out where $config->get($ns, $d); occurs. Reflective calls to the configuration object is mitigated by the fact that getBatch is used, so we can simply talk about that in the namespace definition page. This might be slow, but it would only happen when we are creating the documentation for consumption, and is sugar. We can put this in a schema/ directory, outside of HTML Purifier. The serialized data gets treated like entities.ser. The final thing that needs to be handled is user defined configurations. They can be added at runtime using ConfigSchema::registerDirectory() which globs the directory and grabs all of the directives to be incorporated in. Then, the result is saved. We may want to take advantage of the DefinitionCache framework, although it is not altogether certain what configuration directives would be used to generate our key (meta-directives!) Further thoughts ---------------- Our master configuration schema will only need to be updated once every new version, so it's easily versionable. User specified schema files are far more volatile, but it's far too expensive to check the filemtimes of all the files, so a DefinitionRev style mechanism works better. However, we can uniquely identify the schema based on the directories they loaded, so there's no need for a DefinitionId until we give them full programmatic control. These variables should be directly incorporated into ConfigSchema, and ConfigSchema should handle serialization. Some refactoring will be necessary for the DefinitionCache classes, as they are built with Config in mind. If the user changes something, the cache file gets rebuilt. If the version changes, the cache file gets rebuilt. Since our unit tests flush the caches before we start, and the operation is pretty fast, this will not negatively impact unit testing. One last thing: certain configuration directives require that files get added. They may even be specified dynamically. It is not a good idea for the HTMLPurifier_Config object to be used directly for such matters. Instead, the userland code should explicitly perform the includes. We may put in something like: REQUIRES: HTMLPurifier_Filter_ExtractStyleBlocks To indicate that if that class doesn't exist, and the user is attempting to use the directive, we should fatally error out. The stub includes the core files, and the user includes everything else. Any reflective things like new $class would be required to tie in with the configuration. It would work very well with rarely used configuration options, but it wouldn't be so good for "core" parts that can be disabled. In such cases the core include file would need to be modified, and the only way to properly do this is use the configuration object. Once again, our ability to create cache keys saves the day again: we can create arbitrary stub files for arbitrary configurations and include those. They could even be the single file affairs. The only thing we'd need to include, then, would be HTMLPurifier_Config! Then, the configuration object would load the library. An aside... ----------- One questions, however, the wisdom of letting PHP files write other PHP files. It seems like a recipe for disaster, or at least lots of headaches in highly secured setups, where PHP does not have the ability to write to its root. In such cases, we could use sticky bits or tell the user to manually generate the file. The other troublesome bit is actually doing the calculations necessary. For certain cases, it's simple (such as URIScheme), but for AttrDef and HTMLModule the dependency trees are very complex in relation to %HTML.Allowed and friends. I think that this idea should be shelved and looked at a later, less insane date. An interesting dilemma presents itself when a configuration form is offered to the user. Normally, the configuration object is not accessible without editing PHP code; this facility changes thing. The sensible thing to do is stipulate that all classes required by the directives you allow must be included. Unit testing ------------ Setting up the parsing and translation into our existing format would not be difficult to do. It might represent a good time for us to rethink our tests for these facilities; as creative as they are, they are often hacky and require public visibility for things that ought to be protected. This is especially applicable for our DefinitionCache tests. Migration --------- Because we are not *adding* anything essentially new, it should be trivial to write a script to take our existing data and dump it into the new format. Well, not trivial, but fairly easy to accomplish. Primary implementation difficulties would probably involve formatting the file nicely. Backwards-compatibility ----------------------- I expect that the ConfigSchema methods should stick around for a little bit, but display E_USER_NOTICE warnings that they are deprecated. This will require documentation! New stuff --------- VERSION: Version number directive was introduced DEPRECATED-VERSION: If the directive was deprecated, when was it deprecated? DEPRECATED-USE: If the directive was deprecated, what should the user use now? REQUIRES: What classes does this configuration directive require, but are not part of the HTML Purifier core? vim: et sw=4 sts=4
http://fossies.org/linux/www/htmlpurifier-4.6.0.tar.gz:a/htmlpurifier-4.6.0/docs/dev-includes.txt
CC-MAIN-2015-18
refinedweb
2,012
50.77
Specifies the frame rate at which Unity tries to render your game. An integer. The default value of Application.targetFrameRate is -1. In the default case, Unity uses the platform's default target frame rate. Otherwise, targetFrameRate is a positive integer representing frames per second (fps). Unity tries to render your game at that frame rate. Use targetFrameRate to control the frame rate of your game. For example, you might need to reduce your game's frame rate to make sure your game displays smoothly and consistently. You can also reduce your game's frame rate to conserve battery life on mobile devices and avoid overheating. Note that platform and device capabilities affect the frame rate at runtime, so your game might not achieve the target frame rate. targetFrameRate and vSyncCount Both Application.targetFrameRate and QualitySettings.vSyncCount let you control your game's frame rate for smoother performance. targetFrameRate controls the frame rate by specifying the number of frames your game tries to render per second, whereas vSyncCount specifies the number of screen refreshes to allow between frames. Mobile platforms ignore QualitySettings.vSyncCount. Use Application.targetFrameRate to control the frame rate on mobile platforms. VR platforms ignore both QualitySettings.vSyncCount and Application.targetFrameRate. Instead, the VR SDK controls the frame rate. On all other platforms, Unity ignores the value of targetFrameRate if you set vSyncCount. When you use vSyncCount, Unity calculates the target frame rate by dividing the platform's default target frame rate by the value of vSyncCount. For example, if the platform's default render rate is 60 fps and vSyncCount is 2, Unity tries to render the game at 30 frames per second. Platform notes Standalone platforms On standalone platforms, the default frame rate is the maximum achievable frame rate. To use the platform's default frame rate, set Application.targetFrameRate to -1. Mobile platforms A mobile device's maximum achievable frame rate is the refresh rate of the screen. For example, a device with a refresh rate of 60 Hertz has a maximum achievable frame rate of 60 frames per second. To target the maximum achievable frame rate, set Application.targetFrameRate to the screen's refresh rate. Screen.currentResolution contains the screen's refresh rate. To conserve battery power, the default frame rate on mobile platforms is lower than the maximum achievable frame rate. Usually, the default frame rate on mobile platforms is 30 fps. To target the default frame rate, set Application.targetFrameRate to -1. To target a frame rate other than the maximum achievable frame rate or the platform default on mobile platforms, set Application.targetFrameRate to the screen's refresh rate divided by an integer. If the target frame rate is not a divisor of the screen refresh rate, the resulting frame rate is always lower than Application.targetFrameRate. Note that mobile platforms ignore the QualitySettings.vSyncCount setting. Instead, you use the target frame rate to achieve the same effect as setting the vertical sync count. To do this, divide the screen's refresh rate by the number of vertical syncs you want to allow between frames, and set Application.targetFrameRate to this number. For example, on a device with a screen refresh rate of 60 Hz, to allow: targetFrameRateto 60. targetFrameRateto 30. targetFrameRateto 20. WebGL By default, WebGL lets the browser choose a frame rate that matches its render loop timing. To use the browser's chosen frame rate, set Application.targetFrameRate to -1. Usually, the browser's chosen frame rate gives the smoothest performance. You should only set a different target frame rate on WebGL if you want to throttle CPU usage. VR VR platforms ignore Application.targetFrameRate and QualitySettings.vSyncCount. Instead, the VR SDK controls the frame rate. Unity Editor In the Editor, Application.targetFrameRate affects only the Game View. It has no effect on other Editor windows. See Also: QualitySettings.vSyncCount using UnityEngine; public class Example { void Start() { // Make the game run as fast as possible Application.targetFrameRate = 300; } }
https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html
CC-MAIN-2022-40
refinedweb
660
51.44
In this article, we will study what is hashing and why working with hashing data structure is easy compared to other data structures. We will start with what is a hash function and what is a collision in hashing including the negative indexing of hash keys. And at last, we will learn some of the frequently asked problem statement which can be solved using hashing technique to find an optimal solution along with its python code and output. So, let's get started! Introduction to Hashing Before starting to understand what is hashing, let us go through one example. Suppose we want to design a system to store the student records with some of their information like roll number, name, class name, section, and parents’ names. And we want the following queries to be performed on the system: - Insert the roll number and corresponding information - Search the roll number and corresponding information - Delete the roll number and corresponding information Now the above system can be successfully developed using - An array of roll number and corresponding information - Linked-List of roll number and corresponding information - Hash Table of roll number and corresponding information Now, if we create the above system using an array or linked-list, we need to search in the linear manner, which is high maintenance practically. For example, using array data structure the insertion time complexity is constant i.e O(1), but the search time complexity and deletion time complexity is O(N) which is big for N number of entries. Similarly, using Linked-List data structure, the insertion, searching and deletion time complexity is O(N) for N number of entries which is not quite feasible. Therefore, hashing is used as a solution that can be utilized in almost all such situations and perform well compared to other data structures. Using hashing we get the time complexity for insertion, searching and deletion as O(1) in average and O(N) in worst time complexity. So, using the hash function we can convert the roll number into a key and use this key as an index in the table called a hash table. Hash Table is a data structure that stores the key-value pair. Each value is assigned to a key which is created using the hash function. This hash table stores values as student information for corresponding roll numbers as keys. The entry in the hash table is “null” if the key does not have its corresponding information. Now let us understand how we can convert the entire system into code: s1 = [1, 'A', 11, 'c', 'f1', 'm1'] s2 = [2, 'B', 12, 'c', 'f2', 'm2'] s3 = [3, 'C', 10, 'b', 'f3', 'm3'] hashTable = [None for _ in range(101)] def insert(s): rollNo = s[0] hashTable[rollNo] = s[1:] return def search(s): rollNo = s[0] if hashTable[rollNo] is None: return False return hashTable[rollNo] def delete(s): rollNo = s[0] hashTable[rollNo] = None return insert(s1) insert(s2) insert(s3) print(search(s2)) print(search(s3)) delete(s1) print(search(s1)) Hash Function and Collision Now, above we assumed that the roll numbers of the student were already small in size so we can directly consider them as the key value. But what if they are not of small size? In such scenarios, we can use the hash function to covert the big number or a string into a small integer that can be used as a key in the hash table. These values which are returned by the hash function are called hash values. Many hash functions can be generated for any given circumstances but for creating an effective hash function following qualities should be fulfilled: - The hash function should be easy to compute and it should not be an algorithm in itself. - Every hash function should be able to generate unique hash values - The hash function should create the minimum number of collisions. - There should be a uniform distribution of the hash values among the entire hash table Index mapping with negative allowed Consider the limited range array contains both positive and negative integer numbers i.e from the range [-Max, Max]. Our job is to search if such a number is present in an array using O(1) time. Here we have limited the range therefore we can use index mapping. We use these values in the index as a big array. Hence, we can insert and search the elements in O(1) time. Now, for the negative indexing, we will shift all the negative keys to the positive keys by calculating the difference between the maximum and the minimum range. Therefore, the formula for the shift will be: Limit = Max – [-Max] + 1 This, limit is added to all the negative keys to shift them towards the positive keys and similarly is done with the positive keys to shift them further to maintain the difference between the keys. Collision Handling As we know that hash function generates small hash values which can be used as keys in the hash table. But many times, same hash values are generated for different inputs in the hash function. This condition leads to a collision. The process handling key generated by hash function pointing to already occupied key in table is called collision handling technique. We can handle collision using the following collision handling technique: - Open Addressing: When all the elements are stored in the hash table itself it is an open addressing process. Here we create the records in the form of the array itself. While using this method, if we find that the slot for storing the value is already occupied, then we simply move on further in the table and find the empty slot to store the value. - Chaining: It is the most commonly used collision technique. Here we make every cell of the hash table point to the linked list of the values that have the same hash function value. Now if a collision occurs then we store both the values in the same linked list. As chaining is a simple process, but it requires additional memory outside the table for creating the linked list. But it can easily accommodate a large number of value if large space is available. Also, the time complexity of inserting data using the chaining technique is O(1) hence, gives better performance in comparison to other collision handling techniques. How Hashing used to solve problems? There are many problem statements available that can be solved using various techniques and methods. But solving such problem statements using hashing techniques gives us the best optimal solution possible. All such problem statements are frequently asked in coding interviews and it is very necessary to learn them briefly.Below are some such problems solved using hashing techniques. Count of Elements in an Array Problem Statement: We are given the integer array and we have to count the frequency of each element in the array. We can solve this problem using the brute force approach i.e we can use the loop and increase the count of the element as its frequency increases. But using this approach the time complexity will be O(N2) and space complexity will be O(1) for an array of size N which is not optimal. Therefore we will use hashing technique to solve the above problem. Using hashing technique we will create the hash map where the key will be the integer number itself and the value will be the frequency of occurrence of the element in the array. Now, we will trace each element of the array and if the element is repeated we will increase its occurrence by +1. For example: nums = [10, 25, 10, 15, 2, 15, 15, 2, 10] key/element value/frequency 10 1 2 3 25 1 15 1 2 3 2 1 2 Output: [10-3, 25-1, 15-3, 2-2] The time complexity of the above method is O(N) and the space complexity is also O(N) for an array of size N. The code for the above problem statement is as given below: def countElements(arr): memo = {} for currentVal in arr: if currentVal in memo: memo[currentVal] = memo[currentVal] + 1 else: memo[currentVal] = 1 for key in memo.keys(): print(key, memo[key]) return arr = [10, 20, 15, 20, 10, 20, 10] countElements(arr) The output of the above code is: 10 3 20 3 15 1 Count distinct element in the array Problem statement: We are given the integer array and we have to count the distinct elements in the array. We can solve this problem using the brute force approach by running the loop over the array and then increase our answer variable by 1 when we discover the distinct element. But by using loops the time complexity of the method will be O(N2), where the size of the array is N and space complexity is O(1). This solution is not feasible and therefore we can use the hashing technique to find an optimal solution. Now using hashing, we will create the hash map where the key will be the integer element of the array itself and the value will be the occurrence frequency of the element in the array. When the element frequency is increased, we will increase the corresponding value by 1. At last, we will run a loop over the hash map and the key having the value as 1 will be the distinct element of our array. For example: nums = [10, 20, 30, 15, 5, 20, 10] key/element value/frequency 10 1 2 20 1 2 30 1 15 1 5 1 Output: [30, 15, 5] The time complexity of the above method is O(N) and the space complexity is also O(N) for an array of size N. The code for the above problem statement is as given below: def countDistinct(nums): memo = {} answer = 0 for currentVal in nums: if currentVal in memo: memo[currentVal] = memo[currentVal] + 1 else: memo[currentVal] = 1 for key in memo.keys(): if memo[key] == 1: answer += 1 return answer nums = [10, 20, 30, 5, 15, 20, 10] print(countDistinct(nums)) The output of the above code is: 3 Finding Anagrams Finding an anagram of the strings is another useful example of applying the hashing technique. Problem Statement: Given two strings s and t, return true if t is an anagram of s, and false otherwise. There are two conditions to check while proving two strings as an anagram of one other. They are as below: - Length of both the string should be same - The occurrence of every character should be the same in both strings We can use the brute force approach to solve this problem by calculating the length of both the strings first and then we will run the loop to check the occurrence of every character in both the string. But the time complexity of this approach is O(N2), where N is the length of the string and space complexity is O(1). This solution is not feasible and therefore we can use the hashing technique to find an optimal solution. Now using hashing technique, we will create a hash map of the string s where the characters of the string will be the key and its frequency will be its corresponding value. After the successful creation of the hashmap, we will trace each character of string t and reduce the frequency of the corresponding character by 1 from the hashmap. After tracing each character of string t if we find our hash map to be empty then string t is anagram if string s and if the hashmap is not empty then it is false. For Example: s = “anagram” t = “nagaram” key/characters value/freqyency a 1 2 3 2 1 0 n 1 0 g 1 0 r 1 0 m 1 0 Output: True The time complexity of the above method is O(N) and the space complexity is also O(1) for an array of size N. The code for the above problem statement is as given below: def checkAnagrams(s, t): if len(s) != len(t): return False memo = {} for currentChar in s: if currentChar in memo: memo[currentChar] += 1 else: memo[currentChar] = 1 for currentChar in t: if currentChar not in memo: return False memo[currentChar] -= 1 if memo[currentChar] == 0: del memo[currentChar] return True s = 'anagram' t = 'nagaram' print(checkAnagrams(s, t)) The output of the above code is: True So, above were some of the common problem statements that are usually asked in coding interviews for finding an optimal solution. There are many such problem statements discussed in detail with python code and examples on the online course Data Structure and Algorithm Hashing. Conclusion Hence in the above article, we studied what is hashing as a data structure and how it is better to use. Along with that we also learned the collision technique and negative indexing in hashing. Also, we learned some of the problems solved using hashing techniques in detail with the python code and output.
https://favtutor.com/blogs/hashing-in-data-structure
CC-MAIN-2022-05
refinedweb
2,186
54.26
Exobot An ES6+ chatbot. Requires Node ^6.2. Installation npm install --save @exoplay/exobot A Brief Example To start an exobot instance, you need to import the bot itself and initialize it with plugins and chat service adapters. Here's an example: import { Exobot, adapters, plugins, LogLevels } from '@exoplay/exobot'; import { Points } from '@exoplay/exobot-plugin-points'; const { Help, Greetings } = plugins; const BOT_ALIAS = '!e'; const BOT_NAME = 'exobot'; const LOG_LEVEL = LogLevels.INFO; const shell = adapters.Shell; const bot = new Exobot(BOT_NAME, { alias: BOT_ALIAS, adapters: [ new shell(), ], plugins: [ new Help(), new Greetings(), new Points(), ], logLevel: LOG_LEVEL, }); module.exports = bot; $ npm run build $ node exobot.js > Chat: hi > exobot: hi, shell! > Chat: exobot++ for being awesome > exobot: exobot has 1337 points, 1336 of which are for being awesome What did we do there? - Created a file named ./src/exobot.js - Imported the Exobotclass, service adapters, and plugins - Initialized a new bot, passing in its name, configured service adapters and plugins - Built the bot to turn ES7+ into node-compatible ES6 - Started the bot - Ran node index.jsand interacted with the bot Getting started The easiest way to start is copy the example above - this will get you started with a chatbot with a shell adapter. The shell adapter will start an interactive console with which you can chat in a single "room"; Exobot will respond to messages that trigger plugins. - Make a directory somewhere that you want to keep your bot's configuration code. - Run git init(or source control initialization method of choice), then npm initto start up an NPM package. (You probably won't publish your bot as its own package - but this will create a package.jsonfile that contains your dependencies.) - Run npm install --save @exoplay/exobotto install the chatbot. - Add npm scripts such as "build": "exobot-build"and "watch": "exobot-build --watch"to your package.json to get access to the bot building commands - Copy the example above to ./src/exobot.js. - Build the bot with npm run build - Run node exobot.js. Chat with yourself for a while, then read on to learn how to configure your chatbot, or even build your own plugins and adapters. Configuration Exobot is configured in its constructor, which takes two arguments - a bot name (a required string), and an options object. The bot name is used for commands - if your bot's name is 'exobot', it will respond to commands beginning with 'exobot'. You'll want this to match the name used in your chat service (so if its name is actually 'DEATHBOT_9000' in Slack, you should call it that here too, or people may be confused.) The options object contains all other configuration - such as a list of plugins and chat service adapters, log levels, and data encryption keys. alias- an additional way to trigger exobot commands. 'hey bot', for example. adapters- an array of initialized chat adapters, such as slack, discord, or twitch. exobot also comes with a shelladapter for playing around in your terminal. plugins- an array of initialized plugins, such as giphy or points. exobot also comes with helpand greetingsplugins as examples. readFileand writeFile- functions called when the in-memory json db is saved. By default, this writes a json file to cwd/data/botname.json, but you could also override the default local file storage to use s3 with exobot-db-s3. dbPath- if you're using local file storage, you can set where to save. Defaults to cwd/data/botname.json. Building plugins Most plugins respond to chat messages - either by listening to all chat messages, or responding to specific commands. exobot comes with greetings and help plugins, but building your own is easy. Some examples: The ES2017 decorators proposal is used to hook commands to validation functions or regexes, to assign permission groups, and to provide help text. An Example Plugin import { ChatPlugin, respond, help, permissionGroup } from '@exoplay/exobot'; export default class Ping extends ChatPlugin { static name = 'ping'; @help('Says "pong" when you send it "ping"'); @permissionGroup('ping'); @respond(/^ping$/); pong (match, message) { return 'pong'; } } In this plugin, we have extended exobot's ChatPlugin class - this gives it functionality to respond to chat messages. We've then told it to respond to the regex /ping/ by firing a function, called pong. The return value of the function is then sent back to the chat channel. A Detailed Anatomy of a Chat Plugin Chat plugins follow the following lifecycle: First, The constructor is called with options sent in. As the bot is initialized with instances of plugins, this is where you would pass in configuration options, such as: import { ChatPlugin, respond, help, permissionGroup } from '@exoplay/exobot'; class StatusPlugin extends ChatPlugin { constructor (options) { super(options); this.endpoint = options.endpoint; } //... @help('Gets the status of the configured endpoint.'); @permissionGroup('get'); @respond(m => m.text === 'status'); async getStatus () { const res = await this. return res.statusCode; } } In the above example, we'd initialize the exobot instance with plugins: [ new StatsPlugin({ endpoint: ' }) ] to pass in the options we need later on. Next, when the bot instance begins listening, the plugin's register method is called, with the bot instace passed in. Note that the constructor doesn't have the bot yet - it doesn't exist until register, fired next. You'll want to give the plugin a static name property - thi is used if you use the permissions plugin to restrict access to commands. listen and respond are decorators that take a function, and fire the method when a match is found. listen and respond are the most important parts of your chat plugin - these allow the bot to interact with chat. Each can take either a regex or a function, and if a match is found (or, if a function, if it is truthy), it will fire the function passed in. Functions for responding can be promises (or ES7 async functions) and will resolve when the promises do. This makes it easy to write asynchronous code, such as firing http requests. The responding function gets two arguments: a match object, which is either the regex's exec response or the function return value, and a object, which contains the original message, user, and whether the message is a whisper. You can optionally add a help decorator, which exobot's help plugin uses to explain to useres how the plugin works. You should also add a permissionsGroup, which you can then use with exobot's Permissions plugin to restrict access to certain commands. In the following case, you can give access to status.get to groups, and if you deny access by default in configuration, only users in the group with access to status.get can use the command. (The bot will ignore the command from everyone else.) Finally, the bot also exposes bot. which is a promise-ified superagent wrapper, to make http calls easy to make. import { ChatPlugin, respond, listen, permissionsGroup, help } from '@exoplay/exobot'; class StatusPlugin extends ChatPlugin { static name = 'Status'; help = [ 'Get the status of an http endpoint. Responds to `status` or listens to', 'status < ].join('\n'); constructor (options) { super(options); this.endpoint = options.endpoint; } register (bot) { super.register(bot); if (!this.endpoint) { bot.log.warn('No endpoint passed in to StatusPlugin.'); } this.respond(/status/, this.getStatus); this.listen(/^status ( this.getStatus); this.listen(m => m.text === 'status', this.getStatus); } @help('use status or status < to get http status codes.'); @permissionsGroup('get'); @respond(/^status$/); @listen(/^status ( @listen(m => m.text === 'status'); async getStatus (match, message) { let endpoint = this.endpoint; // if the regex succeeded, match[1] should be an http endpoint if (match && match.length) { endpoint = match[1]; } const res = await this. return res.statusCode; } } You can also build other types of plugins: EventPlugin, HTTPPlugin, or build your own class of plugin with the Plugin class. Documentation to come someday. Exobot exports a handy scripts for testing your plugins: exobot-try. By either installing exobot globally ( npm install -g @exoplay/exobot) or adding a script to your package.json ( "try": "exobot-try"), exobot will fire up a simple bot with a shell adapter so you can test your plugin. Building Adapters Adapters allow your bot to connect to a chat service, such as Slack or Discord. exobot comes with a shell adapter by default, but you could also build your own for your chat service of choice. Some examples: An Example Adapter // An example: import an API lib for your chat service, or do it with raw // sockets or or whatever. import ChatServiceLibrary from '@chatservice/lib'; import { Adapter, User } from '@exoplay/exobot'; export default class ChatServiceAdapter extends Adapter { constructor ({ token, username }) { super(...arguments); this.token = token; this.username = username; } register (bot) { super.register(bot); // Initialize the chat service lib we pulled in earlier this.service = new ChatServiceLibrary(this.username, this.token); // listen to some events. bind the functions to `this` to make sure we can // access our class instance, bot, and `super`. this.service.on('ready', this.serviceReady.bind(this)); this.service.on('message', this.serviceMessage.bind(this)); } // the `send` funciton is defined by Adapter and called by plugins when they // resolve (if they resolve.) send (message) { this.bot.log.debug(`Sending ${message.text} to ${message.channel}`); // Send the message data to the chat service client. this.service.sendMessage({ to: message.channel, message: message.text, }); } serviceReady () { this.status = Adapter.STATUS.CONNECTED; this.bot.emitter.emit('connected', this.id); this.bot.log.notice('Connected to ChatService.'); } // We'll pretend our fake chat service lib takes a function which is called // with message, user, and channel. We'll take these arguments and "receive" // them, which will fire off all of the plugins so they can respond where // necessary. serviceMessage (user, text, channel) { // We don't want to listen to messages from ourself. if (user.name === this.username) { return; } // Create a new User instance to pass along in the Message. const user = new User(user.name, user.id); // Check if our fake chat service lib says the channel is "private". If it // is a private message between the user and bot, we'll make it act like a // "respond" command instead of just a "listen". if (channel.private) { return super.receiveWhisper({ user, text, channel }); } return this.receive({ user, text, channel }); } // This is useful for chat services where names aren't unique, for use by // plugins where uniqueness matters (like Permissions.) getUserIdByUserName (name) { return this.service.getUserByName(name).id; } } A Detailed Anatomy of a Chat Service Adapter Chat service adapters have a similar lifecycle to plugins: - Constructor, before the bot is initialized; - Register, when the bot is initialized, where you first get acccess to the exobot instance, and where you listen to your chat service; - Functions called by events fired by the chat service; - Finally, send, called by the bot instance when plugins resolve. You can listen and fire any arbitrary functions - for example, some chat services may include presence information, and fire enter and leave events. You can then receive your own PresenceMessage similar to how we receive a TextMessage in the serviceMessage in the example. (Right now, the only Message classes are TextMessage and PresenceMessage). Many adapters may also want to make use of the Status enum, which could be: - UNINITIALIZED - CONNECTING - CONNECTED - DISCONNECTED - RECONNECTING - ERROR You may also want to use bot.log to log important events to stdout, such as connection or configuration errors. bot.log can fire: - debug - info - notice - warning - error - critical - alert - emergency In order of ascending severity. Acknowledgements Exobot is loosely based on hubot, for which the author has a great deal of admiration. Hubot is more user-friendly in many ways (autoloading scripts, for example, instead of requiring the user to write their own imports and configuration). In other ways, this flexibility can be limiting; it's easier to make a pure-js bot more efficient and testable (and the author thinks that ES6, rather than Coffeescript, is a more viable choice of language; plugin-writers can always choose to opt-in to Coffeescript and export a built file if they want.) License LGPL licensed. Copyright 2016 Exoplay, LLC. See LICENSE file for more details.
https://www.npmtrends.com/@exoplay/exobot
CC-MAIN-2022-21
refinedweb
2,002
56.66
This is an OP Kudos discussion and contributors may be rewarded Reputation Points: 1,238 [?] Q&As Helped to Solve: 1,058 [?] Skill Endorsements: 28 [?] 1 This snippet defines 3 functions to create in a few seconds an image of a graph containing arbitrary python objects. It uses the module pygraphviz (available at). See the example use case at the end of the module. # module fastgraph # created by Gribouillis for the python forum at # November 9, 2010 # Licence: public domain """This module defines 3 functions (node, edge and graph) to help create a graph (a pygraphviz.AGraph instance) linking arbitrary python objects. This graph can be saved in various image formats, and in dot format. """ import pygraphviz def node(x): "helper to create graphs" return (x,) def edge(x, y): "helper to create graphs" return (x, y) def graph(items, tolabel, **kwd): """Create a pygraphviz AGraph instance @ items - a sequence of node(obj), or edge(obj, obj) items (obj can be any python object) @ tolabel - a function tolabel(obj) -> str which converts an object to string @ **kwd - additional keyword arguments for AGraph.__init__ """ names = dict() the_graph = pygraphviz.AGraph(**kwd) for uple in (tuple(t) for t in items): for obj in uple: if not obj in names: names[obj] = "n%d" % len(names) the_graph.add_node(names[obj], label=tolabel(obj), shape="box") if len(uple) == 2: the_graph.add_edge(*(names[obj] for obj in uple)) return the_graph if __name__ == "__main__": def my_items(): """Exemple generator of graph items. Our graph contains string here""" for x in "abcde": yield node(x) for s in "ab ac bd ea da".split(): x, y = iter(s) yield edge(x, y) def my_label(x): "Create a label for graph objects" return x.upper() g = graph(my_items(), my_label) g.draw('mygraph.png', prog='circo') # prog can be neato|dot|twopi|circo|fdp|nop
https://www.daniweb.com/software-development/python/code/323792/link-any-objects-in-a-graph-and-draw-the-graph-
CC-MAIN-2015-35
refinedweb
306
65.12
Data visualization with Seaborn Seaborn provides an API on top of matplotlib, which uses sane plot and color defaults and simple functions for common statistical plot types. Visualization with Seaborn Matplotlib is a useful tool, but it leaves much to be desired. There are several valid complaints about matplotlib that often come up: - Matplotlib’s defaults are not exactly the best choices. It was based off of MatLab circa 1999, and this shows. - Matplotlib is relatively low-level. Doing sophisticated statistical visualization is possible, but often requires a lot of boilerplate code. - Matplotlib is not designed for use with Pandas dataframes. In order to visualize data from a Pandas dataframe, you must extract each series and often concatenate these series’ together into the right format. The answer to these problems is Seaborn. Seaborn provides an API on top of matplotlib which uses sane plot & color defaults, uses simple functions for common statistical plot types, and which integrates with the functionality provided by Pandas dataframes. Let’s take a look at Seaborn in action. We’ll start by importing the key libraries we’ll need. from __future__ import print_function, division %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd Then we import seaborn, which by convention is imported as sns. We can set the seaborn style as the default matplotlib style by calling sns.set(): after doing this, even simple matplotlib plots will look much better. Let’s look at a before and after: x = np.linspace(0, 10, 1000) plt.plot(x, np.sin(x), x, np.cos(x)); import seaborn as sns sns.set() plt.plot(x, np.sin(x), x, np.cos(x)); Ah, much better! Exploring Seaborn Plots The main idea of Seaborn is that it can create complicated plot types from Pandas data with relatively simple commands. Let’s take a look at a few of the datasets and plot types available in Seaborn. Note that all o the following could be done using raw matplotlib commands (this is, in fact, what Seaborn does under the hood) but the seaborn API is much more convenient. Histograms, KDE, and Densities Often in statistical data visualization, all you want is to plot histograms and joint distributions of variables. Seaborn provides simple tools to make this happen:: for col in 'xy': sns.kdeplot(data[col], shade=True) Histograms and KDE can be combined using distplot: sns.distplot(data['x']); which can be passed to jointplot: for example, we can use a hexagonally-based histogram instead: with sns.axes_style('white'): sns.jointplot("x", "y", data, kind='hex') Pairplots When you generalize joint plots to data sets of larger dimensions, you end up with pair plots. This is very useful for exploring correlations between multi-dimensional multi-dimensional relationships among the samples is as easy as calling sns.pairplot: sns.pairplot(iris, hue='species', size=2.5); Faceted Histograms Sometimes the best way to view data is via histograms of subsets. Seaborn’s FacetGrid makes this extremely simple. We’ll take a look at some data which shows the amount that restaurant staff receive in tips based on various indicator data: tips = sns.load_dataset('tips') tips.head() tips['tip_pct'] = 100 * tips['tip'] / tips['total_bill'] grid = sns.FacetGrid(tips, row="sex", col="time", margin_titles=True) grid.map(plt.hist, "tip_pct", bins=np.linspace(0, 40, 15)); Factor Plots Factor plots can be used to visualize this data as well. This allows you to view the distribution of a parameter within bins defined by any other parameter: with sns.axes_style(style='ticks'): g = sns.factorplot("day", "total_bill", "sex", data=tips, kind="box") g.set_axis_labels("Day", "Total Bill"); Joint Distributions Similar to the pairplot we saw above, we can use sns.jointplot to show the joint distribution between different datasets, along with the associated marginal distributions: with sns.axes_style('white'): sns.jointplot("total_bill", "tip", data=tips, kind='hex') The joint plot can even do some automatic kernel density estimation and regression: sns.jointplot("total_bill", "tip", data=tips, kind='reg'); Bar Plots Time series can be plotted using sns.factorplot: planets = sns.load_dataset('planets') planets.head() with sns.axes_style('white'): g = sns.factorplot("year", data=planets, aspect=1.5) g.set_xticklabels(step=5) We can learn more by looking at the method of discovery of each of these planets: with sns.axes_style('white'): g = sns.factorplot("year", data=planets, aspect=4.0, hue='method', x_order=range(2001, 2015)) g.set_ylabels('Number of Planets Discovered') For more information on plotting with Seaborn, see the seaborn documentation, the seaborn gallery, and the official seaborn tutorial.
https://www.oreilly.com/content/data-visualization-with-seaborn/
CC-MAIN-2022-21
refinedweb
764
59.4
Ah, you did! What are you doing there? If you don't want to do it , I know I have to to get at the keymap files. I'd be happy to share. Though you may already be working/finished it, but I just wanted to throw it out there. Not sure what you mean...but I do spit out bbcode... [pre=#0C1021]if bulletin_board: # print css bbcode = "[pre[/color]=%s]" % dict(cssNone]).get('background-color', '#000000')] A = bbcode.append from lxml.html import fromstring import re TAG = re.compile(r'(\\w+|\/\w+)', re.M | re.S) def crude_tokenizer(text): # TODO: this would be a better algorithm for `inversion_stream` "Yields" last_end = end = 0 for match in TAG.finditer(text): start, end = match.span() if start != last_end: yield text[last_end[/color]:start] yield text[start[/color]:end] last_end = end token_length = len(text) if end < token_length: yield text[end[/color]:token_length] for txt in fromstring(html).xpath('//text()'): if txt.is_tail or txt.is_text: parent = txt.getparent() if txt.is_tail: parent = parent.getparent() style = None while parent is not None: style = parent.get('style') if style: break else: parent = parent.getparent() color = re.search(r'(?<!background-)color:(#[A[/color]-Fa-f0-9]+)', parent.get('style')) if color: color = color.group(1) else: color = dict(cssNone]).get('color', '#000000') color_wrap = lambda t: "=%s]%s]" % (color, t) for t__ in crude_tokenizer(txt): A(color_wrap(t__)) html = "".join(bbcode + "[/pre[/color]]"]) [/pre] That seems to work, making sure to wrap any tag looking things in a bbcode element so as to break em up If?
https://forum.sublimetext.com/t/st3-exporthtml/8938/17
CC-MAIN-2017-26
refinedweb
260
64.27
Join devRant Pipeless API From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple APILearn More Search - "leaving" - *In Office Coworker raises his head, looks at boss: "I'm leaving". Boss raises head looks at coworker: "Ok". All this took 5 seconds,..the weirdest 5 seconds of my life10 - Today I presented a client with their new website. Feedback from the owner was "I fucking love it". Got a cash bonus and a bottle of champagne before leaving. Today was a good day!19 - If you are reading this, I want you to know that I am probably on some kind of FBI watchlist because I googled "How to kill all children while leaving the parent alive". So yeah, Linux is brutal - We are required to say “leaving for the day” when we leave office. (On slack) One developer decided to quit and just said “leaving “ and we realised the next day what he meant when he did not show up 😂😂😂7 - - Immortalised this actual legacy code for our Senior Devs leaving present (we all inherited this) with his last task being to refactor it, may he never have to work with code like this again.13 - - Boss: if I could put together a counter offer, is that something you might be interested in? Me: eh, no. I’ve accepted an offer for slightly less money than I’m on Boss: oh ... oh ok. Right so there’s nothing I can do? Me: afraid not. You can’t offer me a role not dealing with those people in the states, having to use their shitty custom tools or having to follow their bad practises all day. Boss: ok ..... shit9 - So, Bing has an in-search code runner. //Just leaving this here //GoogleDoesnt //YesGoogleIsBetter 70%OfTheTimes //IHatePython8 - Today is my last day at this job. Can't tell you how happy I am to be leaving this place in about 7 hours. Starting my new job in January, so I get 4 weeks of nice vacation/ family time.8 - Me, in the zone, staring at the code. Co-worker enters. Co: hey, can you... Me (not really listening): no. Co: it's just... Me: no. Co: later? Me: no. Co: but... Me: no. Co: (leaving)14 - I FUCKING HATE WAITING FOR PEOPLE. It feels like a full quarter of my life is wasted just goddamn WAITING. Fuck off. From now on I'm just leaving whomever behind.11 - I can now die without regret, I came back to a project after leaving it for three months I WAS ABLE TO UNDERSTAND MY CODE! I think I reached the point of writing clean code? Let's hope so :)10 - - - Best: got an offer from Google. Worst: family and friends trying to convince me to turn down the offer and take a local job. (I'm from a small town where family is everything to everyone and leaving is blasphemous.)12 - - My fellow coworker's commit history of last 24 hours. And my boss was surprised when I told him I'm leaving the company..18 - !rant Working at home this Saturday. My wife made coffee, some toasted bread and is leaving me quiet in my corner. She's the best!11 - - - Tried Asphalt 9 today. You can’t actually steer. It’s a racing game. You can’t steer. Game steers for you. I’m leaving this planet.17 - - - - Company organised a meeting with everyone for me to explain (again) why I'm leaving. Basically participated to a meeting to say that I'm out of their company6 - I am leaving my job from a very big company with very high paying package for doing my own startup. 1 month notice period on.10 - I asked collegue about status of component thru Skype (different countries, you know) and received answer he's leaving company in 8 days. FML.1 - So I was playing Formula 1 game and I heard “push, push, push” from the engineer while leaving pit-lane. I immediately closed game and started “git push”3 - - - !rant This is a little Bluetooth Low Energy Tank I made for a colleague as a leaving gift. 3D printed turret driven by a Pi 0 W and a Zumo chassis.7 - - - 1825. Leaving work. Today sucks. My coworker is out and she normally does this weekly report. I need her. I don't like this.26 - Fuck me! I'm frustrated as fuck, because I'm too scared to quit my job. The boss just fired her assistant and now wants me to do her job. I'm INCAPABLE of doing phone calls and set up meetings; furthermore THAT ISN'T MY FREAKING JOB! Holy shit, what do I have to do? I'm scared to not being able to find a job in few days/weeks. Any suggestion? Should I swallow it and keep working here while searching? I aged badly in 2 years because of this job.11 - - - - - me : *leaving 15 min earlier* manager : IT'S UNACCEPTABLE, HOW CAN WE BUILD A TRUST RELATIONSHIP LIKE THAT manager one week later: yeah we need you to work till midnight if needed today. You cannot say no. me : ¯\_(ツ)_/¯10 - - My former boss is trying to modify a MEAN webapp I finnished before leaving my last job. Apparently, he is debugging Node with alerts.9 - - - 4 months ago, i decided to talk leaving my shyness behind and today, yes today i am completely a new thing. Thanks to everybody who made me realized that I do have my personal existance.9 - - up at 11:30pm finishing some work when fire alarm goes off.... waited to see if my tests passed before leaving3 - I've made up my mind, I'm leaving this toxic environment, the current company and making a switch. FUCK IT8 - Heard my team leader is leaving, this leaves me as the only developer in the company, we went from 4 all the way down to 1... #thiscompanyisamess4 - - When abandoning a midnight bug hunt in the middle of a particularly nasty bug, always remember to leave kind words for your future self to see, so that they're not as disappointed with you for leaving this work for them.3 - - Me: Why are all the devs leaving work early!? Other devs: Microsoft Services are down. Me: Okay I'll start packing.1 - Was at a farewell party at work yesterday and those of us who are leaving got one each of these... 😂1 - I've been calling the W3 Consortium every day for the past week leaving the same message: "Why the fuck doesn't CSS "vertical-alignment" work on all elements?" Still waiting for them to return my call..7 - Leaving for work before finding the source of a bug is the worst kind of stress. All I thought about the entire time I was at work 😭4 - To all kids that are leaving Github only because the "big bad corp) bought it: Why did you not leave earlier? Github was good being closed before23 - - - Handing in my resignation letter on April 1st, but then actually leaving. Not really a prank, that's something I genuinely feel like doing nowadays.2 - Keeping old and unused code blocks commented out and not deleting them immediately is the equivalent of leaving that bottle of soy sauce in the fridge even though you know very well that you won't use them ever again.7 - - Went to my boss to tell him that I will be leaving by the end of the year. Apparently he had similar plans and pretty soon we were discussing where he can go to!5 - My company just announced we are leaving Slack for Google Chat because it is a "superior" (and cheaper) tool. FML13 - - My worst dev sin was leaving out the 'WHERE' in a SQL update statement on a production database Set every booking to be owned by the same sales consultant 👀3 - I have a large code library I have been working on for over 10 years. I have nightmares about leaving it to another unfortunate dev. I'll have to work at this company the rest of my life.7 - I - Going to a webpage and after 5 seconds being "welcomed" by the typical "Are you leaving?" popup. Yes, at first I wanted to read the article but now on second thought I am leaving. - - Continuing someone's project mid way be like doctor performing operation, leaving it mid way and other doctor trying to continue. May the god bless the patient.1 - I get more work done when I know I'm leaving early than when I'm in the office for a whole day....2 - Woo, rant time. I've recently changed jobs to a new company due to a number of factors at my old job. I didn't tell my old boss (let's call him X) my expected salary, nor did I tell him which company I was going to. However, I've been informed by someone that still works there that X has been discussing my new wage in front of everyone; he was telling everyone that I'm going to lose money by moving job and that I made a stupid decision. I didn't leave due to money, it was due to X's inability to take constructive criticism, the constant subtle sexism of the office and just a generally bad overall feeling about the job/office going forward. Yes, I will admit that money did have a minor part in my decision to leave but I didn't verbalise that to anyone in the office, and I made X aware that my departure wasn't to do with money. I left on good terms. I feel as though it was wrong of X to talk about his opinions on my new job in front of my ex-colleagues and friends. I don't know, maybe this is the norm and I've just been living in a cave before this, or maybe my last boss was just a bit of a douchenugget. Has anyone else had this experience? I've got to meet up with everyone from my last place tomorrow to properly say goodbye and things.. but I'm not sure how to approach my old boss when leaving drinks are held now. Should I say anything? Should I just act as though I know nothing about it? What would you guys do in this situation???19 - - So, packing up and leaving this hell hole. In the end I just said that I had 2 panic attacks in the last week, and that I am leaving for medical reasons.7 - - When your university drops the support for IMAP on their mail-server, leaving Exchange as only possible option, because apparently the thought that somebody MIGHT be using Linux in a fucking IT major is completely out of this world...7 - Fuck. Fuck this shit Fuck. What the hell is this? What the fuck???? Fuck this place. How the hell is it even possible?? Fuck all. M leaving. . . . . A snapshot of my workday nowadays.8 - i outed to my boss During this moment, i had this in mind: - we do not forget - we do not forgive - we are legions result : bloody nose for me heart issues for him score : 1-1 I am leaving ...23 - - - - - - *Rant* Dear current manager, You wouldn't know real talent if it hit you in the face. Sincerely, Your employee who's leaving for a FANG2 - I came back to work after a two week vacation to find out that some people left the company and others are leaving soon. What the fuck happened while I was gone?3 - - - I'm a responsable grown up! *uses a can of glitter hairspray on hair* much adult. Such wow. Now I'm leaving behind a trail of fabulous. No regrets. Pfft and my mum keeps on asking when I'm going to have kids...34 - - - - This is my bottom drawer. That's +150 packets of honey from the cafe downstairs. I've been slowly collecting them since I started working here. I'm leaving soon and thinking about leaving them so the next dev can have a pleasant surprise 😂8 - - What my twitter looks like after Cloudflare decides to randomly close all my websocket connections from my free Discord bot, leaving it to die from arbitrary rate limits. - - - Anybody else interested in a feature to save the state/amount of "scroll" when accidentally leaving the application? - - -not commenting -leaving console logs behind in production -not testing if it works in IE -using root too much -using if instead of switch -never staying consistent with naming conventions -starting projects and never finishing3 - Hmm, What could go wrong with allowing mediocre programmers to police good programmers? Some of the core contributors are already leaving Linux behind. - Most of my friends think that leaving the browser opened on 3G will keep consuming data. In fact they also think that browsing as fast as possible will leave them with more available data on the mobile plan.4 - small victories... leaving little fuck you notes all over the code.. along with all the test cunts that still get incremented on the production.. - I solved this riddle/puzzle. Now my inner completionist split into two and both are arguing what is worse: taking the solved puzzle apart or leaving the 15 remaining possibilities unsolved... *rips of his face* 💀4 - Today I decided that from now on for all strings that need to be initialized and don't need a special value, I will assign a TIE-fighter "|-o-|". That will be my legacy.5 - The more I study IT and programming languages, the more I'm leaving Windows for Unix. Windows feels so heavy, I don't know why.6 - - First day at my first not-an-internship job, and I have to leave the place due to the medical appointment 2 hours into the day. Great first impressions I'm leaving 😂8 - Overhearing your boss pitch the application you're currently working on to a client as an effort to save them from leaving, only to also hear him list features that were never discussed as part of the application launch.1 - - - You know what is a nice phrase to write in your documentation right before you leave the job? "I leave this to the evaluation and practice of the reader." Such a delight to write that down.2 - - - The amount of icons on my Desktop is directly related to my likelihood of leaving a company. If I stop caring enough for my entire Desktop to fill up, then my foot is already out the door.1 - Finally got a new job! Outta here! Just got out of a meeting that I drove half an hour for (that could easily have been a damn phone call), for hand off stuff with the agency my company has hired to replace me. I've talked to their senior dev a few times in the past, and he always struck me as an arrogant asshole. I assumed this meant that he had some level of competence to justify this attitude, but evidently not. Turns out he and his employees are a bunch of fucking idiots who don't even know how to use the command line, or anything but a cms with stock themes. I'm taking all of the specific public stuff I've done for my employer off my resume as soon as I get back, because these dudes are going to fuck it up worse than a soup sandwich. - It's been 1 year in my crappy yet comfy and high paying IT job(my first job). I have already been in 2 dev interviews, with 3 more on the way. The end of my IT career is near, the future is bright and full of code!1 - - DevSup channel: Someone: FYI, Db is down(ticket link) Otherone: Can anyone help me connecting with db? I am having issues. I am so happy I am leaving this place in 2 months.... 😂😂1 - You know what’s more annoying than someone downvoting your answer on Stack Overflow without leaving a comment explaining why? When it’s your own answer to your own question... - Leaving my current job, after being there for 10 years straight after uni, in 2 weeks! I have now been taken out of development and have to somehow write confluence docs of all my knowledge... Fml5 - Leaving an intentional compiler error on Friday so I know where to continue on Monday. Now I have a compiler error and not a fucking clue of what I'm supposed to do with it.4 - Today a tester returned my task because “placeholder should say Bruse Wayne not John Doe”. Yes, Bruse, not Bruce. Too bad I’m leaving John Doe there and close it anyways5 - Completely drunk...coming from a farewell Party of a good colleague...sad to see good people leaving3 - Passing my projects to the next maintainer before leaving the company. And I had to leave this in the milestone - Fuck! I check my server before leaving and it's fine. I leave to go to see my dad for the weekend and maybe I can remote ftp&mysql into it. No! it crashes the minuet I try logging on!!!!!2 - - Installing Fedora Rawhide on tablet instead of arch to get some stuff working. And no I'm not leaving Arch its still my main lovely OS.4 - Kuronbka is leaving its nest for the first time, soon to became a cartridge, like the big bros. Soon gonna return to my laptop to grow7 - Never understood why other Devs are annoyed most of the time, until i started working with a project manager and having meetings 4 times a week. I can feel my soul leaving my body everyday9 - Everyone leaving early on Wednesday and you realize that it's not weekend but just No overtime working day. #welcome #to #japan Weekend still 2 days away.2 - Our intern is leaving because school started this week and our PM said it would be nice to give him something as a parting gift: "Let's make him a T-shirt and write something in frontend on it"3 - Best: completely switching to (void)-Linux and leaving winblows behind me in the dirt. Worst: everything else1 - Will be leaving the current company at the end of the Year without being able to end the worst project I have ever seen. Tempted to write an apology in the comments of one of the core files.... - I'm apparently supposed to take over some projects from the guy who sits next to me, who's leaving the country indefinitely. I don't even understand what I'm working on myself.3 - - Looking through job openings in case I get shafted so bad here I end up leaving, I see a nice sounding Java role and think "oohhh dis sounds good". Required experience: Using the Eclipse IDE. *closes page, cries* - Does it happen with anyone else - you try to fix one small bug Friday evening before leaving work and the next thing you know you are still at work at 9pm?! If it's just me, I really need a life :(4 - I just had a nightmare I spilled my gin inside my computer. Might be putting that back under my desk... And not leaving drinks on my case with an open top...4 - Getting really annoying how I think of the perfect solution on a project after leaving the office. Now I need to wait 15 hours to implement it 😭😭8 - - left work last night at 4am, leaving the laptop at the office disgustes. now i feel insecure for leaving it there on a sunday2 -*!!! - - Not writing tests for your code is like leaving it unguided in the hands of future Devs who gonna just change something and break the core logic and there won't be any regression test to run and check the integrity. - - Sometimes devs are missing social skills. I felt that today. I did not know the social code of conduct when leaving the hospital masurbitary room and meeting a colleage about to use the same room I just used.3 - - - - What's your opinion on leaving funny notes in comments from time to time? Is it highly unprofessional or you don't mind them if they are sparse? I found this on GitHub jebej/Schrodinger.jl7 - The senior developer on my team is leaving, and I'm dreading what's coming down the pipe. Basically everything he's responsible for now will land on me when he's gone. I guess now would be the time to reevaluate my salary.3 - imagine how much more intricate https would be without rsa, leaving us with just aes. i mean, youd have to have servers responding with isps, info is easily tracked. - Those days where you start to think of leaving a good job and a great team because of one insufferable cunt.1 - Me, converting shit to JSON between a data pull and an API call even though I don't have to just because the data only makes sense to my brain that way.4 - Dear last dev, thanks 4 leaving little 2 no //comments as u possibly could. 😑😣😢😠 Please //comment ur code!!1 - When leaving for the day on my last day in the company. I thought what I learned here? nothing technical except how to survive the politics, backstabber, betrayal, blame game and getting used. I wish it could be added as skills in CV.2 - Dear devrant community, I have a question... For perspective, a few years ago, we had an incident, where one dev was looking for other employment, he did not say anything, he was just looking, and ended up accepting an offer, handing in his resignation and all that. But there was another dev doing the same thing, but he informed management that he was thinking of leaving, and would be attending interviews... Personally I note difference in treatment of the dev that was honest, he was slightly getting phased out and getting the cold shoulder most of the time combined with weird kindness that was cearly not sincere, where the other dev was given a hard time for not saying anything about them looking for other opportunities, and treated as though they betrayed all the trust they had earned and no longer deserved to be trusted.... My question is, what, in your opinion, is the right thing to do when you are looking for a new opportunity? Do you tell management, or is it actually none of their business?3 - Was very sick today. Hopped over to work virtually so I can help with an issue holding up prod release. Felt pretty awesome about the whole deal. Than realized three things: 1- this was a bad example to junior devs. 2- stole learning experience from other devs 3- I am leaving this company. I should have allowed the weaning process to start2 - Is it normal when you give your leave notice, the boss (and colleagues) take it personally that much? It's unraveling more as I'm leaving that I'm working in a hell hole.8 - "Almost everything – all external expectations, all pride, all fear of embarrassment or failure – these things just fall away in the face of death, leaving only what is truly important." - Steve Jobs3 - Fuck this, I'm done, I'm leaving Facebook. Not messenger tho, all my friends are there (fuck 'em). But when you realize the thing you'll miss the most are meme pages, you can leave with peace of mind.6 - - The hardest thing I've done in the last few years, was leaving microsofts fucking insider program for windows, so hard to fucking get out. Fuck you microsoft. - True story: I got fired once for leaving placeholder text that was replaced by an Ajax call anyway.6 - when you're in the zone coding away and the coo comes into your office to kick you out because he wants to go home and he has to set the building's alarm before leaving - Has anyone said WhatsApp and fb are parting their ways or its just the founders leaving the baby with fb?1 - - I suddenly have no regrets leaving LastPass when they were bought out and started to go to shit. Lastpass now contains several trackers. - - When leaving my computer logged in, for a few minutes, I always run "cmatrix" in fullscreen ... no one dares to touch it. - Just upgraded to Mojave and Android studio 3.2. I am now leaving it all broken and going to sleep - - Compile before leaving for the night, everything's good. Compile when I come in and it's all fucked up. Over 50 files changed and hit overnight. 14 hours later, compile successful 100% That's how a day should end. - - Being a zoomer means leaving your favorite indie musician on repeat overnight for them to earn a bit more money. Being a zoomer means never leaving a one-star review on your Uber driver because if you do this, they fire them, put them on an internal blacklist that is unofficially shared between such bloody companies and they'll never find a job and probably die of starvation.9 - From time to time I go to the office bathroom and there's this guy who's leaving without washing his hands. I admire his courage for doing so even if there's people around!!2 - Finally leaving the """innovation lab""" where I worked and was a fucking garbage. I can now expect a correct project management and a real task list6 - - - - - Leaving work with a task only partly completed just guarantees my mind is going to obsess about it all night and my dreams will be plagued with lines of code.1 - Boss(at 5pm): Do you think we will have a full app by tomorrow morning Me (in mind): we are all leaving office when do u think i will work on those features2 - I hear a lot of advice saying to never take a counter offer when leaving a company. Does anyone have an experience where it has worked out?2 - EU Referendum results are in and it looks like Britain is leaving. Scary times ahead! Good job I'm part of a global industry eh? - *coffee time 5 issues* *While solving issues 4 more issues* *Total 11 new issues while leaving office* Do testers realise the gravity of time?5 - Layoffs, hard to see good working people leaving the building. You can feel the mood of the company the next days/weeks is a killer of productivity. - - Best feeling? Just leaving the office with a well-working codebase. And no bugs to fix.... until tomorrow morning.1 - - Best: leaving an overly stressful job Worst: not dev but coughing up nearly a litre of blood sucked pretty badly. Covid y'all.6 - I finish at my current role on Thursday Really can't be bothered to create more work for myself. I'm basically doing the occasional work and browsing DevRant :) - leaving work place > stay to finish important feature > on second thought we don't need this feature - So... I just finished my last day in office. I'm leaving my first job. I was expecting some emotions. Strangely, I don't feel anything more than when I'm after work. Wtf?6 - - After telling my manager I'm leaving for another company they started taking interest in my life all of a sudden and really want me to stay. In serious doubt about what I should do now.5 - Today I felt like the grinch explaining to my team that you can have memory leaks in a garbage collected language if they keep leaving live references. - I wrote like 6 or 7 functions today and havent built the project before leaving so if they all work on monday im deadass gonna do a fortnite dance - How do you do to get going quickly again after leaving code unfinished? To-do comments? Separate notes? Something else?6 - Developer in anger : I'm gonna leave this team and the manager/team will suffer for my loss and the project will fail. In the meanwhile, Manager to the senior manager : If one of the developers die or leaves the team, the project deadline extends by 1 month. Senior manager : Great. - Some of the software companies haunt their former employees to maintain the projects they worked on before leaving them, even if these companies know they have a full-time new job.4 - - A teammate wants to transition from our current team to another team while there was an ongoing project. Ended up leaving the whole project to me. FML2 - Leaving my current employer in a two and a half weeks, motivation is hard to find some days... Like today.2 - *manager behind my back me working on vim manager thinking hell he knows this s*** manager leaving, me switching to npp "this is so easy" 😂😂😂 - - Our configuration manager is leaving for a new job and now the office is crumbling. How do you deal with person dependencies at your workplace?4 - I'm leaving my internship. It was fun and now I'm sad that my day job isn't coding. Guess I gotta think of some projects for myself... - Wanted to remind you Americans that it's too late to start on a new feature, function, or debug. Go to sleep after leaving yourself some notes. You'll be better off in the morning.3 -. - Sometimes the best times are after 9pm (5pm if you work at a office) and before 7am, nobody is doing emails or phone calls. Leaving me with a nice period of time to actually get work done.4 - - I like how firebase deprecated their support for node 8 (leaving you only with node 10) but node 10 support is still in beta.. - - - - - Apparently leaving a lecture theatre is like trying to escape the bottom of a stack. We must make it more efficient!1 - Shouldn't there be a phenomenon named "critically timed bug" which always shows up like '15 mins before sleep time', '10 mins before your workplace's leaving time' or even worse '5 minutes before production/presentation'? - Is it just me or there is always a work emergency (or clients suddenly needing something new done right now) on the day before leaving for holidays?1 - Best tip for getting unstuck? If it's after your usual leaving time, GO HOME. So many times I solved the problem right away the next morning. Only wish I followed my own advice more often... - Leaving Discord open while working on personal projects. When switching between windows it’s all too easy to get distracted by a spicy shitpost strolling by...1 - a world fair has been postponed straight to the autum holidays leaving my wife all alone with the kids. can't skip being a speaker.1 - Just heard today that our team's senior dev might be leaving soon after fresh challenges and opportunities. I'm happy for them, but it's sad to think about that they won't be around soon anymore..2 - Getting predictable... Deadline day and developer takes day off sick. Or day before deadline developer takes day off sick. Leaving it all to everyone else to clean up their mess... Same people every time...1 - Because I'm leaving the company, they planned me on the project that caused me to burn out... thanks Head of Dev! You really deserve a metal for being even shittier than you already were!!5 - !!shortRant Took over a project of someone leaving the company. 5k loc in 1 File. 40 classes, mccabe average is 12. FUCK THIS SHIT1 - Got this new Macbook pro at work. It's awesome for lot of things. But apple deserves more than one MIDDLE finger for leaving no way to do a goddamn MIDDLE click. Sad Linux terminals.5 - Valid reasons to quit? i don't want to do it. But I see people leaving enterprises every 6 months.7 - Reading devRant and new job postings is leaving me with less time to write any code in this shit hole. - On a white board discussing with the team, rubbed list leaving numbers so that I won't have to list them again.1 - I never thought that my usual lunch buddies/co-interns leaving would cause me to have a hard time coping up. I'm very unproductive these past three days. I feel so sad. - - !rant i just to ask people here what made them quit or look for another job at another company. I need some insight because i have conflicting feelings about leaving earlier than expected.11 - Today is the last day of my placement. Over the past year, I began working on small front end bugs, to becoming the sole front end developer on the project, to being full stack. Back in July, I and the other dev on the project released the app into the wild. It now is reaching 100 users. The app has a lot of external dependencies (10+), one of which could cripple it entirely should it cut us off (which they can do at any time, it's a free API). I was given, effectively a week and a two days to do a complete handover/transfer of knowledge to the placement student that will be taking my place. They hadn't touched front end (like me) when starting, but also had no experience in node/js. As of this, I can't leave feeling like I've fully completed my work, and I feel bad leaving the new guy with these clients. Undoubtedly I'll be doing some off-the-record help. - "hey, i know you're leaving on vacation tomorrow but could you develop this small feature for me before you go?" :/2 - - - - "When you do something, you should burn yourself up completely, like a good bonfire, leaving no trace of yourself." - Shunryu Suzuki3 - - I've implemented Chat function for my app. Since I'm a security noob what is the preferred way of encrypting the messages End-to-end maybe? I'm definitely not leaving them as plain text :)4 - - - Leave JAVA TF alone. You ungrateful bastards. Leaving your long time love for these small ass small houses of programming languages1 - Since many of youtubes best creators are leaving in november due to the spartan google policies, just wondering where people will be going next? Any up and coming video platforms anyone recommends? Any of your favorite channels already switching?15 - - Asshats in QA, Kindly please be leaving me the fuck alone so I can work. Fuck off, -Rowsdower (Sorry, 'ol Rowsdower's grumpy today.) - - I will leave in September this job location, but what's weird is that I've already (yesterday, a causality) shacked the hand to the next probable guy that going to continue on my work. I do have planned the change of location by the same company, btw. Is it normal to see this happening so early? (More than 4 months) - Pomodoro technique but with 52min stretches and 15 min breaks. For avoiding procrastination: create 2 Todo lists every day before leaving work, one for small tasks to be done first thing in the morning and others throughout the day.1 - That feeling when you notice, that you have a pokestop right infront of yout house😍.... .... Now I can catch Pokemons without leaving the house. Thank You Lure Modules! - Every time i try to learn a new skill it always ends up in leaving the course in between. Does this only happens to Me? Or there is anyone else?3 - Walk away get a break. Hit coffee or table tennis, than come back on the problem. I am assuming you already googled before leaving. - !rant So, after being remanaged from Localization PM to create an Automation department, my boss now asked me help to manage projects again, but not leaving the automation. Let's see how things will happen.1 - - About to accept another job, having some guilt towards leaving my coworkers during a stressful time. Anyone else felt something similar?1 - - Well once someone tell you please give more effort at work and you provide your maximum then he finds it not enough. I guess it will be more than fair to leave without any discussion.3 - What do you think took windows out of the mobile phone race leaving just iOS and Android when they have some of the best development tools?7 - !rant Super pumped to be leaving for my hometown,Bangalore tomorrow after a little more than 3 years.😊 - - - Best: leaving Job in just 6 months to start freelancing. Worst: yet to make :p, probably I'm planning to stop working for masters or moving to Geemany from India for on site project. And both are pretty much risky 😅 - - Not gonna lie but i feel so much more peace of mind after blocking all whores from my contacts and leaving little to no but good and high quality people left2 - It would be cool if the comments for the rant postings were able to be viewed/interacted with on the rant feed without leaving the page.1 - - When I normalize a database, it always feels like I cannot predict Cascading, leaving broken relationships and trash queries.2 - *guy* Starts to think of getting into ethical hacking. Downloads Kali and installs fuckload of apps. Doesn't want to get caught so spends first hour on setting up a VPN. Ends up leaving "white stains" on the laptop. - - Finally working on rewriting the core of our internal platform on CakePHP 3. It feels so good leaving the legacy codebase behind!4 - - That time my then employer decided to build an ERP system but was unable to fund the process, long story short delayed salaries, low morale, everyone on the team leaving, sad times - Area of focus...leaving a couple tests running while I go enjoy a coffee on the balcony and focus on making the payloads more serious/articulate/real . - Another dark theme with Monokai conversion achieved today. I feel like I'm leaving this world in a better place. - A.I surgeon. They'll "get sick" at some point I wonder what the equivalent of leaving tools in a patient's body would be 😈 - I am planning on leaving my current office and work on freelancing projects. Any suggestions where I can find such projects?2 - AOA friends please help me to solve the program of C++ #include <iostream> using namespace std; int main() { int passengers = 126; int empty_seats = 0; //passengers =126; passengers after 1st bas leaving= passengers - 50; passengers after 2nd bas leaving= passengers - 50; passengers after 3rd bas= passengers; empty_seats= 50 % passengers; cout << "Empty seats in last bas"<< empty_seats <<endl; return 0; }34 Top Tags
https://devrant.com/search?term=leaving
CC-MAIN-2021-31
refinedweb
6,543
72.26
You can use Page Fragments to take your design vision and accurately realize it on a web page. You start with a “blank slate.” You then have three tools at your disposal to accomplish your vision: HTML: The markup of the fragment. Fragments use standard HTML with special tags to add dynamic behavior. CSS: Styles and positions the fragment’s markup. JavaScript: Provides dynamic behavior to the fragment. The HTML, CSS, and JavaScript are all completely standard, but can be enhanced with Liferay-specific features. You can specify text, images, and links as editable and provide for “rich” text with formatting. You can also access the FreeMarker templates engine from your HTML using the alternative (square bracket) syntax. Learn more about available FreeMarker objects in Front-end Reference. Liferay portlets can also be embedded in Fragments as widgets, making pages with Fragments more dynamic than regular web content. Now you’ll step through some Page Fragment basics. Developing Page Fragments There are two types of Page Fragments: Sections and Components. A Section defines columns, padding, and spacing on the page. A Component contains content that is added to a Section. Fragments are created inside of Collections. Collections provide an easy way to manage and share groups of related Fragments. Users navigate Collections when selecting Fragments to add to a page. To see examples, the admin page shows all the out-of-the-box Fragments (and their code). You can create and manage Fragments and Collections without using any external tools, but you can also use your preferred web development tools. For an explanation of Fragment creation using Liferay’s built in tools, see Creating a Fragment. Making a Fragment Configurable Page Fragments are also configurable: defining configuration options for your fragment eliminates having to maintain multiple other fragments similar in style. For example, if you want a dark background banner and a light background banner, you can create one banner with a configuration option for background type. The following field types are supported for Fragment configurations: checkbox colorPalette itemSelector text This is available for all Fragment types (e.g., Fragment Renderer, etc.). For more information, see Making a Fragment Configurable. Fragments CLI To streamline fragment development, Liferay DXP 7.2 provides command line tools for generating, importing, and exporting fragments and fragment collections. For more information about the CLI, see the official Liferay Fragments CLI project reference. Using this CLI is also covered in Developing a Fragment using Desktop Tools. Contributed Collections Most of the time, Page Fragments are created and imported through the Page Fragments interface or created directly using the built-in tools. Any user with the right permissions can update or edit Page Fragments created like this. You may have certain situations, however, where you want 100% static fragments that cannot be modified. In this case you can create a Contributed Fragment Collection. Contributed Fragment Collections are deployable modules containing Page Fragments. Those fragments can be used just like regular fragments, but are not contained in the database, and cannot be modified except by updating the module they came from. Use the Creating Contributed Collections guide to learn to create your own Contributed Collections. Fragment Specific Tags In addition to standard HTML, CSS, and JavaScript you can use Liferay-specific tags to make editable sections or embed widgets in your Fragment. Editable elements can be modified before publication. This means that web developers can create simple, reusable fragments that have identical formatting, but contain elements that are adaptable to the specific context. You can make text, images, and links in a fragment editable by using an <lfr-editable> tag. The <lfr-editable> tag requires a unique id, a type, and some content of the specified type inside. The following four type options are available in an lfr-editable tag: text: Creates a space for editable plain text. image: Must contain a valid <img> tag which can then be replaced with an image before publishing—including those from Documents and Media. rich-text: Provides rich text formatting, such as bold, italics, underline, links, and predefined styles. link: Must contain a valid anchor tag for which the style, target URL, and link text can be edited before publishing. The text or images you provide here are the default values for the fields. You may want to display them in the final version of the page, or you may want filler text that should be replaced before the page is published. All of these work together to help you create dynamic, reusable elements for building a site. For example, if you need a small text box with an image and link to provide a product description, you can create a fragment containing editable filler text, space for an editable image, the appropriate formatting, and an editable link. That fragment can be added to multiple pages, and marketers can define the image, text, and link for each product they need to describe. You can make a Fragment even more dynamic by including a widget. Currently, portlets are the only embeddable types of widgets, but other options are planned. You can find a complete list and usage examples of these in the Page Fragments Reference. Recommendations and Best Practices In general all your code should be semantic and highly reusable. A main concern is making sure that everything is namespaced properly so it won’t interfere with other elements on the page outside of the Fragment. CSS While you can write any CSS in a fragment, it’s recommended to prefix it with a class specific to the fragment to avoid impacting other fragments. To facilitate this, when creating a new fragment, the HTML includes a div with an automatically generated class name and the CSS shows a sample selector using that class. Use it as the basis for all selectors you add. JavaScript Avoid adding a lot of JavaScript code, since it isn’t easily reusable. Instead, reference external JS libraries.
https://help.liferay.com/hc/ja/articles/360028726832-Page-Fragments
CC-MAIN-2021-49
refinedweb
990
55.34
by teomoiseev GitHub Readme.md Simple signalling server that can be used to coordinate handshaking with webrtc or other fun stuff. npm install signalhub Or to install the command line tool npm install -g signalhub var signalhub = require('signalhub') var hub = signalhub('my-app-name', [ '' ]) hub.subscribe('my-channel') .on('data', function (message) { console.log('new message received', message) }) hub.broadcast('my-channel', {hello: 'world'}) hub = signalhub(appName, urls) Create a new hub client. If you have more than one hub running specify them in an array // use more than one server for redundancy var hub = signalhub('my-app-name', [ '', '', '' ]) The appName is used to namespace the subscriptions/broadcast so you can reuse the signalhub for more than one app. stream = hub.subscribe(channel) Subscribe to a channel on the hub. Returns a readable stream of messages hub.broadcast(channel, message, [callback]) Broadcast a new message to a channel on the hub hub.close([callback]) Close all subscriptions You can use the command line api to run a hub server signalhub listen -p 8080 # starts a signalhub server on 8080 To listen on https, use the --key and --cert flags to specify the path to the private key and certificate files, respectively. These will be passed through to the node https package. To avoid logging to console on every subscribe/broadcast event use the --quiet or -q flag. Or broadcast/subscribe to channels signalhub broadcast my-app my-channel '{"hello":"world"}' -p 8080 -h yourhub.com signalhub subscribe my-app my-channel -p 8080 -h yourhub.com This also works in the browser using browserify :) Through the magic of free hosting, here are some free open signalhub servers! For serious applications though, consider deploying your own instances. No additional configuration is needed. now mafintosh/signalhub MIT
https://elements.heroku.com/buttons/teomoiseev/signalhub
CC-MAIN-2021-04
refinedweb
296
57.57
#include <MSelectInfo.h> MSelectInfo is used with user defined shape selection and is passed as an argument to the MPxSurfaceShapeUI::select method. This class encapsulates all the selection state information for selected objects. apiMeshShapeUI.cpp, apiMeshShapeUI.h, apiSimpleShapeUI.cpp, apiSimpleShapeUI.h, and quadricShape.cpp. Constructor. Copy constructor. Destructor. Returns the view that the current selection is taking place in. This methods determines if we want to select a single object. Determines if we want to select the closest object. Given the selection mask, this method determines if the object is selectable. Given the selection mask, this method determines if the component is selectable. Is there a selection ray. This method isused to find ray object intersection. Returns the alignment matrix. This method is used to find ray object intersection. Get the selection ray. This method isused to find ray object intersection. Give the selection mask, can this object be selected for the hilite list. This means that you can only select components if the object is hilited. Returns the highest selection priority value. Sets the highest selection priority value. Adds components or objects to the active selection list. For an example of how this is used please refer to the method definition apiMeshShapeUI::select() in the devkit example code apiMeshShape.cpp. Returns a path to the item that is being selected.
http://download.autodesk.com/us/maya/2009help/API/class_m_select_info.html
crawl-003
refinedweb
221
52.76
FM-index is the fastest full text search algorithm using a compressed index file. This is FM-index for JSX/JS/AMD/Common.js. FM-index is the fastest full text search algorithm using a compressed index file. This is FM-index for JSX/JS/AMD/Common.js. FM-index is the alternate search algorithm of an inverse index algorithm. FM-index has the following advantages: import "fm-index.jsx";class _Mainstatic : voidvar fm = ;fmpush"hello";fmpush"world";thisfmbuild5;console.logthisfmsearch'world'; // -> [5] var FMIndex = require'fm-index.common.js'FMIndex; // use fm-index.amd.jsdefine'fm-index.amd.jsx'var fmindex = fmindexFMIndex;// Write simple usage here!; $ npm install fm-index.jsx You should add the following modules to package.json if you want to use from JSX: If you want to use this library from other JSX project, install like the following: $ npm install fm-index.jsx --save-dev or add like these lines to your parent project's package.json: devDependencies:"fm-index.jsx": "~0.3.0"peerDepenencies:"fm-index.jsx": "~0.3.0" And add node_modules/fm-index.jsx/src as a search path. You should add to peerDepenencies if your product is library. Constructor. Append string. Return total length of pushed string. It is available before build(). Build search index. ddic is a cache density. (1 / ddic) * 100 % is a actual cache rate. If ddic == 1, densty = 100%, it provides maximum speed but it use match memory and storage. Initial recommendation value is 50. maxChar is a maximum character code. If you reduce this, you can save memory. Return contetn size. It is available after build(). Return position list that includes keyword. Return original document content. Export bit-vector. Import bit-vector. Don't be afraid JSX! If you have an experience of JavaScript, you can learn JSX quickly. To create development environment, call following command: $ npm install $ grunt test $ grunt build $ grunt doc MIT Complete license is written in LICENSE.md.
https://www.npmjs.com/package/fm-index.jsx
CC-MAIN-2015-40
refinedweb
326
55
Apr 16, 2012 05:11 PM|LINK I'm trying to route a .aspx (webforms page) in my asp.net mvc project. I register the page in global.asax: routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapPageRoute("Tickets", "Reports/Tickets", "~/WebForms/Reports/Tickets.aspx"); routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); The problem is, after i add the second line, the site stops to enter in my Home Controller (Index Action) and is redirecting to: always that i run the project. Project Details: Obs: to reproduce this error, create a new asp.net mvc project as internet app, after create the `Tickets` webforms page inside a `/WebForms/Reports` folder, and register the new route. Run the project (probably you're logged), so now logoff and you will be redirected to ``, so why? All-Star 18647 Points Apr 16, 2012 05:22 PM|LINK I answered this in your other thread, but you need to add a route containt to the webforms route to ensure that it only catches on incoming routes, not outgoing route generation. Add the following class to your project (either in a new file or the bottom of global.asax.cs): public class MyCustomConstaint : IRouteConstraint{ public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection){ return routeDirection == RouteDirection.IncomingRequest; } } Then change the Tickets route to the following: routes.MapPageRoute( "Tickets", "Reports/Tickets", "~/WebForms/Reports/Tickets.aspx", true, null, new RouteValueDictionary { { "outgoing", new MyCustomConstaint() } } ); All-Star 26445 Points Apr 16, 2012 05:22 PM|LINK If you are using Forms Authentication as you mentioned, are you using something such as an [Authorize] attribute on a specific method or controller that may be causing the redirect. If that isn't the issue - you may want to look into adding a constraint to your routes (Adding Route Constraints). Apr 16, 2012 05:29 PM|LINK @CodeHobo, if not asking so much, can you explain me why this happens? Or give me some link to understand this problem? All-Star 18647 Points Apr 16, 2012 05:47 PM|LINK No problem, I'm not sure about the internals. But the routing engine is confusing an MVC route with a webforms route, so when you call @Html.ActionLink, instead of selecting the correct mvc route, it was picking the webforms route. By specificy a route contraint you ensure that the webforms route is only used for handling incoming requests and not generating links. That's the behavior you want, as you don't want @Html.ActionLink to generate a link to a webforms page. 5 replies Last post Apr 16, 2012 06:04 PM by Vecthor
http://forums.asp.net/t/1793462.aspx/1?After+add+MapPageRoute+to+an+asp+net+mvc+project+the+site+stops+to+enter+in+Home+Controller
CC-MAIN-2013-20
refinedweb
443
56.15
Only one sample is presented, and I didn't bother to convert it to a test case, I just ran my Python script passing the provided input and I had visual check on the result. The point is the problem is not difficult, it just takes some time to get understood properly. At least in my case. However, if this is the input: $#**\0100000101101100011100101000We are expecting this output: ##*\$Here is the logic behind the transformation. The first characters represent the dictionary used in this message. We know that they are over when we read a zero or a one. In our case they are five: $#**\We convert them in a variable size string of zeros and ones, listing all the numbers from zero on, but skipping the ones represented by 1-only binary numbers: $ -> 0 # -> 00 * -> 01 * -> 10 \ -> 000If we had a sixth element, it would have been coded as "001". Then we have a three-character block, that we have to read as a binary number, and give as the size of the following chunks in the message. Here is "010", meaning 2. We go on reading elements of this size until when we get a terminator, represented by an all-one sequence: 00 00 10 11We have three valid elements, and a terminator. We get the first part of our message: # # *Back to the size, this time is "011", meaning 3. So we get on reading three by three, until the terminator: 000 111We already knew the only valid character sized 3 was '\', here we have one on it. Read again the size, is "001". We read one character at the time. 0 1There is just a single zero before we get 1, that is the sequence terminator. We add '$' to the decoded message and we read again the size, that is zero: 000End of transmission. The message was "##*\$". Job done. Writing a solution in Python, I used a generator to create the keys for the letters in the dictionary: def key_generator(): size = 1 cur = 0 while True: yield format(cur, '0{}b'.format(size)) if cur == 2 ** size - 2: size += 1 cur = 0 else: cur += 1I keep the generator status in two variables, size, that knows how long should be the generated key, and cur, that knows the binary value that should be pushed in that space. The yield statement converts the cur value as expected, using both the built-in format() function and the format() string method. The first gets in the cur value and converts it to a string containing its binary representation. The second provides to the numbers of characters that the binary string should take. Than we prepare to the next iteration. If increasing the cur we'd get a 1-only binary number, we skip it, resetting cur to zero, and increasing the size. Otherwise it is just a matter of increasing cur. Now I just have to use the generator to map the provided characters to their coded representation: mapping = {} i = 0 for key in key_generator(): # 1 if line[i] not in ['0', '1']: # 2 mapping[key] = line[i] i += 1 else: break # 31. I instantiate the generator and loop indefinitely on it. 2. If the current character is valid, I couple the key to it in the dictionary that I named mapping. 3. When I detect a '0' or a '1' I stop filling the dictionary. I implemented the result generation with a boring double loop: result = [] while True: size = int(line[i:i + 3], 2) # 1 if size == 0: break i += 3 while True: chunk = line[i:i+size] # 2 i += size if chunk not in mapping: # 3 break result.append(mapping[chunk]) # 41. Convert a three character substring in an integer, considering it as binary. If it is zero, job done. Otherwise move the index in the line and go on reading. 2. Get a chunk of the specified size. 3. There is not such a key in the dictionary, meaning, we got a terminator. Interrupt the inner loop. 4. Otherwise convert the chunk in the actual character and put it in the result list. We just have to collate the result in a string an return it to the caller. I pushed the Python3 script to GitHub.
http://thisthread.blogspot.com/2017/03/codeeval-message-decoding.html
CC-MAIN-2018-43
refinedweb
710
70.53
> I have a random spawner and I have 7 objects and each object has a tag. I want destroy same objects with tag. I use a sign with 7 objects and another 7 objects is spawned. Those are has same tag. How can i destroy spawned objects according to sign? Sorry for bad english. i hope it's will enough for understood. Answer by poisoned_banana · Apr 08, 2018 at 04:22 PM public void DestroyAllWithTag(string tag){ GameObject[] objects = GameObject.FindGameObjectsWithTag(tag); foreach(GameObject obj in objects){ Destroy(obj); } } I don't want destroy all. I just want destroy spawned objects according to sign. For example. if sign is red. I want destroy just red objects. or sign is blue just destroy the blue. Simply, if the resulting objects have the same tag as the indicator, I want to destroy them. This function is fine for your purpose, just pass to it the desired tag to be destroyed specified by your sign. For example, when you hit the red sign, you call DestroyAllWithTag("red") (assuming that red objects all have the tag "red"). If this is unclear, or not what you want, then please give more details about your project, what kind of game you are making, how it works, and what you want to achieve. DestroyAllWithTag("red") Answer by rebelarcher · Apr 09, 2018 at 03:27 PM green object is my sign and its random spawn in there between 7 colors. And other spawned objects is like enemies. if sign is green i just want destroy green enemies. @poisoned_banana method is fine just call it when you spawn the sign : spawn(sign_object); // or show us your spawning code DestroyAllWithTag(sign_object.tag); using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawn : MonoBehaviour { public GameObject[]enemies; public Vector3 spawnValues; public float spawnWait; public float spawnMostWait; public float spawnLeastWait; public int startWait; public bool stop; int randEnemy; void Start () { StartCoroutine (waitSpawner ()); } void Update () { spawnWait = Random.Range (spawnLeastWait, spawnMostWait); } IEnumerator waitSpawner(){ yield return new WaitForSeconds (startWait); while (!stop) { randEnemy = Random.Range (0, 7); Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1 ,Random.Range(-spawnValues.z, spawnValues.z)); Instantiate(enemies[randEnemy],spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation); yield return new WaitForSeconds (spawn can i destroy multiple objects with tag? 2 Answers Destroy Enemies With Tag/Color/Name according a indicator. 0 Answers How do i make an object spawn another one? 1 Answer Spawn Objects at Different Locations with Tags? 2 Answers Spawn Script Assistance? 1 Answer
https://answers.unity.com/questions/1490997/find-and-destroy-multpile-gameobject-tag.html
CC-MAIN-2019-13
refinedweb
422
60.31
1 Aug 01:06 2008 Re: newbie - map reduce not distributing Dru Jensen <drujensen@...> 2008-07-31 23:06:50 GMT 2008-07-31 23:06:50 GMT UPDATE: I modified the RowCounter example and verified that it is sending the same row to multiple map tasks also. Is this a known bug or am I doing something truly as(s)inine? Any help is appreciated. On Jul 30, 2008, at 3:02 PM, Dru Jensen wrote: > J-D, > > Again, thank you for your help on this. > > hitting the HBASE Master port 60010: > System 1 - 2 regions > System 2 - 1 region > System 3 - 3 regions > > In order to demonstrate the behavior I'm seeing, I wrote a test class. > > public class Test extends Configured implements Tool { > > public static class Map extends TableMap { > > <at> Override > public void map(ImmutableBytesWritable key, RowResult row, > OutputCollector output, Reporter r) throws IOException { > > String key_str = new String(key.get()); > System.out.println("map: key = " + key_str); > } > > }(Continue reading)
http://blog.gmane.org/gmane.comp.java.hadoop.hbase.user/month=20080801
CC-MAIN-2015-11
refinedweb
161
62.07
OpenCV crashes after playing a video... help.. please! I am going thru the tutorials to learn OpenCV. And I have a problem. When I run this code: which is plain vanilla code I get this error after the video finishes:which is plain vanilla code I get this error after the video finishes: import cv2 cap = cv2.VideoCapture('C:\Users\wg\174037210.avi') while(cap.isOpened()): ret, frame = cap.read() cv2.imshow('Video', frame) if cv2.waitKey(75) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() Traceback (most recent call last): File "C:/Users/wg/python/video-test.py", line 15, in <module> cv2.imshow('Video', frame) cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow' The environment is as follows: Windows 7 Professional Python 3.6.5 OpenCV 3.4.3 Any help is greatly appreciated. Thanks! @wgb-2019, You need to check that your video is finished. retis a flag for it. python users NEVER check their input, or return values. @berak, As for me, if a python variable isn't used, it's better to name it correspondingly. In example, _, frame = cap.read(). ... but they HAVE to check the retvalue ! if the movie comes to an end, the last frame will be empty / invalid, and the NEXT line of code will crash.
https://answers.opencv.org/question/206687/opencv-crashes-after-playing-a-video-help-please/?sort=votes
CC-MAIN-2022-40
refinedweb
238
71
Cyrill Gorcunov <gorcunov@gmail.com> writes:>> nested checkpoint/restore simply because even plain and direct CR still> has a number of problems which are not yet addressed.>> As to return such ID in ino field (if I understand you right -- you> propose to return such ID as inode of kstat structure) -- I don't think> it would be right either. Instead of one iteface applied to all objects> we export there will be a few different approaches instead -- for net-ns> it would be dev+ino, for tasks and other members of task-structure> it'll be IDs from /proc (as implemented in another patches). I like> more Kyle's idea about object_id() call which would simply return the> entrypted ID to user-space and it'll be up to user-space to do anything> it wants with such pieces of information.Right now everything thing that is exported is dev+ino. My objectionis that you are adding yet another interface to get that information.I already have patches that already implement dev+ino for the namespacesso I fully expect that to happen independently of your patches. Mypriority is to get the rest of the namespaces exported which requiresa bit more review.> Yes, there will be no way to restore such IDs later but the interface> is not supposed to work this way.It sounds like it won't be possible to retrofit the ability to restorethe IDs later. If the path to what will be needed to support nestedcheckpoint/restore is not clear the user space interface is brokenby design. And since it is broken by design I say the design needsto bake more before we think of baking it.> All this mess only because of lack> of way to figure out which task resources are shared and which are not.> Maybe if we can carry CLONE_ flags from copy_process()/unshare()/setns()> (and which else modify task resources?) inside task_struct and provide> these flags back to user-space we might not need the IDs helpers at all.> But I think such approach might end up in a pretty big patch bloating> the kernel. In turn I wanted to bring as minimum new functionality as> possible *with* a way to completely turn it off if user don't need it.The tricky case is file descriptors and file descriptors can be passedover unix domain sockets in arbitrary ways.If you can find a way to do this without id helpers that sounds likea good design.I have a nasty feeling that by trying to do this piecemeal instead ofin one big system call you are slowly painting yourself into a cornerfrom which you can not get out.Eric
https://lkml.org/lkml/2012/1/4/220
CC-MAIN-2015-22
refinedweb
448
68.1
A query regarding validation of xml-schemas Discussion in 'XML' started by Divya Alice George,: - 837 - Tony Prichard - Dec 12, 2003 mutliple schemas/namespaces - xml validationDominique, Jun 29, 2004, in forum: XML - Replies: - 3 - Views: - 497 - Dominique - Jun 29, 2004 XML Schemas: Advanced Validation, Mar 13, 2008, in forum: XML - Replies: - 3 - Views: - 528 Why do we need XML Schemas other than for automatic validation?Water Cooler v2, May 15, 2008, in forum: XML - Replies: - 3 - Views: - 931 - Andy Dingley - May 18, 2008 Can xml schemas from a dataset be used to validate standard xml files?Andy B, Aug 7, 2008, in forum: ASP .Net - Replies: - 0 - Views: - 405 - Andy B - Aug 7, 2008
http://www.thecodingforums.com/threads/a-query-regarding-validation-of-xml-schemas.165839/
CC-MAIN-2015-18
refinedweb
114
60.48
specifications. our best selling porch railing system. price includes all four pieces. made of seven trust clear western cedar. use with 2 1/2 and 3 1/2 spindles and balusters.. also can be used with sawn balusters.. sloped bottom rail provides better water drainage which helps prevent rot and is recommended for exterior applications. saudi arabia stainless steel handrail, saudi arabia stainless steel handrail suppliers and manufacturers directory - source a large selection of stainless steel handrail products at stainless steel ,stainless steel bottle ,stainless steel tumbler from saudi arabia alibaba.com there are 303 wrought iron railing for sale on etsy, and they cost $226.62 on average. the most common wrought iron railing material is metal . the most popular color? saudi arabia handrail, saudi arabia handrail suppliers and manufacturers directory - source a large selection of handrail products at balustrades inox handrail balcony ,balustrades handrails ,handrails for outdoor steps from saudi arabia alibaba.com 68 ho/hon3 scale rix products 628-0124 wrought iron highway overpass railings. time left2d 1h left 0 bids top rated seller c $4.54 shipping from united states 6 new and refurbished from us $6.95. import china stairs railing from various high quality chinese stairs railing suppliers and manufacturers on globalsources.com. we use cookies to give you the best possible experience on our website. for more details including how to change your cookie settings, please read our cookie policy . saudi ekmal considers the quality as the first sensitive factor to provide a unique product and service. thus, it is our responsibility to adhere to the most common international standards for our supplied products in both material grades and fabrication standards. < sponsored listing tags: stair handrail railing glass stair handrail railing outdoor handrail railing outdoor house aluminum glass handrails us $ 60.0 - 100.0 saudi arabia and bahrain, welded type handrails are fabricated as per client dings, vertical handrail posts, horizontal top and mid rails, toe or kick plates all are welded together before painting or galvanising there are 3,819 handrails for outdoor steps suppliers, mainly located in asia. the top supplying countries or regions are china, india, and saudi arabia, which supply 99%, 1%, and 1% of handrails for outdoor steps respectively. handrails for outdoor steps products are most popular in north america, oceania, and south america. china stair handrail manufacturers - select 2019 high quality stair handrail products in best price from certified chinese stainless steel manufacturers, china fence suppliers, wholesalers and factory on made-in-china.com saudi arabia 3 online service stair railing, stair railing suppliers and manufacturers at alibaba there are 3,566 outdoor handrails for steps suppliers, mainly located in asia. the top supplying countries or regions are china, india, and saudi arabia, which supply 99%, 1%, and 1% of outdoor handrails for steps respectively. outdoor handrails for steps products are most popular in north america, oceania, and africa. sudhakar engineering - manufacturer of stainless steel handrail, spiral staircase and elevation glass railing from coimbatore, tamil nadu, india high design. myriad options. our highest-performance railing option offers more colours in more component profiles than any railing out there. wont rot, warp, peel or splinter which trumps sanding row after row of timber balusters any day and it never needs painting or staining, ever.
https://www.thehoosebelfast.co.uk/fence/1456-exterior-stair-handrails-price-saudi-arabia.html
CC-MAIN-2020-24
refinedweb
546
54.22
hi i want to take in a integer from the user and use a boolean true or false to find out if each number is unique?? i know how to take in the number and convert it to a string but having trouble setting conditional to compare each character. I thought you could compare each element of the string to the other element but am not sure how to do thisThis what i have so far I am only doing java 3 weeks . import java.util.Scanner; public class Numberunique { public static void main ( String args[] ) { int userInput = 0; boolean unique = false; String myString = ""; Scanner input = new Scanner( System.in ); System.out.println (" enter your number"); userInput = input.nextInt(); myString = Integer.toString(userInput); for ( int i = 0; i <= myString.length (); i ++) { if ( myString. charAt(0) == myString.charAt(1)) unique = false; } System.out.println( "the number entered " + unique ); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/18027-class-assignment-printingthethread.html
CC-MAIN-2014-15
refinedweb
147
66.44
Sona Systems, Ltd. EXPERIMENT MANAGEMENT SYSTEM Master Documentation Set - Eric Norton - 2 years ago - Views: Transcription 1 Sona Systems, Ltd. EXPERIMENT MANAGEMENT SYSTEM Master Documentation Set Version 2.61 Revision A Copyright 2005 Sona Systems, Ltd., All Rights Reserved 2 About This Manual This manual covers usage of the system from a variety of perspectives: Participant (Student), Researcher/Principal Investigator, Instructor, and Administrator. The manual is broken out into sections based on the type of user. As a licensee of the software, you are granted a right to copy this documentation, modify it, and distribute it within your organization. You may not distribute it outside of your organization without prior written permission from Sona Systems, Ltd. You are encouraged to copy and modify this documentation to suit the needs of your organization. You will find this documentation covers every feature of the software, while you may have chosen to disable certain features in your implementation. Your users may prefer to read documentation that covers the system exactly as they will experience it, as opposed to this documentation, which may cover features that are not enabled for them. 1 3 PARTICIPANT (STUDENT) DOCUMENTATION... 6 Introduction... 6 Getting Started... 6 Requesting an Account... 6 Logging In... 7 Retrieving a Lost Password... 8 Logging Out... 8 Changing Your Password and Other Information Address Options... 9 Unique ID Codes Studies Viewing Studies Two-Part Studies Online Survey Studies Signing Up For Studies Canceling a Sign-Up Tracking Your Progress Reassigning Credits Online Pretests Frequently Asked Questions RESEARCHER/P.I. DOCUMENTATION Introduction System Basics Principal Investigator Special Note Participant ID Codes Special Note Getting Started Logging In Retrieving a Lost Password Logging Out Changing Your Password and Other Information Address Options Working with Studies Web-Based (Online) Studies Studies for Pay Two-Part Studies Adding a Study Updating a Study Deleting a Study Pretest Participation Restrictions Viewing Your Studies Viewing Other Studies Online Survey Studies Introduction Creating or Modifying a Survey General Survey Information 4 Section List Adding or Modifying a Section Adding or Editing a Question Copying a Question Saving Your Changes Deleting a Participant s Survey Responses Analyzing Survey Responses Working with Timeslots (Sessions) Timeslot Usage Restrictions Creating Timeslots Creating Multiple Timeslots Modifying and Deleting Timeslots Deleting Multiple Timeslots Manual Sign-Up Manual Cancellation Viewing the Participant List Viewing Pretest Responses Granting or Revoking Credit Batch Credit Granting ing Participants Viewing Uncredited Timeslots Analyzing Pretest Responses Pretest Qualification Analysis Frequently Asked Questions (FAQ) Regulatory Compliance Guidelines Introduction Data Handling and Security Guidelines Human Subjects/Privacy Policy Acknowledgment INSTRUCTOR DOCUMENTATION Introduction Getting Started Logging In Course Reports Granting Credits Viewing Studies Changing Your Password Logging Out ADMINISTRATOR DOCUMENTATION Introduction Getting Started Typical Administrator Tasks Start-of-Term Tasks Ongoing Tasks End-of-Term Tasks General User Notes User IDs 5 Duplicate User IDs s and User IDs Participant Unique ID Codes Importing Users Preparation Tasks Performing the Import Adding and Editing Users Overview Finding Users Editing Users Adding Users Deleting Users Participants with Excessive No-Shows Removing a User s Access to the System New Participant Account Message Principal Investigator (P.I.) Accounts Principal Investigator Timeslot Usage Limit Researcher Accounts Researcher Timeslot Usage Limit Administrator Accounts Participant Account Self-Creation Overview Automatic Account Approval Approving Accounts Online Pretests Introduction Privacy Protections Pretest Participation Credits Creating or Modifying a Pretest General Pretest Information Section List Adding or Modifying a Section Adding or Editing a Question Copying a Question Saving Your Changes Deleting a Pretest Generating Reports Overview Credit Completion Reports No-Show Reports Unassigned Credit Reports Time Usage Reports Study Attendance Reports Credit Usage Report Resource Usage Report System Summary Report 6 Pretest Reports ing a Group of Users Nightly Reminder s Batch Operations Granting Non-Study Credit Course Maintenance Location Maintenance and Scheduling End-of-Semester Maintenance Exporting Data Clearing Out Old Data Monitoring Studies Batch Study Updates Updating System Text Frequently Asked Questions Feature Requesting Technical Support Frequently Asked Questions (FAQ) System Settings Settings That You May Change at Any Time Settings That May Only Be Changed when the System is Empty Regulatory Compliance Introduction Handling an Information Request Data Handling and Security Guidelines Strict IRB Mode Human Subjects/Privacy Policy Acknowledgment 7 PARTICIPANT (STUDENT) DOCUMENTATION Introduction The Experiment Management System provides an easy method for you to sign up for studies, and track your progress through the term. Everything is done through the software s web-based interface, so you can access the system at any time, from any computer, with a standard web browser. It should be noted that this documentation covers all the features in the system, but your organization may have chosen to disable certain features. Do not be alarmed if the documentation covers options and features that are not visible on the system you are using. notification immediately with your login information, or you may receive the notification only after the administrator has approved the account. The notification will include login instructions for the system. You will be assigned a default password, which you can change after your first login. In many cases, you may also provide an alternate address (after your first login) if you prefer to receive future notifications at another address. The will come from the administrator s address (listed on the request account page), so be sure to configure your junk mail filters to allow from that address. 6 8 Figure 1 - Requesting an Account If your organization has not enabled this feature, then your organization will create an account on your behalf. You will receive this account information, most likely by . Logging In Once you have your login information, go to the front page of the site and enter your user ID and password to login. Figure 2 - Login Page 7 9 Once you login, you may be asked to review and acknowledge your organization s human subject policy for research. You will need to acknowledge this only once every 6 months. You may also be asked to participate in a pretest. After you complete these tasks, you will see the Main Menu. Figure 3 -. This is especially important if you are using a public computer lab. Retrieving a Lost Password If you have forgotten or do not have your password, and the feature is enabled on the system, then you may choose to have your password ed to you. You will see an option on the front. 8 10. Figure 4 - Updating Your Profile Address Options There are certain events in the system which will cause an notification to be sent to you. Most often, these are notifications that you have received credit for a study, or a confirmation that you have signed up for a study. If Unique ID codes are not enabled (see Unique ID codes), your address is also displayed to the researcher when they view who has signed up for their study,, and this is also the address that will be displayed to researchers (if enabled). 9 11 In some cases, depending on how the system is configured, you will be required to provide an address (which will be listed as Address instead of Alternate Address ) and all s to you will go to that address. On some systems, the Alternate Address option is not available. Unique ID Codes If enabled, the system will automatically assign a unique, numeric ID code to you. You should continue to use your normal login ID to log in to the system. The purpose of the ID code is to identify you to researchers in a way that does not reveal your identity or compromise your privacy. If this feature is enabled, you will see this ID code when you view the Human Subjects Policy, when you update your profile, and in confirmations and reminders about your upcoming study sessions. You should bring this ID code with you when you go to studies or when communicating with researchers, as they know you only by your ID code, and not your name.. A brief description of each study will be listed, as well as any special requirements that may restrict your eligibility to participate in the study. 10 12 Figure 5 - Viewing Studies. You may also select a specific date to view studies with available timeslots on that date. To view more information about a study, click on the name of the. Signing Up For Studies. 11 13 Some restrictions are automatically enforced by the system. If the study has certain prerequisites or disqualifiers (studies you must not have participated in to participate in this study), those will be listed, as well as a note about whether you meet those eligibility requirements. Figure 6 - Study Information The study may have other restrictions listed as Subject Restrictions. An example of a Subject Restriction is Left-handed people only. If listed, then the system does not enforce this restriction, but you should only sign up for the study if you meet this restriction. If you sign up for the study and you do not meet the restrictions, you will likely not receive credit for the study,. 12 14 Figure 7 - Study Timeslots may receive an confirmation as well, depending on how your system is configured. You are now signed up for the study.. 13 15 Figure 8 - Sign-Up Cancellation). The system will warn you, but will not block the cancellation.. You may also have an option to view how many credits you have earned for each course. Below that, if you have signed up for any studies, those are listed as well. In the list of studies, you will see information about your credit status. 14 16 Figure 9 - Viewing Your Progress If you failed to appear for a study, it is possible you were assessed a penalty. That will be displayed in your progress, and the penalty (if assessed) will increase the number of credits you must earn. You can also see any comments the researcher left regarding the study and your credit for it. Non-study credit is also listed, when applicable. Non-study credit is usually granted for writing a paper or some other special situation. Reassigning Credits If you belong to multiple courses, and the system is configured to allow it, you may reassign a credit from one course to another. To do this, simple use the Reassign link that appears when you view your progress. The link appears under the course entry for each item in your progress listing. Online Pretests If enabled on your system, you may be asked to take an online pretest before you use the system. Depending on how the pretest was configured, you may have the option to opt out of the entire pretest and/or individual questions. You should realize that declining to participate in the pretest or certain questions may affect your eligibility for some studies, so participation is strongly encouraged. In some cases, you may earn credit for participating in the pretest, and you may even earn credit if you decline to participate in the pretest. If either case holds true, the system will inform you of this before you commence the pretest. 15 17 The pretest may consist of multiple sections. All questions are either multiple-choice or fill-in (free-entry) answer, so it should be rather easy to complete. At the end of the pretest, you will have a chance to review and change any of your responses. After you save all your responses, you may not take the pretest again, so answer the pretest carefully. Figure 10 - Pretest Questions Frequently Asked Questions, may see this information. How do I change the address where notifications from the system are sent? Provide an Alternate address and notifications will be sent there. See the Address Options section of this documentation for more information. In some cases, this option may not be available. I wrote a paper instead of participating in studies. How do I know I have completed my requirements? 16 18. 17 19 RESEARCHER/P.I. DOCUMENTATION Introduction The Experiment Management System is used for the scheduling and management of human subject pools and the studies they participate in. Participants, researchers, principal investigators, and instructors all use the system for their respective purposes. As a researcher, you can set up your studies in the system, schedule the sessions (timeslots) when participants may participate, and grant or revoke credit after the session. All of this is handled through a simple web-based interface that you can access at any time, from any web browser. The system is highly configurable by the administrator, to enforce the rules for the human subject pool exactly as your organization desires. It should be noted that the documentation herein may refer to features that are not enabled on your system. Contact your subject pool administrator, whose contact information appears at the bottom of every page on the system, for more information. System Basics In the system, you create studies. Each study may have a number of timeslots, which are the times when you plan to run the study. Participants sign up for the timeslots by viewing a list of studies and available timeslots. You grant or revoke credit to participants after the session occurs. Principal Investigator Special Note This documentation applies to both researchers and principal investigators (P.I.s), when P.I. support is enabled by the administrator. A P.I. can perform all the same functions on a study as a researcher. This allows a P.I. to operate in an oversight role and monitor the progress of their studies, and step in on behalf of the researcher when necessary. Because the privileges are the same, throughout this documentation, the term researcher can be used interchangeably with principal investigator except where otherwise noted. Participant ID Codes Special Note If enabled by the administrator, the system will identify participants to you only by a unique, system-assigned ID code, and not by their name or address, for privacy reasons. Getting Started The system works best if you use a web browser that is less than 2 years old. It works well with Internet Explorer version 4 and above, Netscape version 4 and above, and Firefox version 1.0 and above. It will work with other web browsers, and with older versions of Internet Explorer and Netscape, however the layout may not be as clean. No functionality will be lost by using an older web browser. Ask your system administrator 18 20 if you need help with installing or using a web browser. This documentation assumes you have a basic knowledge of how to use the web. On this system, it is not necessary to use the Back button. You can always use the toolbar on the top to navigate to anywhere on the site. Logging In Your administrator will provide you with a username and password to login to the site, as well as the URL (web address). When you go to the front page of the site (the login page), you may see a link to request an account. This form is only for participants. Do not use this form to request an account, as participant accounts have an entirely different set of privileges, and the privileges are not appropriate for a researcher. Figure 11 - Login Page Once you login, you may be asked to review and acknowledge your organization s human subject policy. If required by the administrator, you will need to acknowledge this once every 6 months. You will see the Main Menu after you acknowledge the policy. 19 21 Figure 12 -. Retrieving a Lost Password If you have forgotten or do not have your password, and the feature is enabled on the system, then you may choose to have your password ed to you. You will see an option on the mainout from the top toolbar to log out. You are now logged out. It is always a good security practice to close all your web browser windows as well, especially if you are using a computer that is shared by others.. 20 22 Figure 13 - Updating Your Profile It is recommended you provide your phone number and office location, as most human subject committees require that this information be made available to research participants. If you are a researcher, this contact information will be displayed to participants when they view information about the study. If you are a principal investigator, only your name will show (since the researcher is the primary point of contact for a study). You may also choose to receive a daily reminder (by ) with information about all of your study sessions scheduled for the following day. Address Options There are certain events in the system which will cause an notification to be sent to you. Most often, these are notifications that a participant has signed up or cancelled their sign-up for your studies, but there are a few other cases where it may be used as well. The address is also displayed to the participant when they view information about the study, in case they need to contact you with questions. You have two choices for your address. When you update your personal information, you will see a box where you may provide an alternate address. If you provide such an address (this could be a Hotmail account, for instance), this is the address where any notifications will be sent, and this is also the address that will be displayed to other users (including participants in your studies). 21 23 In some cases, depending on how the system is configured, you will be required to provide an address (which will be listed as Address instead of Alternate Address ) and all s to you will go to that address. Working with Studies Most of your time on the system will be spent, not surprisingly, using the study-related features of the system. Be sure to read this section closely, in its entirety, as there are special features and situations you should be aware of. Web-Based (Online) Studies If enabled, you may set up studies that are web-based (online), and these studies may be set up internally in the system (as a survey) or outside the system. The options will vary depending on how your system is configured. There are a few things to note about web-based studies: Once you indicate to the system that the study is web-based, you may not be able to change it so it is no longer web-based (but you can disable or delete the study). So, make this choice carefully Web-based studies are typically setup so there is one timeslot, and that timeslot contains the maximum number of participants you would like to participate, and the last date and time when they can participate (often, this is the end of the term). It is not recommended that you set up multiple timeslots for a web-based studies (it confuses participants), though the system will support it. It is generally assumed that participants will participate in an online study shortly after they sign up. Because of this, the system will expect you to grant credit to them soon after they sign up. If you are creating an online survey within the system, credit will be granted automatically, immediately after the participant completes the survey. Throughout the sign-up process, participants are notified that the study is web-based. If the study is not administered by the system, then participants are not given the URL for the website until they have signed up, to ensure they do complete a sign-up in the system for the study. This restriction applies only to participants, and only to web-based studies administered outside the system. Online survey studies (surveys administered by the system) are discussed in great detail in the section Online Survey Studies, later in this document. Please read it carefully before setting up an online survey study. Studies for Pay You may have a situation where participants are compensated for their participation in the study. They may or may not also receive credit for the study. If the study is not for credit, you may set it up as a pay-only study and specify the compensation amount. If 22 24 participants are compensated and they receive credit, you should set it up as a credit study and indicate additional compensation in the study s information section. Regardless of the type of study, after a participant participates in a study (including studies that are for pay only), you should still go into the system and indicate their participation by granting the credit (or revoking if they did not show). This allows the system to properly enforce certain restrictions on the participant and their studies. Two-Part Studies You may create a two-part study in the system. Often, these are studies involving memory research, where the participant must return a specified number of days after the first session. When creating a study, you may specify the day range for the second part of the study (e.g. 7 to 10 days after the first part). Participants are required to sign up for both sessions at the same time, to reduce the chance they will forget to sign up for the second part. Each part of a two-part study may have a different credit value and duration, but each part must be the same type either both parts are for credit or both parts are for compensation. You may specify that the second part of the study must be scheduled to take place at the exact same time as the first part (on a different date), or at any time on the dates that are the specified number of days after the first part. You should ensure there are enough available timeslots for both parts of the study, or participants later, you will need to manually sign them up for the second part (if you are allowed to do so), or ask the administrator to handle this. If you grant a no-show for the first part of a two-part study, the second part of that participant s sign-up will not be cancelled automatically, but you will be reminded of the situation in case you would like to cancel the second part. The cancellation is not automatic as there are some situations where automatic cancellation is not desirable. Adding a Study Some researchers choose to set up their studies in the system before they have received the proper approvals (usually from their IRB) to run the study. This is supported in the system. You can setup a study but specify that is it not visible to participants. That way, as soon as your approval is received, you can simply make the study visible and everything else is already prepared. You can also post a study and make it visible immediately, if that is appropriate. Some systems will be configured in such a manner that only the administrator can make the study visible to participants, in which case you will need to contact the administrator to do so. 23 25 Figure 14 - Adding a New Study To add a study, choose the Add New Study option from the top toolbar. You will need to fill out a number of fields, which are explained in the following table. All fields must be filled out unless otherwise noted. Field Study Name Short Description (this feature might be disabled on your system) Explanation A short name for the study. This is how the study is identified throughout the system. Most systems are configured so studies show in a random order to participants (choose Your Studies on the toolbar and it will state at the bottom of the resulting page if they are displayed in random order), so there is no advantage in choosing a study name that might put it at the top of an alphabetical list. You should consult with your administrator if there is a naming convention to be followed when naming studies. Study names must be unique, and you will be prevented from adding a study if there is already another study in the system with the same name. This is a short one or two line description of the study. This short description will be displayed to participants when they view the entire list of studies, so you may want to list the most pertinent details here. Forpay studies usually include the compensation information here. This field 24 26 Long Description (this feature might be disabled on your system) Eligibility Requirements Pre-Requisites (this feature might be disabled on your system) is optional. This can be a rather lengthy description about the study, and it will show if a participants clicks on the study to get more information, before they sign up. You may include basic HTML in this area, but please be sure you know what you are doing. If you would like to add a carriage-return (paragraph break), simply type in <p> (without the quotes).this field is optional. If there are any restrictions on who may participate (for instance, only those who are left-handed), list them here. Otherwise, leave the field as-is. If you list any restrictions, these will be displayed on the list of studies, when participants view a list of all available studies. Note the system does not enforce these restrictions, but it is expected a participant will only sign up for a study in which they are qualified, since they would otherwise fail to receive credit. In most cases, you will leave this field as-is and set pretest participation restrictions, which you can do after you add the study. If there are any studies a participant must participate in before participating in your study, choose them here. You may select multiple studies, and on most systems, you hold down the Ctrl key and click the desired studies. The system will handle enforcement of the pre-requisites in a strict or lenient fashion depending on how your system is configured. In strict enforcement mode, the participant must have received credit for the pre-requisite studies. In lenient enforcement mode, the participant must only be scheduled to participate in the prerequisite studies (it is assumed they will go on to complete the pre-requisite studies). You can ask your subject pool administrator how this is configured, if it is of concern. If your system is in lenient enforcement mode, and a participant cancels a necessary pre-requisite for you 25 27 study (they are warned of this situation), and you have configured your study so that the researcher will receive notifications of cancellations or sign-ups, then the researcher will receive notification of the pre-requisite problem and can contact the participant if necessary. Disqualifiers (this feature might be disabled on your system) Course Restrictions Duration Timeslot Usage Limit Preparation Sign-Up Password (this feature might be disabled on your system) If there are any studies a participant must not have participated in, please select them here. You may select multiple studies. The system will handle enforcements of the restriction, during the sign-up process. If you would only like participants enrolled in certain courses to participate in your study, select the eligible courses here. Participants who are not in at least one of the courses you selected will not set the study when they go to view the list of available studies. You may choose No Restrictions if you would like to make the study available to participants in all courses. The amount of time, in minutes, that each study session will take. If you are setting up a 2-part study, then this setting applies to the first part of the study. Depending on how your system is configured, you may see an item that specifies the maximum number of experimental session hours available to this study. This value is set by the administrator, and only the administrator can adjust it. To determine the current session usage for a study, go to the Add A Timeslot page for the study, and the usage will be listed there. Enter any advanced preparation a participant must do here (e.g. do not eat 2 hours before session ). If there are no preparation requirements, leave this field as-is. If you would like to have a special sign-up password for this study, enter it here. This is a password just for this study. Participants must know the password to 26 28 sign up. This is often used in cases where the researcher wants to personally select participants, so the researcher only provides the password to the desired participants. Is this a web-based study? (this feature might be disabled on your system) Should survey participants be identified only by a random, unique ID code? Study URL Credits/Pay If you do not need a sign-up password, leave this field blank. If this is a web-based (online) study, choose the type of online study it is. If you have set up the study on another website, you should note the study is administered outside the system. If you want to set up an online survey study to be administered by the system, select the appropriate option. This only applies to web-based studies administered by the system, and only if participant anonymous ID codes are not already turned on system-wide. If set to Yes, participants are only identified by a unique system-assigned ID code, to protect their privacy. Participants are also notified of this when they start the survey. Once enabled, this setting cannot be changed after participants have taken the survey, as a matter of privacy protection. The URL (web address, usually starting with for your study. This is only required for web-based studies administered outside the system. Enter the number of credits or compensation for the study.-pay studies. If the study has a credit value, you may specify a fractional credit value up to one decimal point of accuracy (e.g. 0.5, 1.5, etc.). If you are setting up a 2-part study, this is the value for the first part of the study. After a study has sign-ups, you may not 27 29 change the credit value of the study. However, the administrator can change the credit value, in certain situations. Is this a 2-part study? Select Yes or No if this is a 2-part study. You can only decide this when creating a study (not when editing it), and this setting may not be changed after the study is created. See Two-Part Studies for more information. Credits/Pay, Part 2 Enter the number of credits or compensation for part 2 of the study, if this is a two-part study (the value is ignored otherwise).pay studies. If the study has a credit value, you may specify a fractional credit value up to one decimal point of accuracy (e.g. 0.5, 1.5, etc.). Part 2 Duration The amount of time, in minutes, that part 2 of the study will take. Part 2 Scheduling Range Specify the number of days (as a range) after part 1 is scheduled, that part 2 should be scheduled. This setting only applies to two-part studies. The range may be the same value (e.g. between 7 and 7 days ) if desired, but must be a whole number. See Two-Part Studies for more information. Part 2 Scheduling Leniency In some cases, you may want to ensure that the participant schedules the second part of the study to take place at exactly the same time (on a different date) as the first part. If so, choose Yes for this option. If there is some flexibility so they can sign up for any time within the Part 2 Scheduling range, choose No for this option. Researcher(s) Select the researcher for this study. Most likely, this is you, and your name will automatically be selected. If you are a researcher, then you may not change who the researcher is (the P.I. for the study, as well as the administrator, can change the 28 30 researcher). Depending on how your system is configured, you may be able to specify multiple researchers for a study. If you specify multiple researchers, each researcher has full control over the study. Principal Investigator (this feature might be disabled on your system) IRB Approval Code IRB Approval Expiration Date Visible to Participants? The pulldown box lists only users who are researchers. Select the Principal Investigator for this study. The person you select will have full access to the study. If you see this option, then you must select a P.I. The pulldown box lists only users who are principal investigators. Enter the IRB approval code here. This field is displayed to the administrator to help them keep track of studies. This field may be required depending on how your system is configured. The date when IRB approval expires. This field may not appear if your system is not configured for it. If it does appear, you must provide a valid expiration date. The system will prevent you from adding new timeslots to take place after this date, and your study will become inactive (not visible to participants) after this date. Only the administrator can change this value, once it has been entered. Select Yes if this study should show up on the list of studies which participants may sign up for. Ensure you have received the necessary approvals to run the study before choosing Yes. A study must be Visible and Active to show up on the list of studies which participants may sign up for. If you select No, the study will not be visible to participants. Some systems are configured such that only the administrator can make a study visible to participants. If that is the case, you should contact the administrator when you are ready to make the study visible to 29 31 Active Study? participants. As a researcher, you can always make a visible study invisible to participants, but you may need the administrator to make it visible again, if so desired. In addition, if you change key items about the study, specifically the name or descriptions, the study will automatically be made invisible to participants, until the administrator reapproves it (if the system is configured this way). The reason for this is that many IRBs approve very specific language for study names and descriptions, so the administrator needs to ensure the study is in proper compliance. Select Yes if this study is in progress. You must select Yes and the study must be Visible if you want the study to show up to participants so they can sign up for it. If a study is Not Visible but is Active, then it does not show up (to participants) on the listing of studies, but it is accessible through other links if the participant has participated in it before and they are viewing their participation history. It will also show up on the study information page (for an individual study) when it is listed as a pre-requisite or disqualifier for a study. Should the Researcher receive an notification when a participant signs up or cancels? The reason to select No is if the study is being kept for historical purposes, but should not show up to participants on the list of studies they may sign up for. Often, this is done so the system can enforce prerequisites, where the inactive study is a prerequisite for an active study. If set to Yes, the researcher for this study will receive an notification whenever a participant signs up, or cancels their signup, for this study. The notification will be sent to an address based on the information the researcher has provided. See the Address Options section of this documentation for more information on how the address is 30 32 determined. If set to Yes, researchers will also receive a notification if the system is in lenient prerequisite enforcement mode and a participant cancels a study that was a prerequisite for the current study. Read the section on Pre-Requisites in this table for more information about this situation. Automatic Credit Granting Can a participant sign up for this study more than once? (this feature might be disabled on your system) Private Comments Participant Sign-Up Deadline (this feature might be disabled on your system) Participant Cancellation Deadline (this feature might be disabled on your system) s are sent to all researchers specified for the study. If set to Yes, timeslots that are more than a specified number of hours old and still in the Awaiting Action state will be changed to a credit grant. The check for timeslots in this situation is made only once per day. If an automatic credit grant is done, you may still change it later if necessary. If you would like to allow participant to sign up (and receive credit) for your study more than once (at different times), choose Yes. Otherwise, choose No. If No is chosen, participants may only sign up for the study more than once if they previously failed to show up for the study. This is an optional area where you may enter any comments or notes about the study, which are only visible to the researchers for this study. Enter the deadline before the study is to occur that the participant may sign up, in whole hours. Enter the deadline before the study is to occur that the participant may cancel their existing sign up, in whole hours. Generally the cancellation deadline should be shorter than the sign-up deadline, so participants can easily cancel an accidental sign-up. Once you have filled out the appropriate information, save it and the system will be updated immediately with the information. Your next step is likely to add timeslots (sessions). See the Working with Timeslots section of this documentation for more information. 31 Sona Systems, Ltd. EXPERIMENT MANAGEMENT SYSTEM Master Documentation Set Sona Systems, Ltd. EXPERIMENT MANAGEMENT SYSTEM Master Documentation Set Version 2.74 Copyright 2010 Sona Systems, Ltd., All Rights Reserved About This Manual This manual covers usage of the system from Sona Systems, Ltd. EXPERIMENT MANAGEMENT SYSTEM Master Documentation Set Sona Systems, Ltd. EXPERIMENT MANAGEMENT SYSTEM Master Documentation Set Version 2.65 Copyright 2006 Sona Systems, Ltd., All Rights Reserved About This Manual This manual covers usage of the system from SONA SYSTEMS RESEARCHER DOCUMENTATION SONA SYSTEMS RESEARCHER DOCUMENTATION Introduction Sona Systems is used for the scheduling and management of research participants and the studies they participate in. Participants, researchers, principal PSYCHOLOGY RESEARCH PARTICIPATION SYSTEM (PRPS) Student User Guide PSYCHOLOGY RESEARCH PARTICIPATION SYSTEM (PRPS) Student User Guide Experiment Management System, Sona Systems Copyright 2007, Psychology Dept. Trent University INTRODUCTION The Psychology Department has STUDENT INSTRUCTIONS FOR SOUTHEAST MISSOURI STATE UNIVERSITY S PSYCHOLOGY RESEARCH WEBSITE () STUDENT INSTRUCTIONS FOR SOUTHEAST MISSOURI STATE UNIVERSITY S PSYCHOLOGY RESEARCH WEBSITE () Introduction The Psychology Research website provides an easy method for you to Melbourne School of Psychological Sciences. Experiment Management System. Research Experience Program Researcher Support Manual 1 Melbourne School of Psychological Sciences Experiment Management System Research Experience Program Researcher Support Manual 2 Introduction... 3 Accessing the EMS... 3 Changing ONLINE EXTERNAL AND SURVEY STUDIES ONLINE EXTERNAL AND SURVEY STUDIES Before reading this document, be sure you are already familiar with the Instructions for using the School of Psychological Sciences Participant Pool available on the Melbourne School of Psychological Sciences. Experiment Management System. Research Experience Program Student Support Manual Melbourne School of Psychological Sciences Experiment Management System Research Experience Program Student Support Manual 2 Table of Contents Introduction... 3 Logging in ONLINE SURVEY STUDIES ONLINE SURVEY STUDIES Web-Based (Online) Experiments If enabled, you may set up experiments that are web-based (online), and these experiments may be set up internally in the system (as a survey) or outside Hendrix College Psychology Department Sona Systems Guide for Researchers Hendrix College Psychology Department Sona Systems Guide for Researchers This document will describe your responsibilities as a researcher and the policies and procedures COURSE INSTRUCTORS RESPONSIBILITIES COURSE INSTRUCTORS RESPONSIBILITIES Psychology Undergraduate Research Experience (PURE) All students in PSY 100, 221, 250, and 251 courses are required to participate in six (6) credits of research. Research Syracuse University Department of Psychology Syracuse University Department of Psychology A Researcher s Guide to SONA and the Department of Psychology Research Participation Pool updated 8/19/2013 Important Dates for the 2013-14 Academic Year Fall Frequently Asked Questions about Participating in the Psychology Course Credit Subject Pool. *** Do I need to register for SONA? Frequently Asked Questions about Participating in the Psychology Course Credit Subject Pool *** Do I need to register for SONA? *** If you have ALREADY REGISTERED on SONA before Aug 29, 2015 please use NASDAQ Web Security Entitlement Installation Guide November 13, 2007 November 13, 2007 Table of Contents: Copyright 2006, The Nasdaq Stock Market, Inc. All rights reserved.... 2 Chapter 1 - Entitlement Overview... 3 Hardware/Software Requirements...3 NASDAQ Workstation...3 The easiest way to think about subject hours is as credits. 1 subject pool credit granted = 1 subject hour used. 4) How do I get subject hours? Frequently Asked Questions for Conducting Research Using the Psychology Course Credit Subject Pool 1) Who can use the Psychology Course Credit Subject Pool? Faculty, post-docs, graduate students and honors Handbook for Psychology Undergraduate Research Experience (PURE) 2015 Spring Edition. Sona Administrators. Department of Psychology Handbook for Psychology Undergraduate Research Experience (PURE) 2015 Spring Edition Sona Administrators Department of Psychology Western Illinois University PURE Handbook 2 Introduction Welcome! In general Mobile Device Access Simple Application Guide Mobile Device Access Simple Application Guide Users can add/manage requests, retrieve passwords, and review password releases/sessions via their mobile device. This manual should be used to help you navigate Instructions for Participating in the Psychology Course Credit Subject Pool Summer 2016 Instructions for Participating in the Psychology Course Credit Subject Pool Summer 2016 Below are instructions about participating in the Psychology Department s Course Credit Subject Pool. Please read Creating an online survey using Sona Systems Creating an online survey using Sona Systems It is important that you read through all of these instructions BEFORE starting to create your online study. 1. Log-in to Sona Systems using your NSID and password. DarwiNet Client Level DarwiNet Client Level Table Of Contents Welcome to the Help area for your online payroll system.... 1 Getting Started... 3 Welcome to the Help area for your online payroll system.... 3 Logging In... 4 Student ANGEL FAQs. General Issues: System Requirements: Student ANGEL FAQs General Issues: What is ANGEL? How do I log in? What is my username and password? How do I activate my account? I forgot my C number/password, what do I do? I registered after the first Health Indicators Advancing Healthy Aging in Your Community. Database Instructions for Managers Health Indicators Advancing Healthy Aging in Your Community Database Instructions for Managers Getting to the Database Website You can access the Health Indicators online database in two different ways. Contents INDEX...61 ECRM...1 ecrm Guide 111011 2011 Blackbaud, Inc. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means, electronic, or mechanical, including photocopying, recording, Richmond Systems. SupportDesk Web Interface User Guide Richmond Systems SupportDesk Web Interface User Guide 1 Contents SUPPORTDESK WEB INTERFACE...3 INTRODUCTION TO THE WEB INTERFACE...3 FEATURES OF THE WEB INTERFACE...3 HELPDESK SPECIALIST LOGIN...4 SEARCHING CUSTOMER PORTAL USER GUIDE FEBRUARY 2007 CUSTOMER PORTAL USER GUIDE FEBRUARY 2007 CONTENTS INTRODUCTION 1. Access to the system 2. Case Management 2.1 Create a case 2.2 Review & Access existing cases 2.3 Update a Case 2.4 Resolve and Close a Unleash the Power of e-learning Unleash the Power of e-learning Version 1.5 November 2011 Edition 2002-2011 Page2 Table of Contents ADMINISTRATOR MENU... 3 USER ACCOUNTS... 4 CREATING USER ACCOUNTS... 4 MODIFYING USER ACCOUNTS... 7 DELETING Welcome to the online research participant sign- up and credit tracking software Welcome to the online research participant sign- up and credit tracking software I WANT TO USE THE SONA- SYSTEM TO RECRUIT PARTICIPANTS OR NON- RESEARCH VOLUNTEERS FOR TRAINING PURPOSES. HOW DO I... WatchDox Administrator's Guide. Application Version 3.7.5 Application Version 3.7.5 Confidentiality This document contains confidential material that is proprietary WatchDox. The information and ideas herein may not be disclosed to any unauthorized individuals Phone Page Web Based Document Delivery Slide 1 This tutorial will introduce you to the Phone Page web-based document delivery system. Click on the top button to continue with the full tutorial or any of the other buttons to view portions of FuseMail- Exchange ControlPanel Admin Guide Feb.27-14 V1.0. Exchange ControlPanel Administration Guide Exchange ControlPanel Administration Guide Table of Contents Top Level Portal Administration... 4 Signing In to Control Panel... 4 Restoring Account Password... 5 Change Account Details... 7 Viewing Account ExDesk s Quick Start Account Configuration Guide ExDesk s Quick Start Account Configuration Guide 1. Some Quick Definitions 2. Account Creation 3. The Decisions 4. Customizing your ExDesk account 5. Creating Admins 6. Creating additional Clients 7. Sharing Using the SimNet Course Manager Using the SimNet Course Manager Using the SimNet Course Manager Contents Overview...3 Requirements...3 Navigation...3 Action Menus...3 Sorting Lists...4 Expanding and Collapsing Sections...4 Instructor Management System (LMS) Guide for Administrators Learning Management System (LMS) Guide for Administrators Contents Core Learning Online LMS Guide for Administrators Overview...2 Section 1: Administrator Permissions...3 Assigning ACT State Testing Online Services Tutorial ACT State Testing Online Services Tutorial Back-up Test Supervisor Version Released July, 2009 2009 by ACT, Inc., All rights reserved. Back-up Test Supervisor Online Profile Form Introduction The Back End User Training Guide End User Training Guide October 2013 2005-2013 ExpenseWire LLC. All rights reserved. 1 expensewire.com Use of this user documentation is subject to the terms and conditions of the applicable End- SnoPAY FREQUENTLY ASKED QUESTIONS SnoPAY FREQUENTLY ASKED QUESTIONS GENERAL QUESTIONS What is SnoPAY? SnoPAY allows you to view and pay your bills anywhere you have Internet access anytime you want. You can pay by transferring money directly Digital Phone Service Web Portal User Guide Digital Phone Service Web Portal User Guide TouchTone provides subscribers an easy-to-use Web-based administrator portal to help manage your IP phone s features and call routing functions. In this document Student Employment Website Employer User Guide Updated March 12, 2008 EMPLOYER USER GUIDE Getting Started...2 Request Log-In Permission...3 Log In...4 My Control Panel...5 Post a New Job...7 Review Student Applications...11 Contact Applicants...12 Hire a Student...13 Manage DEPARTMENT OF PSYCHOLOGY RESEARCH PARTICIPATION POLICIES AND PROCEDURES DEPARTMENT OF PSYCHOLOGY RESEARCH PARTICIPATION POLICIES AND PROCEDURES The Department of Psychology provides opportunities for students to become familiar with the nature of psychological research through Corporate Telephony Toolbar User Guide Corporate Telephony Toolbar User Guide 1 Table of Contents 1 Introduction...6 1.1 About Corporate Telephony Toolbar... 6 1.2 About This Guide... 6 1.3 Accessing The Toolbar... 6 1.4 First Time Login... Frequently Asked Questions Frequently Asked Questions What is an electronic health record? Borgess has transitioned from paper-based medical records to electronic health records (EHRs). An EHR is an electronic version of your medical AT&T Voice DNA User Guide AT&T Voice DNA User Guide Page 1 Table of Contents GET STARTED... 4 Log In... 5 About the User Dashboard... 9 Manage Personal Profile... 15 Manage Messages... 17 View and Use Call Logs... 22 Search Frequently Asked Questions What is ecentral? Who can use ecentral? What can ecentral do? Frequently Asked Questions How do I start using ecentral? What if I forget my User ID? Step-by-step: How to find your User ID Can I change Taleo Enterprise. Taleo Scheduling Center Configuration Guide Taleo Enterprise Taleo Scheduling Center Feature Pack 12B April 26, 2012 Confidential Information and Notices Confidential Information The recipient of this document (hereafter referred to as "the recipient") Paxton Light Online Presentment and Payment FAQ s Paxton Light Online Presentment and Payment FAQ s General What are some of the benefits of receiving my bill electronically? It is convenient, saves time, reduces errors, allows you to receive bills anywhere CyberSource EBC for MIT Clubs Transcript CyberSource EBC for MIT Clubs Transcript... 1 1. INTRODUCTION... 2 2. OVERVIEW... 4 3. NAVIGATING CYBERSOURCE EBC... 7 4. SEARCH FOR AND VIEW TRANSACTIONS... 10 5. VOID TRANSACTIONS... 17 6. MANAGE SOFT Casino Essentials Learning Management System (CELMS) Casino Essentials Learning Management System (CELMS) Administrator Guide March 2010 Casino Essentials, LLC Table of Contents Introduction... 2 Users... 2 Creating New User Accounts... 2 Modifying User User Manual 03/12/2014. A collaborative effort by User Manual 03/12/2014 A USER GUIDE DESIGNED TO HELP CREATE AND MAINTAIN PERSONAL ACCOUNTS IN mynhdoe, THE NH DEPARTMENT OF EDUCATION SINGLE SIGN-ON SYSTEM FOR ACCESSING SECURE APPLICATIONS A collaborative Terminal Four. Content Management System. Moderator Access Terminal Four Content Management System Moderator Access Terminal Four is a content management system that will easily allow users to manage their college web pages at anytime, anywhere. The system Resource Owner. Resource Owner. Resource Owner. Anyone given access Managing Accounts 1 s in Office 365 A account is an object in the Outlook Calendar that represents a room or a piece of equipment. These room resources are typically small conference rooms belonging Hosted Service Documentation and Limited License Agreement GETTING STARTED In your web browser go to the link provided by T&T Software. This is a unique link for your organization. For example. When you successfully MECnet Portal: Using Web Based Email DRAFT User s Manual MECnet Portal: Using Web Based Email MECnet is a division of Merrimack Education Center, a non profit organization DRAFT MECnet Portal Quick Reference Guide To access your mail, use UNFCCC Online Registration System UNFCCC Online Registration System Admitted Observer Organizations (IGOs & NGOs) User Manual Release 1.3.4 June 2015 Page 1 of 43 Table of Contents 1 Overview... 3 1.1 What the System does for you... Manager. User. Guide Meeting Manager Room7 User Guide Copyright 2008, NetSimplicity Software 8 th Edition, MRM 7.8 User Guide June 2008 Written for Meeting Room Manager 7.8 Written by Barry Shanko ActiveX, Internet Explorer, WorkKeys Internet Version Test Administration and User Guide WorkKeys Internet Version Test Administration and User Guide ACT endorses the Code of Fair Testing Practices in Education and the Code of Professional Responsibilities in Educational Measurement, guides Egress Switch Secure Workspace 2.x. Administration Guide Egress Switch Secure Workspace 2.x Administration Guide November 2015 Confidentiality Statement This document contains information confidential and proprietary to Egress Software Technologies. It shall User Guide For Event Registration System (ERS) User Guide For Event Registration System (ERS) Contents CONTENTS... 1 GETTING STARTED GUIDE... 2 ACCESSING ERS... 3 SSO LOGIN... 3 PIN LOGIN... 3 LOGIN NOTICE PAGE... 4 CONFIGURATION OPTIONS... 4 CREATING Merchant Interface Guide. Version 4.0 December 2011 Business Gateway Merchant Interface Guide Version 4.0 December 2011 Business Gateway Merchant Interface Guide Table of Contents About this Guide... 4 Update History... 4 Copyright... 4 Introduction... 5 What is the Merchant Online Sharing User Manual Online Sharing User Manual June 13, 2007 If discrepancies between this document and Online Sharing are discovered, please contact backupfeedback@verizon.net. Copyrights and Proprietary Notices The information U.S. Bank Secure Mail U.S. Bank Secure Mail @ Table of Contents Getting Started 3 Logging into Secure Mail 5 Opening Your Messages 7 Replying to a Message 8 Composing a New Message 8 1750-All Introduction: The use of email Skipjack Merchant User Guide. Quick Guide. (a supplement to the Merchant User Guide) Skipjack Merchant User Guide Quick Guide (a supplement to the Merchant User Guide) COPYRIGHT INFORMATION Evolve Adaptive Technology and Skipjack Financial Services are registered trademarks of the Bradley-Madison Hosted VoIP Phone System. Admin Portal User Guide for. Call Center Administration Hosted VoIP Phone System Admin Portal User Guide for Call Center Administration Contents Table of Figures... 4 1 About this Guide... 6 2 Accessing the Hosted VoIP Phone System Administration Portal... Single Sign-On (SSO) for Applications Single Sign-On (SSO) for Applications User Guide October 2008 1 Contents Introduction... 3 Overview... 3 Extra Information... 3 1. Registering for an SSO Account... 4 SSO Registration... 4 2. Configuring Last Updated July, 2014 MyHealth Patient Portal Last Updated July, 2014 Frequently Asked Questions General What is MyHealth Portal? Is there a fee to use MyHealth Portal? What do I need to use MyHealth Portal? Who do I contact USERS MANUAL FOR OWL A DOCUMENT REPOSITORY SYSTEM USERS MANUAL FOR OWL A DOCUMENT REPOSITORY SYSTEM User Manual Table of Contents Introducing OWL...3 Starting to use Owl...4 The Logging in page...4 Using the browser...6 Folder structure...6 Title Bar...6 SaskTel Hosted Exchange Administrator Guide SaskTel Hosted Exchange Administrator Guide Customer Center Administration Portal At least the first of the following tasks (Accept the Terms of Service) needs to be completed before the company portal Web Mail Classic Web Mail April 14 Web Mail Classic Web Mail Version 2.2 Table of Contents 1 Technical Requirements... 4 2 Accessing your Web Mail... 4 3 Web Mail Features... 5 3.1 Home... 5 3.1.1 Mailbox Summary... 5 3.1.2 Announcements... Student Employment Website Employer User Guide Updated July 17, 2015 EMPLOYER USER GUIDE Getting Started... 2 Request Log-In Permission... 3 Log In... 4 My Control Panel... 5 Post a New Job... 7 Review Student Applications... 11 Contact Applicants... 13 Hire a Student... The Peer Reviewer s Guide to Editorial Manager The Peer Reviewer s Guide to Editorial Manager Registering with EM The Register option is found in the main toolbar. New users simply click on REGISTER. [Note: You may have been proxy registered as a review Table of Contents INTRODUCTION... 2 HOME PAGE... 3. Announcements... 7 Personalize & Change Password... 8 Reminders... 9 SERVICE CATALOG... Table of Contents INTRODUCTION... 2 HOME PAGE... 3 Announcements... 7 Personalize & Change Password... 8 Reminders... 9 SERVICE CATALOG... 11 Raising a Service Request... 12 Edit the Service Request... MathXL Getting Started Guide for Instructors MathXL Getting Started Guide for Instructors Copyright Notice Copyright 2013 by Pearson Education. All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form Volunteers for Salesforce Installation & Configuration Guide Version 3.76 Volunteers for Salesforce Installation & Configuration Guide Version 3.76 July 15, 2015 Djhconsulting.com 1 CONTENTS 1. Overview... 4 2. Installation Instructions... 4 2.1 Requirements Before Upgrading... SUCCESSFACTORS LEARNING USER OVERVIEW REFERENCE GUIDE SUCCESSFACTORS LEARNING USER OVERVIEW REFERENCE GUIDE SuccessFactors, Inc. 4401 Wilson Boulevard, Suite 400 Arlington, VA 22203 Tel: (703) 678-0000 Confidential and Proprietary For Campus Solutions Self Service: Student Quick Reference Guide Campus Solutions Self Service: Student Table of Contents Introduction to Step Sheets... 4 Getting Started in CUNYfirst... 5 Activate My CUNYfirst Account... 6 Log into My CUNYfirst Account... 10 Sign Out Last Revised: 2/16/2010. Microsoft Office SharePoint 2007 User Guide Last Revised: 2/16/2010 Microsoft Office SharePoint 2007 User Guide Table of Contents OVERVIEW...3 Accessing SharePoint Site...4 Document Library...5 Viewing a File...5 Uploading File(s)...8 Check Document Help System. Table of Contents Help System Table of Contents 1 INTRODUCTION 1.1 Features 2 GETTING STARTED! 2.1 Installation 2.2 Registration 2.3 Updates 3 VIEWING RECORDED DATA 3.1 Snapshots 3.2 Programs 3.3 Websites 3.4 Keystrokes Administering Cisco ISE CHAPTER 8 This chapter describes the administrative activities for the Cisco Identity Services Engine (ISE) and how to perform them. The following topics are covered: Logging In, page 8-1 System Time and Institution/Department Administrator Manual ETS Major Field Tests Institution/Department Administrator Manual Updated: December 2010 Table of Contents 1.0 WELCOME... 1 1.1 INTRODUCTION... 1 1.2 COMPUTER HARDWARE AND SOFTWARE REQUIREMENTS... 1 2.0
http://docplayer.net/17479221-Sona-systems-ltd-experiment-management-system-master-documentation-set.html
CC-MAIN-2018-26
refinedweb
9,374
54.63
Instrumenting AWS Lambda Functions Scorekeep uses two AWS Lambda functions. The first is a Node.js function from the lambda branch that generates. Note Running the random-name Lambda function requires the creation of additional resources outside of the Elastic Beanstalk environment. See the readme for more information and instructions: AWS Lambda Integration. The second function, scorekeep-worker, is a Python function that runs independently of the Scorekeep API. When a game ends, the API writes the session ID and game ID to an SQS queue. The worker function reads items from the queue, and calls the Scorekeep API to construct complete records of each game session for storage in Amazon S3. Scorekeep includes AWS CloudFormation templates and scripts to create both functions. Because you need to bundle the X-Ray SDK with the function code, the templates create the functions without any code. When you deploy Scorekeep, a configuration file included in the .ebextensions folder creates a source bundle that includes the SDK, and updates the function code and configuration with the AWS Command Line Interface. Functions Random Name Scorekeep calls the random name function when a user starts a game session without in or specifying a user name.. Lambda passes the function segment to the X-Ray SDK through the function context. When you instrument a Lambda function, you don't use the SDK to create a segment for incoming requests. Lambda provides the segment, and you use the SDK to instrument clients and write subsegments. ![ Service map showing. To write annotations, the function creates a custom subsegment with AWSXRay.captureFunc, and writes annotations in the instrumented function. In Lambda, you can't write annotations directly to the function segment, only to a subsegment that you create.; This function is created automatically when you deploy the sample application to Elastic Beanstalk. The xray branch includes a script to create a blank Lambda function. Configuration files in the .ebextensions folder build the function package with npm install during deployment, and then update the Lambda function with the AWS CLI. Worker The instrumented worker function is provided in its own branch, xray-worker, as it cannot run unless you create the worker function and related resources first. See the branch readme for instructions. The function is triggered by a bundled Amazon CloudWatch Events event every 5 minutes. When it runs, the function pulls an item from an Amazon SQS queue that Scorekeep manages. Each message contains information about a completed game. The worker pulls the game record and documents from other tables that the game record references. For example, the game record in DynamoDB includes a list of moves that were executed during the game. The list does not contain the moves themselves, but rather IDs of moves that are stored in a separate table. Sessions, and states are stored as references as well. This keeps the entries in the game table from being too large, but requires additional calls to get all of the information about the game. The worker dereferences all of these entries and constructs a complete record of the game as a single document in Amazon S3. When you want to do analytics on the data, you can run queries on it directly in Amazon S3 with Amazon Athena without running read-heavy data migrations to get your data out of DynamoDB. ![ Service map showing how the Scorekeep worker function uses Amazon SQS, Amazon S3, and the Scorekeep API. ](images/scorekeep-servicemap-lambdaworker-node.png) The worker function has active tracing enabled in its configuration in AWS Lambda. Unlike the random name function, the worker does not receive a request from an instrumented application, so AWS Lambda doesn't receive a tracing header. With active tracing, Lambda creates the trace ID and makes sampling decisions. The X-Ray SDK for Python is just a few lines at the top of the function that import the SDK and run its patch_all function to patch the AWS SDK for Python (Boto) and HTTclients that it uses to call Amazon SQS and Amazon S3. When the worker calls the Scorekeep API, the SDK adds the tracing header to the request to trace calls through the API. Example _lambda/scorekeep-worker/scorekeep-worker.py -- Worker Lambda Function import os import boto3 import json import requests import time from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all patch_all()queue_url = os.environ['WORKER_QUEUE'] def lambda_handler(event, context): # Create SQS client sqs = boto3.client('sqs') s3client = boto3.client('s3') # Receive message from SQS queue response = sqs.receive_message( QueueUrl=queue_url, AttributeNames=[ 'SentTimestamp' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=0, WaitTimeSeconds=0 ) ...
https://docs.aws.amazon.com/xray/latest/devguide/scorekeep-lambda.html
CC-MAIN-2018-43
refinedweb
767
56.35
How to implement Merge Sort algorithm in Python This Python tutorial helps you to understand what is Merge sort algorithm and how Python implements this algorithm. Algorithm of Merge Sort This algorithm is a sorting algorithm which follows the divide and conquer principle like quicksort. This algorithm divides the given input array into two halves and calls itself recursively until all the elements are divided. Once all the elements are halved or divided, the algorithm starts merging the two sorted halves and this process repeats till all the halves are sorted. Advantages of Merge Sort:- - It can be applied to files of any size. - Running time complexity of Merge sort is O(n log (n)) for best case, average case and worst case. Disadvantages of Merge Sort:- - Merge sort requires more space than other sorting algorithms. - Merge sort is less efficient than other sorting algorithms. Implementation of Merge Sort in Python Let’s try to implement merge sort algorithm in Python with the below code. Source Code: Merge sort in Python def merge_sort(arr, begin, end): if end - begin > 1: middle = (begin + end)//2 merge_sort(arr, begin, middle) merge_sort(arr, middle, end) merge_list(arr, begin, middle, end) def merge_list(arr, begin, middle, end): left = arr[begin:middle] right = arr[middle:end] k = begin i = 0 j = 0 while (begin + i < middle and middle + j < end): if (left[i] <= right[j]): arr[k] = left[i] i = i + 1 else: arr[k] = right[j] j = j + 1 k = k + 1 if begin + i < middle: while k < end: arr[k] = left[i] i = i + 1 k = k + 1 else: while k < end: arr[k] = right[j] j = j + 1 k = k + 1 arr = input('Enter the list of numbers: ').split() arr = [int(x) for x in arr] merge_sort(arr, 0, len(arr)) print('Sorted list: ', end='') print(arr) Output:- Case-1 : Enter the list of numbers: 9 8 7 6 5 4 3 2 1 0 Sorted list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Case-2: Enter the list of numbers: 5 6 1 3 8 9 2 7 4 0 Sorted list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] You can also read,
https://www.codespeedy.com/merge-sort-in-python/
CC-MAIN-2020-40
refinedweb
368
57.23
Book Review: Core Python Applications Programming, 3rd Ed. 65 thatpythonguy writes ." Keep reading for the rest of Ahmed's review. You can purchase Core Python Applications Programming, 3rd ed from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. Re:Why Python? (Score:5, Informative) The Python module library (which is included, like PHP's) is set up in something resembling a sane, logical system. PHP just imports every goddamn thing into the default namespace, and tends to have 5 ways to do everything (none of which work similarly, none of which are compatible, none of which do what you want.) Python typically provides one sane way to do things. I'll grant you that the standard library doesn't include everything PHP does, but there are modules for just about everything and they tend to be painless to install and use. Not to mention, Python is inherently object-oriented, and PHP is not--PHP's OO is bolted-on and wonky. The enforced whitespace is really not that big a deal, especially if you are using a decent editor. I never even have to think about it. Python is quite a well-structured and thought-out language, especially compared to the existential disaster that PHP is. Re: (Score:2, Insightful) The enforced whitespace is really not that big a deal, especially if you are using a decent editor. I never even have to think about it. Perhaps, but it still stupid, unnecessary and potentially problematic. Other than Python being inherently object-oriented, I can't fathom any reason for it over Perl for most tasks. (Not trying to flame/troll, I'm just saying that's my opinion w/25+ years of experience.) Re:Why Python? (Score:4, Interesting). Re: (Score:3). Agreed. Sometimes there are several appropriate tools for a job and programming languages fall into this category based on many factors, so arguing over which is "better" is often silly. On the other hand, there is *no* good reason for white space delimited blocks, other than that's the way Python was designed -- especially when mixing tabs and spaces can give one an aneurysm :-) [ Remember kids that X11 converts tabs to spaces during cut/copy and paste...] All languages have their eccentricities; some are Re: (Score:3) On the other hand, there is *no* good reason for white space delimited blocks, other than that's the way Python was designed -- especially when mixing tabs and spaces can give one an aneurysm :-) [ That was finally fixed, a decade later that it should have been. Sequences of tabs and spaces which create ambiguity between what you see and what the parser understands are now syntax errors. For example, a line indented with tabs followed by a line indented with spaces is an error. Re: (Score:2) On the other hand, there is *no* good reason for white space delimited blocks On the contrary there is a very good reason to have indent delimited blocks sans the visual clutter of braces etc.: Readability counts. especially when mixing tabs and spaces can give one an aneurysm :-) Which is why you should 1.) Follow the advice in the Style Guide (aka PEP 8), "Never mix tabs and spaces ... For new projects, spaces-only are strongly recommended over tabs.." And 2.) set up your editor to make it so. Having Re: (Score:3) that is a really big 'other than', having had a lot of experience in both perl and python I have to say that as much as you can write workable software in either environment, for large applications I would give python the nod, given its better OO model. For other tasks it's pretty much a wash between the two IMHO, although when working in a multi-developer environment python's whitespace constraints Re: (Score:2) ...and as a previous commenter said once you set things up in your editor of choice it's not that big of a deal. Sure, and I'm a heavy Emacs user -- and also LISP programmer, to respond to another post -- (from way back), but I and others routinely (nay, daily) also use several other editors, sometimes on the same code, depending on when and where we have to edit it. We also use several other languages daily - and (w/2 others) maintain about 500k lines of code in about 10 different languages on Solaris/Linux/Windows (none of which are white-space delimited) - so learning and using another language isn't the issue. Re: (Score:2) Re: (Score:3) I used to think like Fahrbot-bot: Enforced whitespace is lame, and I'd like the creative freedom to just bang out one line of Perl when necessary. I now love programming in Python. (And felt this way after a week.) After using Emacs to edit lisp for six years, I've become accustomed to "magically" indenting everything to The Correct Place. The language doesn't require it, but the editor makes it trivial, and it's a huge win for code readability. The parens (and braces in other languages) can fade in import Re: (Score:2) Bloody hell -- double pasting what I meant to edit. I'm very sorry about that. Short version: - I use whitespace conventions to read code more easily, so enforcing one is no different from using Emacs or Eclipse to autoformat everything. I find Python code indentation very similar to Lisp-y indentation. - I miss Perl's easy regex integration. - I miss being able to write one-liners on the command line, or toy implementations in the REPL. In practice, I nearly never need to do this. - List comprehensions (and d Re: (Score:3) The thing with the whitespace is: people don't react well to nannyism. A lot of people bring up the point: "You would have indented it anyway." Exactly. Since you would have indented it anyway, what's the point of enforcing it? There are myriad other rules that code shops follow. Do they all have to be hard-coded in the compiler? Thought experiment: You would have named consonants in upper case anyway. So now the compiler will enforce that. Like Java-style naming (thisIsAFunctionName)? The compiler will enforce Re: (Score:2) Since you would have indented it anyway, what's the point of enforcing it? Let me turn that around: Since you would have indented it anyway, what's the point of braces? Also, when you're pushing enter at the end of the line anyway, what's the point of ; ? Yet, almost no one complains about that missing for some reason.. It seems that perfection is reached not when there is nothing left to add, but when there is nothing left to take away Why have something that isn't needed? Why say the same thing twice? It'll just add to what can go wrong. Inconsistence between bracing and indentation leads to confusion. Confusion leads to anger. Anger leads to hate. Hate leads to suffering. *sad Yoda face* Re: (Score:2) Exactly. It sounds like a really big deal at first, but in practice (and believe me, I am still new to Python) it no longer seems like a big deal. There's so much other good, expressive stuff in well-written python that minor annoyances are less critical, and the "whitespace rules" end up being no different than having an agreed-upon coding style (KNR, etc) in your organization. To be fair, this is likely because I happen to work with a codebase of what looks like very neatly written Python, and also prefer Re: (Score:1) I don't even consider perl to be a first class language it is a nasty hack that got completely out of control. Show me how you define a function call that takes parameters? Never mind I know how it is done in perl, just saying with my 25 years of experience. typing curly braces, begin, end etc is just unnecessary cruft to type simply to satisfy the compiler. Re: (Score:3) The gap Perl left Python to successfully fill mainly involves shipping a good enough standard module library. Keeping small scoped library enhancement work moving with the Python Enhancement Process minor version after version is the true reason for the language's success. CPAN has always been a nightmare of bad version control for non-professional Perl programmers, where it's trivially easy to break things if you try and follow what seems the easiest path for installing things. What Perl should have been Re: (Score:2) it still stupid why? unnecessary you have to delimit code blocks somehow, if it weren't this it would be curly braces or something else potentially problematic But not problematic in practice. Re: (Score:1) Python's OO isn't horrible, but it's not great. There are two types of classes, old-style and new-style. That alone is pretty annoying, since if you're subclassing an old-style class (new classes should, of course, all be new-style), you can't use "super" (not that "super" is well-designed, either). So all Python's included classes have been updated to be new-style, right? No, of course not! Python also ha Re: (Score:3) Python also has no idea of public and private in its classes. The closest it comes is the double-underscore prefix which mangles names, but not to the point that clashes are impossible. Python has the trite saying that "we are all adults" (or something similar), implying that we just shouldn't poke around at things that start with an underscore. However, the lack of public/private essentially means that a large advantage of classes (the ability to keep a stable public API while completely changing how the backend works) is removed: if I create a subclass, since there's no such thing as private, I just have to cross my fingers and hope the superclass author doesn't choose names that clash with mine. Basically, if you're subclassing, you have namespace global to all classes. First of all, python have good support for later adding setters / getters [thegreenplace.net] if needed. And for public API, if you poke around with _variables and __variables in someone else's class, you should EXPECT things to go to hell in the future. _ and __ basically says "this is not meant for you. Any usage is on your head" - it's still there, so you can if you have to. But you shouldn't, and you're making a deliberate choice when you do. That's what the "we're adults" saying points out. You're not a kid, so we won't lo Re: (Score:1) The Python module library (which is included, like PHP's) is set up in something resembling a sane, logical system. This. Coming from a Java background, I had the opportunity to begin and deploying custom applications over a year ago. Since then, I have found the language pragmatic and straight-to-the-point i.e. Pythonic. You should see how Java developer's head spin when I tell them I got a prototyped RESTful Web Service interacting with our legacy system in two days.... TWO DAYS! This is from someone who considers himself a basement coder versus all these J2EE developer types Thank you Flask! Plain and simple, Py Re: (Score:2) Really? What a slacker, I know it does not take two days. I understand though, 5 minutes per day and the rest of the time to surf Slashdot. On day two the java dev is still trying to figure out why his class path is screwed. Re: (Score:1) Re: (Score:2) I am myself familiar with PHP but not Python. What's so good about Python and why should one choose to use it? Let's take for example PHP's comprehensive library that is usable without any downloads and external includes. It's one of the things I love about PHP. Python seems to miss that. That's both good and bad thing. PHP doesn't really have any solid library thinking, it just has random functions thrown together and glued across with some duct tape and spit. Since changes to core language basically alter how the entire language works, it gets really f-ing annoying to maintain your codebase between versions. Meaning you have to rewrite alot of code. The external includes allow you to build compiled projects, which can be delivered without source code. Not sure if you can do something lik Re: (Score:2) >Another thing I don't like about Python is the use of TABS and white space as code block separators. Really? Why?? Just because the creator happened to like that and decided to enforce it on the rest of the world. >I'm sure Python can be great language but the style and some parts of it really put me away from it. It is a great language, for the most part. Here's the weird stuff: You already mentioned tabs. The stock answer is "use an editor designed for Python." Erm, what? Why should I have to use an ed Why an editor? (Score:1) Re: (Score:1) IMHO, this editor thing is very much a non-issue. Every remotely sane (and wishing to retain that state) Python programmer I know of uses spaces, and ONLY spaces. And they make sure to set their editors to treat hitting tab button as a shortcut to insert a set number of spaces. And hitting backspace in front of at least the same amount of spaces to chuck away that same amount of spaces. And if your editor can't handle stuff like tab/spaces replacement, you really should look for alternative editor anyways. Re: (Score:2) Here's the weird stuff: You already mentioned tabs. The stock answer is "use an editor designed for Python." Erm, what? Why should I have to use an editor specifically for one language? For any other language, I can use any editor or none (count gedit as none). Not easily. Writing decent code in any language gets a lot harder if you don't have help with indentation. You'll make mistakes and your coworkers will waste time reindenting it. And when you decide to play with Python in a serious way, you now get to go editor-hunting, downloading, installing and trying them out, figuring out their idiosyncrasies. That's when it pays off to already have invested in an editor which is everywhere and supports everything, like Emacs or Vim. Re: (Score:2) Another thing I don't like about Python is the use of TABS and white space as code block separators. Really? Why?? You don't have to use tabs, you can indent your blocks with any number of spaces as well -- so long as you are consistent within each particular scope. As to why, easy -- it allows Python to reclaim two high value delimiters ({,}) for another function (dictionaries). Re: (Score:2) Eric S. Raymond's answer [linuxjournal.com] As he (and many other comments here explain), most of the "issues" people think Python have (like the significant whitespace part) aren't even noticeable after a short while. And as he points out, it's a language that's well designed and easy to both learn and work with. IMHO, with it's modular approach it's very structured and self-similar. And the duck typing approach makes the modularity even stronger. Re: (Score:1) Python Web Development with Django (Score:2) Re: (Score:2) Core? (Score:2) How is it core Python programming when it's 800 pages? Another case of publishers coming up with one keyword and then using it for every single book they put out. -Unleashed -In 24 hours -In 30 days -Pragmatic Re:Core? (Score:4, Funny) sounds like a good "next step" book (Score:2) Especially this part, "...covering web clients/servers (yes, he writes a small web server!), general web programming (i.e., CGI and WSGI), the Django framework, cloud computing (mostly Google App Engine; GAE), and web services." Re: (Score:1) .... A "Core" of 800+ Pages? (Score:1) I'll wait for the Cliff's Notes version, thank you. Python is pretty decent, I only have two concerns (Score As for white-space delimiting, don't knock it till you try it. Just use a good editor (eg emacs, or other smart editor). Once you get used to it, it's actually very easy on the eyes sans having extra delimiters (curly braces, semicolons, etc.) and Re: (Score Switch/case has always been a bit of a funky construct. LISP's cond was just a general form of if/then/else'. C's switch was pretty tied to C's eq style equality (and was a fun hotspot for compiler writers.) C++'s switch is just an artifact from C that must ignore C++'s attempts to generalize equality. Fortran's computed goto is best described as "interesting." I'm not sure what Python could provide in this space that would be a significant benefit. RAII is also a bit funky. The best garbage collector is oft Re: (Score no Re: (Score non-deterministic/varies by GC algorithm). You might be right. I've never liked Python''s new/init stuff. As for switch/case, either add that, or goto. There *are* use cases where it makes coding cleaner/easier to read--which is one of the underlying points to python, isn't it? A use case, or even infinite use cases, does not mean it is a good idea. Even a use case in which some snippet is objectively easy to read. This is basic language design. If you add a new entity to your language, you and your users have to understand what it is. Take, for example, the target (label) of your proposed goto statement. Is it a marker in a block of text? If so, how does it interact with try/catch/finally? Is it a first class object? Is Re: (Score:3) th Re: (Score:1) 1) A switch in python is implemented using a dictionary 2) RAII is done through context managers ( ) When Python lets me... (Score:2) lets me choose my own block delimiter I will consider it, until then it sucks ditch water and is not worthy of even the most banal task. Re: (Score:2) python lets you use any delimiter you would like, take the following example code for instance. #{ print "hello I am a moron and like to type cruft" #} Re: (Score:1) he wrote a small web server!. That's probably an example of what you can find in the book, it is in the 2nd edition of Core Python Programming.
http://books.slashdot.org/story/12/07/30/1210224/book-review-core-python-applications-programming-3rd-ed
CC-MAIN-2014-15
refinedweb
3,151
71.65
Asked by: Value Type vs Reference Type Question Hi, why instance fields cann't be initialized inside a struct? and one more question System.object is the base class for all types if I declare a value type I mean struct , it must derived from system.object so reference types are accepting null why cann't i initialize null to value type? kindly any one please tell me why instance fields cann't be initialized Example: struct SampleStruct { internal int a; internal double d; } I have few ideas of ->value types are stored in stack and reference type are stored in heap and all. ->Value types has implicitly default constructor(parameter less constructor) ->without using new operator we can access struct (SampleStruct s;).when I access fields which is not initialized compiler is throwing error like "Use of unassigned variable". so if i want to use a field i must initialize the field. my suggestion is the above way let me initialize a field inside a struct if i didn't assign a field and i am trying to using that field you can show error at that time right? Monday, October 15, 2012 5:38 AM - Edited by Alavudeenbatcha Monday, October 15, 2012 5:57 AM All replies Hi Friend, You are right... Base type of the types in .NET is System.Object. In case of ValueTypes, they are inherited from System.ValueType which is inturn inherited from System.Object. You can have a look to these hierarchy with the help of Object Browser in Visual Studio. Now you can make a value type to nullable using the new feature in .net. example: if you declare as int, it cannot hold any null value. But if you declare like ?int, you can have null values too. you may try the same in struct too. more information is available in the link below. Regarding the storage, For all objects there will be a stack entry. For value types, this will be the value itself and for reference type, the address of the heap location where the value is, will be stored there(in stack). -- Thanks Ajith R Nair Monday, October 15, 2012 8:45 AM - Edited by Ajith R Nair Monday, October 15, 2012 8:53 AM Hi, Thanks for your help. still i have two question -> I can understand they have separate kind of value type to handle nullable type (int?). my question is why cann't they fix this with (int) itself. what is the issue with this? -> why can't i declare a default constructor? -> why instance fields cann't be initialized inside a struct? I am very eager to know this answer kindly help me. Monday, October 15, 2012 9:15 AM - Edited by Alavudeenbatcha Monday, October 15, 2012 9:22 AM Friend, Good question..You made me reading lot of blogs and article to confirm. thanks for that first. I would say, please go throught the links below, which will belp you strong in .NET memory management. As a hint i can tell you that,value types are in stack and it must have a value from 0 to its maximum capacity. There is no chance of null/empty there as it is binary. But in reference type, you can have the address in stack where it points to a location which virtually treats as null. -- Thanks Ajith R NairTuesday, October 16, 2012 9:43 AM Thanks a lot dude. still searching and reading blogs to get answers for my question. -> why can't i declare a default constructor? -> why instance fields cann't be initialized inside a struct? Tuesday, October 16, 2012 12:43 PM - Edited by Alavudeenbatcha Tuesday, October 16, 2012 12:44 PM Dear friend... Why you need a default constructor for a valuetype in which the value is already initialized to a default value... Make sence? For struct, yes we can have constructors. Please find the link here : If the question is, how to instantiate a reference type in Struct constructor, please find the code below. class Program { static void Main(string[] args) { Point p = new Point(10, 20); } } public struct Point { public int x, y; public string Name; // Constructor: public Point(int x, int y) { this.x = x; this.y = y; Name = "Ajith Raveendran"; } // Override the ToString method: public override string ToString() { return (String.Format("({0},{1})", x, y)); } }In the above, the name is valuetype(string) and got initialized in constructor. -- Thanks Ajith R Nair Wednesday, October 17, 2012 6:08 AM - Edited by Ajith R Nair Wednesday, October 17, 2012 6:09 AM Hi, kindly check this link dude. one sentence is saying "There are rare situations when the runtime must initialize a value type and is unable to call its default constructor. For example, this can happen when a thread local value type must be allocated and initialized when an unmanaged thread first executes managed code. In this situation, the runtime can't call the type's constructor but still ensures that all members are initialized to zero or null. For this reason, it is recommended that you don't define a parameterless constructor on a value type. In fact, the C# compiler (and others) consider this an error and won't compile the code. This problem is rare, and it never occurs on reference types. There are no restrictions on parameterized constructors for both value types and reference types." I cann't understand the above exactly and I don't know how this unmangaed thread won't affect reference type but it is affecting value type?Wednesday, October 17, 2012 6:16 AM
https://social.msdn.microsoft.com/Forums/en-US/5021eedc-2064-4e1a-b9e7-92c6c33c74ff/value-type-vs-reference-type?forum=winforms
CC-MAIN-2021-04
refinedweb
937
73.37
05/17/2017 - Beta - AIR 26.0.0.107Milind.Jha Welcome to the AIR Runtime and SDK version 26 26. For full details, please see our release notes New and Updated Features Disabling Packaging of Shared Android Applications Starting with AIR 26, packaging of shared applications for Android is disabled. With this change, published applications will always have a captive copy of the runtime included in their installation package irrespective of the target selected (that is, apk or apk-captive-runtime). This change allows us to focus our testing and engineering on captive installation - by far, the most popular option. Moving to WKWebView for StageWebView on iOS Starting AIR 26, For StageWebView on iOS, we now use WKWebView (instead of UIWebView) behind the scene, which uses WebKit engine to render WebViews. For more information on WKWebView, see. This does not impact AS developers directly. However, because of a few known WebKit bugs, there may be some workflow changes in the existing iOS Apps. Do report them on Adobe AIR forums for us to investigate. This change also allows developers to debug StageWebView content in iOS. To enable web inspector on iOS, complete the following steps: 5. After Web Inspector is enabled, connect your device to your desktop machine with a USB cable. The name of your device appears in the Develop menu of Safari. Alternately, developers can use iOS Simulator to take advantage of Web Inspector’s debugging capabilities. Use the same instructions to enable Web Inspector on iOS, from within the iOS Simulator’s Settings app. Apple TV support (Beta Quality) We have made some enhancements to tvOS support, which was introduced in AIR 24 beta channel. For more information, see the Release Notes specific to this feature. DeviceRotation Event Handler for Mobile When a device is rotated, the orientation of the plane defining device screen changes. This change can be depicted in terms of a Rotation Vector, which can be represented by Roll-Pitch-Yaw or Quaternions data. The DeviceRotation event handler is used to fetch this data. One scenario where this data can be useful is to update the viewport of Spherical videos when the device is rotated. This event handler has been introduced in AIR 26, where we have added a new DeviceRotation class which dispatches DeviceRotationEvent based on the activity detected by the device’s motion sensors namely Accelerometer and Gyroscope. DeviceRotation object The user can create an object of DeviceRotation class and can access its properties or register for events on this object. For example: var deviceRotation:DeviceRotation = new DeviceRotation(); DeviceRotation.isSupported returns true if the following conditions are satisfied: - The device has Accelerometer and Gyroscope sensors. - Android devices with versions 4.3(JELLY_BEAN_MR2) and above. - iOS devices with versions 4.0 and above. DeviceRotationEvent.UPDATE is the event, attached to a DeviceRotation object. The event is used in the following scenarios: - When a new listener function is attached using addEventListener. - When the value of the DeviceRotation vector changes, this event is delivered at some device-determined interval. - When the player may have missed a change in the DeviceRotation (for example, if the player is waking up after sleep), this event is delivered. DeviceRotationEvent object When an update event is fired on DeviceRotation object, it is caught as a DeviceRotationEvent object. For example: private function updateHandler(event : DeviceRotationEvent ) : void { } Properties for DeviceRotationEvent are exposed as: - Timestamp - The duration in milliseconds from the application launch time. - Roll, along Y-Axis - Its unit is Number and the value is an angle in degrees. - Pitch, along X-Axis - Its unit is Number and the value is an angle in degrees. - Yaw, along Z-Axis - Its unit is Number and the value is an angle in degrees. - Quaternion - It is an array that represents the quaternion values in [w, x, y, z] format. Enhanced Profile With AIR 26, we are introducing a new stage3D profile “Enhanced” for AIR Mobile. This will be a new constant in Context3DProfile class. Availability of "enhanced" profile indicates the availability of AGAL4. The same profile name can be used in requestContext3D and requestContext3DMatchingProfiles methods of Stage3D. AGAL 4 introduces a new opcode “tld” and new Vertex Sampler register “vs” for fetching texture in a vertex shader. ‘tld’ is similar to 'tex' opcode used in the fragment shader. But unlike ‘tex’ opcode, ‘tld’ requires a level of detail ( LOD ) value for parameter since GPU does not support the automatic calculation of LOD in the vertex shader. Latest version of AGAL is available at Vertex Texture Fetch With the introduction of new Stage3D profile i.e. ‘ENHANCED’, Vertex Texture Fetch is now available in AIR mobile. Texture Data will be available in Vertex Shader using AGAL4 and Enhanced profile. AGAL 4 introduces a new opcode “tld” and new Vertex Sampler register “vs” for fetching texture in the vertex shader. ‘tld’ is similar to 'tex' opcode used in the fragment shader. But unlike ‘tex’ opcode, ‘tld’ requires a level of detail ( LOD ) value as a parameter since GPU does not support the automatic calculation of LOD in the vertex shader. tld usage: tld dst, src, sampler dst: a destination register for the sampler texture pixel src: a register containing texture coordinate where the pixel is sampled and containing a level of detail indication as an index of mipmap to use. The XY components of the src register: a texture coordinate where a texture pixel is sampled. The z component will be used for indicating the side of the cube map texture if the vertex texture is a cube map. The w component of the src register: an index of mipmap to use, with a value range from 0 to n-1 where n is the total number of the mipmaps. The zero index indicates a mipmap in the highest resolution. The fractional part of src.w is how much a selected mipmap would be interpolated with the next level of the mipmap in lower resolution based on the mipmap filter (mipnearest or miplinear) passed in the shader or set from the setSamplerStateAt() API. Mipnearest uses nearest-neighbor mipmap, while miplinear uses linearly filtered mipmapping. vertex sampler ‘vs’ tld vt0, va0, vs0<2d,linear,miplinear> The above example code fetches texture pixels from the texture bound to vertex sampler 0 (vs0) to a vertex temporary register 0 (vt0) with a texture coordinate provided in a vertex attribute register 0 (va0) and a sampler state(< 2d, linear, miplinear >) provided in the vertex shader. The LOD value is provided in va0.w in the example. A total number of vertex samplers available will be 4. The sum of vertex and fragment samplers is restricted to 16. Please note that tld opcode cannot be used inside fragment sampler. To provide a texture for a vertex sampler in the vertex shader, developers should use existing ActionScript API, SetTextureAt(). SetTextureAT(0, texture); The above example code binds 'texture' to the vertex sampler 0 (vs0). Note that this call would set up 'texture' to the fragment sampler in the same index, which is the fragment sampler 0 (fs0), if there is access to fs0 in the fragment shader. A sampler state of the vertex sampler in the vertex shader code could be overridden with the existing AS API, SetSamplerStateAt: SetSamplerStateAt(0, Context3DWrapMode.CLAMP, Context3DTextureFilter.LINEAR, Context3DMipFilter.MIPNEAREST ); Like the SetTextureAt API, the above call would also set up the state of the fragment sampler in the same index, which is the fragment sampler 0 (fs0), if fs0 is used in the fragment shader. Please note, Anisotropic Filtering is not available for texture sampling used in vertex shaders. Vertex Texture Fetch feature is useful for a number of effects like displacement mapping, water simulation, and explosion mapping etc. Known Issues - [iOS] StageWebView not loading local HTML - Using same texture for fragment and vertex sample does not render the object when same sampler state is defined for both fragment and vertex shader (4187904) - [Android] 'Texture decoding failed' error is observed when uploading the texture asynchronously(AIR-4198272) - [iOS] Compilation failed while executing: compile-abc - Class (...) could not be found (AIR-4198225) - [Android] Launcher icons are packaged in incorrect resources location (AIR-4198222) - [iOS] Interfaces don't function when shared between SWFs (AIR-4194914) - [iOS] Starling masking is not working on iOS with Anti-Aliasing ON(AIR-4198229) Fixed Issues - Starling masking is not working on iOS with Anti-Aliasing ON (AIR-4198229) - [Android] StageText not firing ENTER event (AIR-4198260) - [iOS] Unable to launch iPad Pro on iOS Simulator from ADT (AIR-4198314) - [iOS] AudioPlaybackMode.VOICE not working with Bluetooth headset (AIR-4196360) - "Could not generate timestamp: Connection error" is displayed while packaging the AIR application (AIR-4195221, AIR-4198332, AIR-4172255) Authoring for Flash Player 26 and AIR 26 - Update application descriptor namespace to 26 - SWF version should be 37.
https://forums.adobe.com/thread/2316781
CC-MAIN-2017-47
refinedweb
1,466
52.9
Generic LDAP Connector for FIM 2010 R2 Technical Reference Updated: January 9, 2015 The objective of this document is to provide you with the reference information that is required to deploy the Generic LDAP connector for Microsoft® Forefront® Identity Manager (FIM) 2010 R2. When referring to IETF RFCs, this document is using the format (RFC <RFC number>/<section in RFC document>), e.g. (RFC 4512/4.3). You can find more information at (you need to replace 4500 with the correct RFC number). Overview of the Generic LDAP Connector The Generic LDAP connector enables you manage LDAP resources using FIM 2010. The connector is available as a download from the Microsoft Download Center. From a high level perspective, the following features are supported by the current release of the connector: Connected Data Source Requirements In order to manage objects using a FIM 2010. Detecting the LDAP server The Connector relies upon a variety of techniques to detect and identify the LDAP server. The Connector uses the Root DSE to find the vendor name and version and it inspects the schema to find unique objects and attributes known to exist in certain LDAP servers. This data, if found, is used to pre-populate the configuration options in the Connector. Connected Data Source Permissions To perform import and export operations on the objects in the connected directory, the connector account must have sufficient permissions. The connector will need write permissions to be able to export, and read permissions to be able to import. Permission configuration is performed within the management experiences of the target directory itself. Ports and Protocols The connector will use the port number specified in the configuration, which would by default be 389 for LDAP and 636 for LDAPS. For LDAPS, you must use SSL 3.0 or TLS. SSL 2.0 is not supported and cannot be activated. Not supported The following LDAP features are not supported: - LDAP referrals between servers (RFC 4511/4.1.10) Required controls and features The following LDAP controls/features must be available on the LDAP server for the connector to work properly: - 1.3.6.1.4.1.4203.1.5.3 True/False filters If you use a directory where a unique identifier is the anchor the following must also be available (see the Configure Anchors section later in this guide for more information): - 1.3.6.1.4.1.4203.1.5.1 All operational attributes If the directory has more objects than what can fit in one call to the directory, then one of the following options must be supported for the connector to be able to retrieve all objects: Option 1: - 1.2.840.113556.1.4.319 pagedResultsControl Option 2: - 2.16.840.1.113730.3.4.9 VLVControl - 1.2.840.113556.1.4.473 SortControl If both options are enabled in the connector configuration, only pagedResultsControl will be used. The connector tries to detect if the options are present on the server. If the options cannot be detected, a warning will be present on the Global page in the connector’s properties. Not all LDAP servers will present all controls/features they support and even if this warning is present, the connector might work without issues. Delta import Delta import is only available when a support directory has been detected. The following methods are currently used: - LDAP Changelog ( ) - For Novell eDirectory the Connector will use last date/time to get created and updated objects. Novell eDirectory does not provide an equivalent means to retrieve deleted objects. Generic LDAP connector. Deployment Prerequisites The following features must be installed on your FIM 2010 server: - Microsoft .NET 4.0 Framework - FIM Synchronization Service (FIM 2010 R2 hotfix 4.1.3461.0 or later) Connector Installation and Configuration The Generic LDAP connector is available as a downloadable MSI package from Microsoft Download Center. This section provides an overview of the Generic LDAP connector installation and configuration. Connector Installation The Generic LDAP connector is a standalone setup package available from Microsoft Download Center. The connector is installed at the location: %Program Files%\Microsoft Forefront Identity Manager\2010\Synchronization Service\Extensions. Connector Configuration You configure your Generic LDAP connector by using the Management Agent Designer. In the following sections, you will find configuration details for some of the designer’s configuration pages. Create Management Agent On this dialog page, you select the connector type (Generic LDAP (Microsoft)) and you provide the name of your connector: Connectivity On the Connectivity page, you must specify the Host, Port and Binding information. Depending on which Binding is selected, additional information might be supplied in the following sections. The Connection Timeout setting is only used for the first connection to the server when detecting the schema. If Binding is Anonymous, then neither username / password nor certificate are used. For other bindings, enter information either in username / password or select a certificate. If you are using Kerberos to authenticate then also provide the Realm/Domain of the user. The attribute aliases text box is used for attributes defined in the schema with RFC4522 syntax. These cannot be detected during schema detection and the Connector needs help to identify those. For example the following is needed to be entered in the attribute aliases box to correctly identify the userCertificate attribute as a binary attribute: userCertificate;binary The following is an example for how this could look like: Select the “include operational attributes in schema” checkbox to also include attributes created by the server. These include attributes such as when the object was created and last update time. Select “Include extensible attributes in schema” if extensible objects (RFC4512/4.3) are used and will allow any attribute to be used on any object. Selecting this option will make the schema very large so unless the connected directory is using this feature the recommendation is to keep the option unselected. Global Parameters On the Global Parameters page, you configure the DN to the delta change log and additional LDAP features. The page will be pre-populated with the information provided by the LDAP server. The top section shows information provided by the server itself, such as the name of the server. The Connector will also verify that the mandatory controls are present in the Root DSE. If these are not listed, a warning will be presented as in the picture above. Some LDAP directories will not list all features in the Root DSE and it is possible that the Connector will work without issues even if this warning is present. The supported controls checkboxes controls the behavior for certain operations: - With tree delete selected, a hierarchy will be deleted with one LDAP call. With tree delete unselected, the connector will do a recursive delete if needed. - With paged results selected the Connector will do paged imports with the size specified on the run steps. - The VLVControl and SortControl is an alternative to the pagedResultsControl to read data from the LDAP directory. - If all three options (pagedResultsControl, VLVControl, and SortControl) are unselected then the Connector will import all object in one operation, which might fail if it is a large directory. The change log DN is the naming context used by the delta change log, e.g. cn=changelog. You need to specify this value to be able to do delta import. The following is a list of default change log DNs: The password attribute is the name of the attribute the Connector should use to set the password in password change and password set operations. This is by default set to userPassword but can be changed if needed for a particular LDAP system. In the additional partitions list it is possible to add additional namespaces not automatically detected. This can, for example, be used if several servers make up a logical cluster which should all be imported at the same time. Just as Active Directory can have multiple domains in one forest but all domains share one schema, the same can be simulated by entering the additional namespaces in this box. Each namespace can import from different servers and will further be configured on the Configure Partitions and Hierarchies page. Configure Provisioning Hierarchy This page is used to map the DN component, e.g. OU, to the object type which should be provisioned, e.g. organizationalUnit. By configuring provisioning hierarchy you can configure the Connector to automatically create a structure when needed. For example if there is a namespace dc=contoso,dc=com and a new object cn=Joe, ou=Seattle, c=US, dc=contoso, dc=com is provisioned, then the Connector can create a new object of type country for US and an organizationalUnit for Seattle if those are not already present in the directory. Configure Partitions and Hierarchies On the partitions and hierarchies page, select all namespaces with objects you plan to import and export. For each namespace it is also possible to configure connectivity settings which would override the values specified on the Connectivity screen. If these values are left to their default blank value, the information from the Connectivity screen will be used. It is also possible to select which containers and OUs the Connector should import from and export to. Configure Anchors This page does always have a preconfigured value and cannot be changed. If the server vendor and version has been identified then this might be populated with an immutable attribute, e.g. the GUID for an object. If it has not been detected or is known to not have an immutable attribute, then the connector will use dn (distinguished name) as the anchor. The following is a list of LDAP servers and the anchor being used: Object Lifecycle Management This section provides information of aspects which are specific to this Connector or for other reasons are important to know. Delta import The delta watermark in Open LDAP is UTC date/time. For this reason, the clocks between FIM Synchronization Service and the Open LDAP must be synchronized. If not, some entries in the delta change log might be omitted. For Novell eDirectory the delta import will not detect any object deletes. For this reason it is necessary to run a full import periodically to find all deleted objects. Troubleshooting For information on how to enable logging to troubleshoot the connector, see the How to Enable ETW Tracing for FIM 2010 R2 Connectors Release Notes Even if the Connector lists the feature “1.3.6.1.4.1.4203.1.5.2 OC AD Lists” as mandatory on the Global page it is actually not used. See Also
https://technet.microsoft.com/en-us/library/dn510997(v=ws.10).aspx
CC-MAIN-2015-14
refinedweb
1,765
52.6
#1 Members - Reputation: 152 Posted 29 March 2013 - 08:16 AM #2 Crossbones+ - Reputation: 1263 Posted 29 March 2013 - 09:38 AM Translating the grid by the mouse delta when a mouse button is held would be the simplest solution but what specifically are you having trouble with? #3 Members - Reputation: 152 Posted 29 March 2013 - 10:52 AM any example? I move my camera when mouse is pressed, so if I move a grid too, grid will be kinda "stick", like a game's hud. But I want to make it like in this video but infinite. #4 Crossbones+ - Reputation: 1263 Posted 29 March 2013 - 10:58 AM I'm not following what your problem is. Do you have the grid already? If so, you say you move the camera, what is the problem? Translating the camera or grid will achieve the same thing albeit in opposite directions. Or is the problem with rendering the grid? Edited by GeneralQuery, 29 March 2013 - 10:58 AM. #5 Members - Reputation: 152 Posted 29 March 2013 - 11:16 AM It's hard to explain for me... Can you give me a code for infinite grid like in that video? Edited by zgintasz, 29 March 2013 - 11:16 AM. #6 Crossbones+ - Reputation: 2633 Posted 29 March 2013 - 11:35 AM Are you asking how to do it using the tools you use (winforms/opentk?), or are you asking how to structure and code it (store unlimited amount of tiles, load them, show the correct ones at correct offset...)? o3o #7 Members - Reputation: 152 Posted 29 March 2013 - 11:39 AM "structure and code it (store unlimited amount of tiles, load them, show the correct ones at correct offset...)" yes, exactly. Edited by zgintasz, 29 March 2013 - 12:01 PM. #8 Crossbones+ - Reputation: 2633 Posted 29 March 2013 - 12:18 PM Well, first of all you want to store the tiles in chunks. (lets say 32*32 tiles per chunk) This way you can render the chunks that are visible, and you can create the chunks as you scroll further. Maybe even save chunks to disk if theres a problem with memory and theyre far away... As you want infinite terrain, you cant really use a huge grid of those chunks (if you can without using up too much memory, its probably simpler that way. Depends how you define "infinite"). You want a tree like container to store them (quadtree or some kind of hash map container...) so you can store lets say the chunk at 3,6 and the one at 64,12553 and leave the left empty. Then you need a camera, to represent where on top of the terrain you are looking at. From the position of the camera and the size of the screen, you can find a rectangle. Find the chunks inside the rectangle (convert the corners to chunk-coordinates, like chunk 1,1 or chunk 4,5, then get all the chunks in that rectangle...), then render them with the appropriate offset from the screen center (difference between the chunk position and camera position) For starters, i would make a single chunk, and a camera, and make the chunk render in the right spot as you move the camera. o3o #9 Members - Reputation: 152 Posted 30 March 2013 - 07:07 AM I'm trying to make it almost for a week... If somebody already did it, I would be very thankful if that person would share the code. #10 Moderators - Reputation: 8667 Posted 30 March 2013 - 08:15 AM #11 Members - Reputation: 218 Posted 30 March 2013 - 08:41 AM You don't have to draw an infinite grid to make it look like one: #include <GL/glfw.h> int main(){ int x, y, nx, ny, mx, my, lx, ly; int dx = 0; int dy = 0; int w = 512; int h = 512; int cell_w = 32; int cell_h = 32; glfwInit(); glfwOpenWindow(w, h, 8, 8, 8, 8, 0, 0, GLFW_WINDOW); glfwGetMousePos(&lx, &ly); while (!glfwGetKey(GLFW_KEY_ESC)){ glClear(GL_COLOR_BUFFER_BIT); /* Make OpenGL cover full window size */ glfwGetWindowSize(&w, &h); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /* Handle mouse input */ glfwGetMousePos(&mx, &my); if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_LEFT)){ /* Offset the grid by the distance the mouse moved */ dx += mx - lx; dy += my - ly; /* Use the %-operator to jump back */ dx %= cell_w; dy %= cell_h; float r = 10.0f; glRectf(mx-r, my-r, mx+r, my+r); } lx = mx; ly = my; glTranslatef(dx, dy, 0.0f); /* Draw a grid which is a little bigger than the screen */ nx = w/cell_w + 2; ny = h/cell_h + 2; glBegin(GL_LINES); for (x=0; x<nx; x++){ glVertex2f(x*cell_w, -cell_h); glVertex2f(x*cell_w, h+cell_h); } for (y=0; y<ny; y++){ glVertex2f( -cell_w, y*cell_h); glVertex2f(w+cell_w, y*cell_h); } glEnd(); glfwSwapBuffers(); } glfwTerminate(); return 0; } This is deprecated OpenGL. With a fragment shader this would be much easier (but much harder to setup). #12 Members - Reputation: 152 Posted 31 March 2013 - 03:29 AM I knew somebody will ask that question . After a few hours of thinking I finally almost completed it, there is only one issue left: sorry for that terrible quality(I can try to record it again if needed...), but as you can see the grid doesn't follow the screen very well. I'll be very thankful if someone will help me fixing that problem. I've just started learning opengl few weeks ago, so I don't know everything very well... Here is my code(grid class, code is a probably a mess right now, I will tidy it after fixing that problem): public class grid { private MainWindow mainWindow; public float viewWidth; public float viewHeight; public Point cameraPos; public Rectangle glview; public int WidthItems { get; set; } public int HeightItems { get; set; } public Rectangle[] squares; private int totalSquares; private int squareSize = 75; public grid(MainWindow window, int widthitems, int heightitems, int ViewWidth, int ViewHeight) { mainWindow = window; cameraPos = new Point(0, 0); viewWidth = ViewWidth; viewHeight = ViewHeight; WidthItems = (int)(viewHeight / squareSize); HeightItems = (int)(viewWidth / squareSize); totalSquares = WidthItems * HeightItems; squares = new Rectangle[totalSquares]; } public Point CalculateViewCenterPos() { return mainWindow.convertScreenToWorldCoords((0 + glview.Width) / 2, (0 + glview.Height) / 2); } float tempOffsetX = 0f, tempOffsetY = 0f; float offsetX = 0f, offsetY = 0f; public void CameraMoved(float x, float y) { tempOffsetX += x; if (tempOffsetX > squareSize) { offsetX -= squareSize; tempOffsetX = 0; } else if (tempOffsetX < -squareSize) { offsetX += squareSize; tempOffsetX = 0; } tempOffsetY += y; if (tempOffsetY > squareSize) { offsetY -= squareSize; tempOffsetY = 0; } else if (tempOffsetY < -squareSize) { offsetY += squareSize; tempOffsetY = 0; } } public void calculateCoords() { Point topleft = mainWindow.convertScreenToWorldCoords(0, 0); mainWindow.testclickX = topleft.X; mainWindow.testclickY = topleft.Y; int startPosX = topleft.X - squareSize * 2; int startPosY = topleft.Y + squareSize; int id = 0; for (int i = 0; i < WidthItems; i++) { for (int j = 0; j < HeightItems; j++) { squares[id].X = startPosX; squares[id].Y = startPosY; startPosX += squareSize; id++; } startPosX = topleft.X - squareSize * 2; startPosY -= squareSize; } } public void draw() { for (int i = 0; i < totalSquares; i++) { GL.Color3(Color.Green); GL.PushMatrix(); GL.Begin(BeginMode.Lines); GL.Vertex3(squares[i].X + offsetX, squares[i].Y + offsetY, -2); GL.Vertex3(squares[i].X + offsetX, squares[i].Y + squareSize + offsetY, -2); GL.Vertex3(squares[i].X + offsetX, squares[i].Y + offsetY, -2); GL.Vertex3(squares[i].X + squareSize + offsetX, squares[i].Y + offsetY, -2); GL.Vertex3(squares[i].X + squareSize + offsetX, squares[i].Y + squareSize + offsetY, -2); GL.Vertex3(squares[i].X + offsetX, squares[i].Y + squareSize + offsetY, -2); GL.Vertex3(squares[i].X + squareSize + offsetX, squares[i].Y + squareSize + offsetY, -2); GL.Vertex3(squares[i].X + squareSize + offsetX, squares[i].Y + offsetY, -2); GL.End(); GL.PopMatrix(); } } } and MainWindow class: // ... grid maingrid; // ... maingrid.draw(); // ... glviewRatio = (ClientRectangle.Width / zoom) / (ClientRectangle.Height / zoom) * 5; // ... maingrid = new grid(this, 50, 50, ClientRectangle.Width * 5 / zoom, ClientRectangle.Height * 5 / zoom); maingrid.glview = new Rectangle(glview.Location.X, glview.Location.Y, glview.Size.Width, glview.Size.Height); maingrid.calculateCoords(); // ... // (every frame when mouse button is clicked) float x = (MousePosition.X - started_mouse_pos.X) * glviewRatio / zoom; float y = -(MousePosition.Y - started_mouse_pos.Y) * glviewRatio / zoom; maingrid.CameraMoved(x, y); started_mouse_pos.X = MousePosition.X; started_mouse_pos.Y = MousePosition.Y; Edited by zgintasz, 31 March 2013 - 08:17 AM. #13 Members - Reputation: 152 Posted 01 April 2013 - 10:23 AM Finally, found the solution myself . Just changed CameraMoved function: public static void CameraMoved(float x, float y) { tempOffsetX += x; tempOffsetY += y; while (tempOffsetX >= squareSize) { offsetX -= squareSize; tempOffsetX -= squareSize; } while (tempOffsetX <= -squareSize) { offsetX += squareSize; tempOffsetX += squareSize; } while (tempOffsetY >= squareSize) { offsetY -= squareSize; tempOffsetY -= squareSize; } while (tempOffsetY <= -squareSize) { offsetY += squareSize; tempOffsetY += squareSize; } } Edited by zgintasz, 01 April 2013 - 10:30 AM.
http://www.gamedev.net/topic/641026-drawing-infinite-grid/
CC-MAIN-2014-52
refinedweb
1,425
64.3
Webpack processes ES2015 module definitions by default and transforms them into code. It does not transform specific syntax, such as const, though. The resulting code can be problematic especially in the older browsers. To get a better idea of the default transform, consider the example output below ( npm run build -- --devtool false --mode development): dist/main.js ... /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = ((text = "Hello world") => { const element = document.createElement("div"); element.className = "pure-button"; element.innerHTML = text; return element; }); ... The problem can be worked around by processing the code through Babel, a famous JavaScript compiler that supports ES2015+ features and more. It resembles ESLint in that it's built on top of presets and plugins. Presets are collections of plugins, and you can define your own as well. Given sometimes extending existing presets is not enough, modify-babel-preset allows you to go a step further and configure the base preset in a more flexible way.. babel-webpack-plugin is another lesser-known option. Connecting Babel with a project allows you to process webpack configuration through it. To achieve this, name your webpack configuration using the webpack.config.babel.js convention. interpret package enables this, and it supports other compilers install babel-loader babel-core --save-dev As usual, let's define a function for Babel: webpack.parts.js exports.loadJavaScript = ({ include, exclude } = {}) => ({ module: { rules: [ { test: /\.js$/, include, exclude,({ include: PATHS.app }),]); Even though you have Babel installed and set up, you are still missing one bit: Babel configuration. The configuration can be set up using a .babelrc dotfile as then other tooling can use the same. If you try to import files outside of your configuration root directory and then process them through babel-loader, this fails. It's a known issue, and there are workarounds including maintaining .babelrc at a higher level in the project and resolving against Babel presets through require.resolveat webpack configuration. At a minimum, you need babel-preset-env. It's a Babel preset that enables the required plugins based on the optional environment definition you pass to it. Install the preset first: npm install babel-preset-env --save-dev To make Babel aware of the preset, you need to write a .babelrc. Given webpack supports ES2015 modules out of the box, you can tell Babel to skip processing them. Jumping over this step would break webpack's HMR mechanism although the production build would still work. You can also constrain the build output to work only in recent versions of Chrome. Adjust the target definition as you like. As long as you follow browserslist, it should work. Here's a sample configuration: .babelrc { "presets": [ [ "env", { "modules": false, } ] ] } If you execute npm run build -- --devtool false --mode development now and examine dist/main.js, you will see something different based on your .browserslistrc file. Try to include only a definition like IE 8 there, and the code should change accordingly: dist/main.js ... /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = (function () { var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "Hello world"; var element = document.createElement("div"); element.className = "pure-button"; element.innerHTML = text; return element; }); ... Note especially how the function was transformed. You can try out different browser definitions and language features to see how the output changes based on the selection. babel-preset-env allows you to polyfill certain language features for older browsers. For this to work, you should enable its useBuiltIns option ( "useBuiltIns": true) and install babel-polyfill. You have to include it in your project either through an import or an entry ( app: ["babel-polyfill", PATHS.app]). babel-preset-env rewrites the import based on your browser definition and loads only the polyfills that are needed. babel-polyfill pollutes the global scope with objects like Promise. Given this can be problematic for library authors, there's transform-runtime option. It can be enabled as a Babel plugin, and it avoids the problem of globals by rewriting the code6/promise", PATHS.app] }.. Although you can find a lot of them within so-called stage presets, it's a good idea to enable them one by one and even organize them to a preset of their own unless you are working on a throwaway project. If you expect your project to live a long time, it's better to document the features you are using well. Babel isn't the only option although it's the most popular one. Buble by Rich Harris is another compiler worth checking out. There's experimental buble-loader that allows you to use it with webpack. Buble doesn't support ES2015 modules, but that's not a problem as webpack provides that functionality. Perhaps the greatest thing about Babel is that it's possible to extend with plugins: import { Button } from "antd";instead of pointing to the module through an exact path. console.warnto functions that have @deprecateannotation in their comment. console.logcalls with information about invocation context, so it's easier to see where they logged. propTyperelated code from your production build. It also allows component authors to generate code that's wrapped so that setting environment at DefinePlugincan kick in as discussed in the book. It's possible to connect Babel with Node through babel-register or babel-cli. These packages can be handy if you want to execute your code through Babel without using webpack. Babel allows you to control which presets and plugins are used per environment through its env option. You can manage Babel's behavior per build target this way. env checks both NODE_ENV and BABEL_ENV and adds functionality to your build based on that. If BABEL_ENV is set, it overrides any possible NODE_ENV. Consider the example below: .babelrc { ... "env": { "development": { "plugins": [ "annotate-console-log" ] } } } Any shared presets and plugins are available to all targets still. env allows you to specialize your Babel configuration further. It's possible to pass the webpack environment to Babel with a tweak: webpack.config.js module.exports = mode => {process.env.BABEL_ENV = mode;... }; The way envworks is subtle. Consider logging envand make sure it matches your Babel configuration or otherwise the functionality you expect is not applied to your build. more secure option. As a result, you find more premade type definitions for it, and overall, the quality of support should be better. You can use TypeScript with webpack using the following loaders: There's a TypeScript parser for ESLint. It's also possible to lint it through tslint. Flow performs static analysis based on your code and its type annotations. You have to install it as a separate tool and then run it against your code. There's flow-status-webpack-plugin that allows you to run it through webpack during development. If you use React, the React specific Babel preset does most of the work through babel-plugin-syntax-flow. It can strip Flow annotations and convert your code into a format that is possible to transpile further. There's also babel-plugin-typecheck that allows you to perform runtime checks based on your Flow annotations. flow-runtime goes a notch further and provides more functionality. These approaches complement Flow static checker and allow you to catch even more issues. flow-coverage-report shows how much of your code is covered by Flow type annotations. Babel has become an indispensable tool for developers given it bridges the standard with older browsers. Even if you targeted modern browsers, transforming through Babel is an option. To recap: This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack.
https://survivejs.com/webpack/loading/javascript/index.html
CC-MAIN-2018-34
refinedweb
1,296
50.23
Qt 5.10 Drag and drop Hi, I have a problem with my drag and drop system since I built my project with Qt 5.10. My dragged object is still in a dragging state even after the event "dragFinished" is called. So if I do another drag move anywhere in my window it will redo the drag and drop of my object mentioned before. I wonder if I have to use the new DragHandler qml object. If it's a bug coming from Qt 5.10. Or if I did it wrong and it worked fine by some way with Qt 5.9.3. Thanks. - SGaist Lifetime Qt Champion Hi and welcome to devnet, If you can create a minimal compilable example that shows the difference of behaviour between the two Qt versions then you may have found something. You can also check the bug report system. Thank you for answering and welcoming me :) I found this bug that could be related to mine. Here is a minimal code that reproduce my problem: import QtQuick 2.7 import QtQuick.Controls 2.0 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") Rectangle { id: container anchors.fill: parent color: "#fefefe" width: 640 height: 480 DropArea{ id: dropArea anchors.fill: parent onDropped: console.log("drop handler") } MouseArea { id: mouseArea drag.target: dragButton drag.axis: Drag.XAndYAxis anchors.right: parent.right anchors.top: parent.top width: 80 height: 80 Rectangle { id: dragButton color: "#ff0000" anchors.fill: parent Drag.active: mouseArea.drag.active Drag.dragType: Drag.Automatic } } states: [ State { name: "dragState" when: dropArea.containsDrag PropertyChanges { target: container color: "#777777" } } ] } } This post is deleted! @Entrevrak Hello, I think if you use Connexion insted of binding (onDropped ) it will work again. If you meant: Connections { target: dropArea onDropped: { console.log("drop handler") } } No it does not work. @Entrevrak then sorry :/ i don't have auther idea Can you describe what should happen ? On my system with both 5.10 and 5.8 (using qmlscene to run your sample) I have a red square that doesn't move but the onDroppedslot gets called. Sorry I hope my next explanation will be better. The only thing my sample code should do is on drag and drop from the red square to the dropArea. But in Qt 5.10, I can keep doing drag and drop event from anywhere in the window. Here is a gif showing the problem: Ok, so just to be sure: - Drag the red square once - Drop - Drag can now be done from anywhere else Is that correct ? Yes, correct. Then I don’t have that behavior on macOS with my 5.10 build. I’ll check with the official release. You're right I tested out on macOS and the problem wasn't there. I tried on Windows 7 and Windows 10 and both have the problem. Thanks for the info, I did not thought of testing on another OS.
https://forum.qt.io/topic/85880/qt-5-10-drag-and-drop
CC-MAIN-2019-22
refinedweb
489
76.11
I need some kind of validation for POJO Business Objects. Maybe you can give me some ideas so that I find a good solution? I'm looking for a straightforward use of validation. XML validation files are not straightforward in my eyes. I think they are a unnecessary structural interruption between Java files and XML files. The Business Objects will not only be used by web clients but by any client type, which includes Swing-Clients. So I do not accept XML files as easily like web application developers. Besides that I think that validation has to do a lot directly with the Business Objects. Thats another reason why I don't think its good to insulate validation into a XML file. Partly I want to hardcode the validation. I plan to hardcode things like maxValue(shoesize, 20) in the Java code. Other things like enumerations of allowed values I plan to store in the database, for example countryNames and their translations. I'm still not sure what to think about the rule based validation techniques I have seen. It seems to me that it shoots sparrows with cannonballs. My idea of validation needs bidirectional Business Objects (POJOs). First I would validate field and class internal things like maxValue(shoesize, 20). After this I would validate the class on Domain Model scope: shoe.getBrand("Addidas").supportsShoeSize(shoesize) and minSize(brand.getShoes(), 1). Shoe and Brand classes need to be bidirectional for this purpose. Wouldn't that be a straightforward use of validation? Why the need for validation rules or even nested validation rules? Why the need to learn a complex validation API or framework before one can start with using validation? What about bidirectionality which my idea needs? All POJO Business Object relationships would need to be bidirectional because it enablies validation on Domain Model scope. Is this justifiable (or even recommended)? Validation puzzle (4 messages) - Posted by: Hans Schw?bli - Posted on: October 19 2003 07:59 EDT Threaded Messages (4) - simple validation framework by Bruce Goldstein on October 22 2003 17:12 EDT - simple validation framework by Hans Schw?bli on October 23 2003 12:31 EDT - more validation stuff by Bruce Goldstein on October 23 2003 04:00 EDT - more validation stuff by Hans Schw?bli on October 24 2003 09:22 EDT simple validation framework[ Go to top ] I use something similar on my project as follows which is based on three classes: - Posted by: Bruce Goldstein - Posted on: October 22 2003 17:12 EDT - in response to Hans Schw?bli 1. Validation - an interface that provides a validate() method which business objects implement (or it can be implemented in a base business object interface - which I do). 2. ValidaionMessage - a java bean to hold a validation message/warning/error. Consists of the properties: field (name of field), value (bad value), error (name of error), message (optional). 3. ValidationMessages - an object that holds ValidationMessage objects using a hierarchy. Also provides validation methods, i.e. validateDate, etc. The following is an example: // example public interface Validation { ValidationMessages validate(); } public class MyObject implements Validation { private String foo; private int bar; public ValidationMessages validate() { ValidationMessages vms = new ValidationMessages(uniqueName); vms.checkLength("myobject.foo", foo, 60); // max length 60 vms.checkRange("myobject.bar", bar, 1, 30) // between 1 and 30 return vms; } } Points to note: 1. uniqueName allows nesting of validation messages in a hierarchy. 2. no if logic in validate method, this is done within ValidationMessages. 3. Pretty simple to use. Also pretty simple to understand for maintenance. 4. Allows keys (first params) that cold be used with a resource bundle for formatting. Hope this helps! Bruce simple validation framework[ Go to top ] Hi Bruce, - Posted by: Hans Schw?bli - Posted on: October 23 2003 12:31 EDT - in response to Bruce Goldstein your solution looks good. One of my questions was how to implement something like a validation context. A business object may be valid only if a field of a related business object is not null for example. How do you validate that? And what if it can't be navigated to the related business object which field needs to be not null? I mean, what if the navigation (getBusinessObjectX()) is only possible in one way and not in the other? Wouldn't that involve to make all related business objects capable of navigating in both directions because to implement validation context? If you don't know what I mean, I will try to explain it in a better way. My main questing is how to implement validation context. more validation stuff[ Go to top ] Note that I mispoke earlier, I actually use the term Validateable rather than Validation for the interface (no big deal either way). - Posted by: Bruce Goldstein - Posted on: October 23 2003 16:00 EDT - in response to Hans Schw?bli I have methods on the ValidationMessages object to validate a child object or children objects as follows: checkObject(String relationName, Validatable v); checkChildren(String relationName, Collection children); For example: private List users; public ValidationMessages validate() { ValidationMessages vms = new ValidationMessages(); vms.checkChildren("users", users); return vms; } This allows for relationships. As to the validation context, I do use a class called context when I need to share arbitrary data, i.e. I cannot navigate so I need another source to pull from. The context class is pretty much just a slimmed down Map. The issue is mainly that you need to enforce ordering so that you make sure that the data is added to the context before it is needed. Could you explain what you mean by validation context and how it differs from what I wrote above. Thanks! Bruce more validation stuff[ Go to top ] There seems to be something like Rule Based Validation. That would involve to have a Rule class I think. - Posted by: Hans Schw?bli - Posted on: October 24 2003 21:22 EDT - in response to Bruce Goldstein You asked about ValidationContext class. There can be a relationship between Rule and ValidationContext. A ValidationContext could filter rules. That would improve the performance in a GUI if not everything has to be validated every time. Besides this, the ValidationContext could store information whether the context is server or client. The validation context could also depend whether a business object is beeing created, updated or deleted. If a customer needs to be registered, then only its name is necessary, but no shipping address. Only when the customer places an order he needs a shipping address. This can be seen as two different validation contexts. In the first context, he doesn't need a shipping address, in the second context he needs it. I think the validation context has something to do with use cases (UML). Registration without ordering is a use case and registration with ordering is another use case. I'm thinking about how to design a Validation API which is easy to (re)use, easy to learn and which is powerful. Maybe you can post your Validation classes here? Its difficult to understand it only with quotations.
http://www.theserverside.com/discussions/thread.tss?thread_id=21971
CC-MAIN-2017-22
refinedweb
1,179
57.16
C++ is a programming language that includes features of both low-level and high-level programming languages. It allows direct access to memory address locations but also provides advanced. The article is targeted at beginners and intermediate users of C++. However, it can be helpful to anyone who wants to test his knowledge of pointer syntax in C++. Especially, the chapters, "Chapter 11: Deciphering (Long) Pointer Declarations" and "Chapter 9: Dynamic Memory Allocation: Multi-Dimensional Pointers" would be very useful. I have made two major changes since the previous version of the article. C++ syntax is now colour-coded through images and a couple of illustrations have been added to make examples easier to understand. The entire article uses more than a dozen examples to illustrate core concepts. It helps to practice these examples yourself as you read along. The source code is included with the download version. All examples have been tested with GNU C++ compiler v3.4. Please send your suggestions on improving the article and making necessary corrections at varunhome@gmail.com. You can also find some more tips on my webpage. Follow the link labeled 'Technical Articles'. A pointer is a variable which stores the address of another variable. There are two important operators when working with pointers in C++: the address of (&) operator and the value of (*) operator. They have been overloaded in C++ so they may have different uses in different contexts. & * How much storage space does a pointer consume? Use sizeof(ptr) without the '*' operator to determine the memory utilised on your system. Irrespective of datatype or whether the pointer points to a single variable or an array, as a general rule, pointers must use the same amount of memory space. sizeof(ptr) The & operator gives us the address of a variable and * gives us the value of a variable at a specified address. For example: Here is a simple example of using pointers in C++: A diagram illustrating the relationships between the different variables in the above example should help clarify the concepts: Just as we have arrays of variables, so also we have arrays of pointers. For example, int *p[5]; declares an array of five pointers to integer variables. More details on pointer syntax are provided in "Chapter 11: Deciphering (Long) Pointer Declarations". Each pointer in turn stores the memory address of an integer on its own. Each pointer may even store the base address of an array of integers. Let us understand the use of arrays of pointers with an example. In the above example, we did not allocate memory for the data pointed to by the pointer ptr[2]. This is because it points to the array ch3 for which memory has already been allocated. However, in some cases, we may want a pointer variable to point to an unnamed memory location. We achieve this through the use of new and delete operators. Here is a simple example followed by a more complex example: ptr[2] ch3 new delete One thing to remember is the use of dynamic memory allocation in classes. When we create a class in C++, the compiler automatically creates four member functions, even if we don't create them: classname& classname () classname& classname (classname&) = classname& operator=(classname&) ~classname () When we make a copy of a class containing a pointer, the pointer gets copied but the data that the pointer points to does not get copied. Therefore, always remember to make a copy of the data using dynamic memory allocation and store it in the pointer of the class copy. When overloading the copy constructor, you should therefore preferably overload the assignment operator also. Array and pointer syntax is generally inter-changeable in C++. The next example reinforces these linkages covered briefly in the previous example. Just as we can have multi(2, 3, 4, .....)-dimensional variables, we can have multi-dimensional pointers also. A simple example is shown below: You will find the above syntax used often in passing parameters to functions and accepting return values. Let us understand this through an example: The usage of the above code can be easily understood from the following diagram. You should try and develop a diagram of your own to understand the example in Chapter 9: Dynamic Memory Allocation: Multi-Dimensional Pointers. I assume that you are aware of these keywords which are used in the next example: exit (int) break continue return Here is another more complicated example of dynamic memory allocation. We will allocate space for a two dimensional array of size [3][4] and manipulate it with a pointer. The above example when used with three dimensional pointers to create an array of size [2][3][4], looks as follows: When dynamic memory allocation fails, an exception is thrown. You would normally want to catch the exception and halt program execution. However before exceptions were used in C++ (or if you use the nothrow version of new), whenever dynamic allocation failed, the pointer stored a NULL value. In that case the following check would be used: NULL int *ptr = new int; if(!ptr) { //error } Just as we have pointers to the basic datatypes, we have pointers to classes and structures also. They are used in exactly the same way as pointers to the basic datatypes. That is why we will not discuss how to use them here. We will instead concentrate on the use of function pointers. Function pointers are pointers to functions. They are used when we do not know at the time of compiling a program the function we will need to call. They are often used in GUI libraries to execute a specified function when a particular signal (input) is received. The rules defining function pointers are the same as with other pointers. However, the declaration looks very different. This chapter explains rules to follow for deciphering pointer declarations. These are particularly important for function pointers. () [ ] Here are a few examples to make the process clear: Let us see an example of function pointers. Let us conclude with the same example implemented with a typedef declaration. typedef 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 double ***ctrlpoints=NULL; const int n=20; ctrlpoints = new double **[n]; for( int i=0;i<n;i++ ){ *(ctrlpoints+i) = new double *[n]; for( int j=0;j<n;j++ ){ *(*(ctrlpoints+i)+j) = new double[3]; } } double ***ctrlpoints=NULL; const int n=20; ctrlpoints = new double **[n]; for( int i=0;i<n;i++ ){ ctrlpoints[i] = new double *[n]; for( int j=0;j<n;j++ ){ ctrlpoints[i][j] = new double[3]; } } if (ctrlpoints){ delete[] ctrlpoints; ctrlpoints=NULL; } #include <conio.h> #include <iostream> #include <vector> #include <ctime> const int numRows = 400; const int numCols = 400; const int numPlanes = 400; class Timer { private: std::clock_t beg; std::clock_t dif; public: void start() { beg = std::clock(); } std::clock_t stop() { dif = std::clock() - beg; return dif; } }; void testVector() { using std::vector; typedef vector<int> Row; typedef vector<Row> Plane; typedef vector< Plane> Array3d; Array3d array(numPlanes, Plane(numCols, Row(numRows))); //Test filling the vector using [] Timer timer; timer.start(); for (int x=0; x<numRows; ++x) for (int y=0; y<numCols; ++y) for (int z=0; z<numPlanes; ++z) array[x][y][z] = 5; std::cout << "\nVector fill time using []: " << timer.stop(); //Test filling the vector using iterators: timer.start(); Array3d::iterator arrayIt = array.begin(); for (int x=0; x<numRows; ++x) { Plane::iterator planeIt = (*arrayIt).begin(); for (int y=0; y<numCols; ++y) { Row::iterator rowIt = (*planeIt).begin(); for (int z=0; z<numPlanes; ++z) { *(rowIt++) = 5; } ++planeIt; } ++arrayIt; } std::cout << "\nVector fill time using iterators: " << timer.stop(); } void testArray() { try { int counter(0), colsAllocated(0), planesAllocated(0); int*** array; try { array = new int**[numPlanes]; for (int plane=0; plane<numPlanes; ++plane, ++planesAllocated) { array[plane] = new int*[numCols]; for (int col=0; col<numCols; ++col, ++colsAllocated) { array[plane][col] = new int[numRows]; for (int row=0; row<numRows; ++row) { array[plane][col][row] = counter++; } } } } catch (...) { for (int i=0; i<planesAllocated; ++i) { for (int j=0; j<colsAllocated; ++j) { delete[] array[i][j]; } delete[] array[i]; } delete[] array; throw ; //To bypass second deallocation } //The array has been allocated, now test the speed: Timer timer; timer.start(); for (int x=0; x<numRows; ++x) for (int y=0; y<numRows; ++y) for (int z=0; z<numPlanes; ++z) array[x][y][z] = 5; std::cout << "\nArray fill time using []: " < timer.stop(); //Test filling the array using pointers timer.start(); int *** arrayIt = array; for (int x=0; x<numRows; ++x) { int ** colIt = *arrayIt; for (int y=0; y<numCols; ++y) { int * rowIt = *colIt; for (int z=0; z<numPlanes; ++z) { *(rowIt++) = 5; } ++colIt; } ++arrayIt; } std::cout << "\nArray fill time using pointers: " << timer.stop(); //Now free the memory used by the array for (int plane=0; plane<numPlanes; ++plane) { for (int col=0; col<numCols; ++col) { delete[] array[plane][col]; //delete the rows } delete[] array[plane]; //delete the collumns } delete[] array; //delete the array } catch (...) { std::cout << "Allocation error - press any key to exit"; getch(); } } int main() { //Old code adapted to show speed difference between safe //arrays and vector usage for (int x=0; x<4; ++x) { testArray(); testVector(); std::cout << "\n"; } std::cout << "\nPress any key to quit"; getch(); } General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/11560/Pointers-Usage-in-C-Beginners-to-Advanced?msg=3902205
CC-MAIN-2015-11
refinedweb
1,608
52.6
Btw, there is a way we can reward you for the awesome job you do? A paypal account maybe? iamntz wrote:Man, you are awesome! Thanks a lot, now looks beautiful! Btw, there is a way we can reward you for the awesome job you do? A paypal account maybe? vitaLee wrote:@facelessuser is that a custom color scheme you're using? care to share? open": "(^if|foreach|while.+:$)", "close": "(^endif|endforeach|endwhile;$)", "open": "(^if.+:$)", "close": "(^endif;$)", iamntz wrote:Ok, so, as i said, me dumb I'm trying to make ST to also highlight if/endif foreach/endforeach and so on in php. What i have now (after like 50 different combinations or so) is this: - Code: Select all open": "(^if|foreach|while.+:$)", "close": "(^endif|endforeach|endwhile;$)", But will not match correctly what i need (php have two ways of doing blocks; one is with if/endif and the other is with curly braces) However, if i'll do only this: - Code: Select all "open": "(^if.+:$)", "close": "(^endif;$)", works good...ish. Because will make things red (which is an error) when i focus inside of the condition: While things are peachy when i'm inside of the block: What do i do wrong? Thanks! { }, def compare(name, first, second, bfr): return "end" + bfr[first.begin:first.end] == bfr[second.begin:second.end] def compare(name, first, second, bfr): opening = bfr[first.begin:first.end] closing = bfr[second.begin:second.end] match = False if opening.startswith("while"): if closing.startswith("endwhile"): match = True else: match = "end" + bfr[first.begin:first.end] == bfr[second.begin:second.end] return match vitaLee wrote). "open": "^\\s*(if|foreach|while).*:$", "close": "^\\s*(endif|endforeach|endwhile;$)" Return to Plugin Announcements Users browsing this forum: No registered users and 7 guests
http://www.sublimetext.com/forum/viewtopic.php?p=38913
CC-MAIN-2015-14
refinedweb
294
60.41
ExOLEDB Architecture Topic Last Modified: 2006-06-12 Microsoft®® Data Objects (ADO), and Collaboration Data Objects (CDO). The following illustration shows the relationship between ADO, CDO, OLE DB, the ExOLEDB provider, and the Exchange store. The ExOLEDB provider is a server-side component, and is therefore used only to access public stores and mailbox stores that reside on the same server. You can, however, access data on the server remotely by wrapping functionality into Component Object Model (COM) components, which can be utilized by ASP and other Web applications. The ExOLEDB provider is also ideal for use in COM+ components and Exchange store event and workflow sinks that run on the server. To access remote public stores and mailbox stores, use the WebDAV protocol, MAPI, or CDO 1.2.1. Exchange registers this provider for the file URL namespace with the OLE DB 2.5 root binder on the local server. The root binder eliminates the requirement to explicitly specify an ADO Connection object when accessing items through OLE DB. This means that you can bind an ADO Record object directly to an item only by using a file-type URL. To bind to items by using The HTTP: URL Scheme through the ExOLEDB provider, you must specify the ExOLEDB provider binder with an ADO Connection object (Connection.Provider = "ExOLEDB.DataSource"). In most cases, it is best that you specify this provider explicitly. The following section summarizes how specific ADO objects can be used effectively in Exchange store applications:
https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2007/aa579147(v=exchg.80)?redirectedfrom=MSDN
CC-MAIN-2019-47
refinedweb
249
52.7
Boolean Parenthesization problem Given a boolean expression, a string with True or False as operands and between each pair of operand, there is boolean operator (and &, or | and xor ^). Find number of ways in which this Boolean expression can be parenthesized so that expression evaluates to True. This is known as Boolean Parenthesization problem. To understand problem better, let’s take some examples Expression : T ^ F & T Two ways : ((T ^ F) & T) and (T ^ (F & T)) T | T & F ^ T Four ways : ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T)) Boolean Parenthesization problem : Line of thoughts What will be the most trivial Boolean expression? Of course, an expression with only one Boolean value T or Boolean value F. How many ways can this expression be parenthesized so that expression evaluates to True ? Apparently, there is only one way. For Boolean value T, there is one way, (T); whereas for F, there no way we can parenthesize to evaluates True. An expression can evaluate to either True or False value. Let’s say, T(i,j) is number of ways expression from i to j can be parenthesized so that it evaluates to True. Similarly, F(i,j) is number of ways expression evaluates to False. With base case, only one value either T or F is there, hence i=j, hence following equations hold true T(i,i) = 1 if operand is T 0 if operand is F F(i,i) = 0 if operand is T 1 if operand is F How to calculate T(i, j) for expression with more than one values and operators between them? This is something familiar to matrix chain multiplication problem. We will put parenthesis at all possible position and count how many ways these two resultant expressions hold True. Once we have count for each expression, we can combine count based on operator between split expression. For expression from index i to index j, find k such that i<k<j, and find number of ways expressions from i to k and k+1 to j evaluates to True. Interesting, once these numbers are determined, number of ways for expression i to j can be calculated based on operator between expression i to k and k+1 to j. When Boolean operator is & (AND) When can expression (i,j) be True if expression is of form Expression(i, k) & Expression(k+1, j)? Only if Expression(i,k) and Expression(k+1,j) are both True. Hence, for any k, expression can be True in T(i,k) * T(k+1, j) where T(i,k) is number of ways Expression(i,k) is True and T(k+1, j) is number of ways Expression(j+1, j) is True. For all possible values of k, expression becomes T(i,j) = Summation ( T(i,k) * T(k+1,j)) for all k such that i < k < j How about expression (i,j) being evaluates to False? Simple enough, one of the two expression should evaluate to False. If Total(i,j) represents total number of ways an expression can be parenthesized irrespective of out being True or False, then Total(i,j) = Total(i,k) * Total(k+1, j) or Total(i,j) = T(i,j) + F(i,j) If we take out number of ways an expression can parenthesized as True from Total, it gives number of ways it can be evaluates False. Hence, below equation F(i,j) = Sum ( Total (i,j) - T(i,k)* T(k+1)) for all k for i< k< j or F(i,j) = Sum (Total(i,k) * Total(k+1, j) - T(i,k)* T(k+1) ) When Boolean operator | (OR) In case, operator is OR, then, whole expression is True is any one of the expressions is True. How many ways both Exp(i,k) and Exp(k+1, j) be False. Following the same logic from AND operator True, it can be derived that F(i,j) = Summation (F(i,k)* F(k+1,j)) for all i<k<j Overall expression is True when both sub-expressions are not False. Hence. T(i,j) = sum ( Total(i,j) - F(i,k)* F(k+1,j)) for k such i<k In the same vein, T(i,j) and F(i,j) when operand is xor will be T(i,j) = sum(T(i,k)*F(k+1,j) + F(i,k)* T(k+1,j)) for k such i<k To find solution to Boolean parenthesis problem, find is T(1,N). Implementation : Boolean parenthesization problem package com.company; /** * Created by sangar on 31.12.17. */ public class BooleanParenthesis { public static int calculateNumberOfWays(String operators, String operands){ int numOperands = operands.length(); int[][] F = new int[numOperands][numOperands]; int[][] T = new int [numOperands][numOperands]; for (int i=0; i<numOperands; i++){ System.out.println(operands.charAt(i)); F[i][i] = (operands.charAt(i) == 'F')? 1: 0; T[i][i] = (operands.charAt(i) == 'T')? 1: 0; System.out.println(T[i][i]); } for (int L=1; L<numOperands; L++) { for (int i=0; i<numOperands-L; ++i){ int j = i+L; T[i][j] = F[i][j] = 0; for (int k=i; k<j; k++){ int totalIK = T[i][k] + F[i][k]; int totalKJ = T[k+1][j] + F[k+1][j]; if (operators.charAt(k) == '&') { T[i][j] += T[i][k]*T[k+1][j]; F[i][j] += (totalIK *totalKJ - T[i][k]*T[k+1][j]); } if (operators.charAt(k) == '|'){ F[i][j] += F[i][k]*F[k+1][j]; T[i][j] += (totalIK*totalKJ - F[i][k]*F[k+1][j]); } if (operators.charAt(k) == '^'){ T[i][j] += F[i][k]*T[k+1][j] + T[i][k]*F[k+1][j]; F[i][j] += T[i][k]*T[k+1][j] + F[i][k]*F[k+1][j]; } } } } for(int i=0; i<numOperands; i++){ for(int j=0; j<numOperands; j++){ System.out.println("(" + i + "," + j + ") :" + T[i][j]); } } return T[0][numOperands-1]; } public static void main(String[] args) { String operands = "TTFT"; String operators = "|&^"; System.out.println("Number of ways to parenthisize expression : " + calculateNumberOfWays(operators, operands)); } } Complexity of dynamic programming approach to find ways to parenthesize a Boolean expression to evaluate it to True is O(n3). and space complexity is O(n2) . Please share if there is something missing or wrong. If you want to contribute to algorithms and me and share your knowledge with thousands of learners across world, please contact us..
https://algorithmsandme.com/tag/boolean-parenthesization/
CC-MAIN-2020-05
refinedweb
1,096
60.45
As we already know that Dotty is the new Scala version and will obviously be more stronger and powerful then Scala 2. In Scala-2, pattern matching is only applicable to the objects and not on the types. But with the new Scala compiler i.e Dotty, it is possible to apply matching on Types also. For example, type Container[C] = C match { case String => Char case Array[Int] => Int case Iterable[Int] => Int } The Container is a type which gets reduce to further corresponding types as under – Container[String] -> Char Container[Array[Int]]-> Int, and Container[List[Double]] -> Double Match types are a very powerful and also provides support for recursive definition. See the example below – import scala.compiletime.ops.int.% type HCF[A <: Int, B <: Int] <: Int = B match { case 0 => A case _ => HCF[B, A % B] } Here the HCF type is of a Singleton Type. Singleton Type are the types which are instantiated with exactly one value. So you have a HCF type and then create its object as – val hcf: HCF[10, 20] = 10 Here we have defined a value which carries the highest common factor of two numbers 10 & 20. But if you try to change the value to something else, you should see the compilation error. The below statement will lead to compilation error- val hcf: HCF[10, 20] = 11 // you should see error.. val hcf: HCF[10, 20] = 11 | ^^ | Found: (11 : Int) | Required: (10 : Int) This is because value hcf is of type 10 which is a singleton type and thus exactly have one value. Match types can also detect infinite loop if it is defined as an endless recursion. The compiler internally detects it by stack overflows. If there is a stack overflow, it will be taken as a compile-time error. The example is available on the GitHub. How compiler reduces the Match Type: Semantically match type reduction is same as it is done in Match expressions. S match {P1 => T1 ... Pn => Tn} which can be further reduced to something as (similar with the pattern matching done in Scala 2): s: S match {_: P1 => T1 ... _: Pn => Tn} And it gets reduced to Ti only when S is of type Pi. The algorithm which compiler implements for match type reduction is as: For every Pi – - if Sis lower bound of Pii.e. S <: Pi, then reduce to Pi. - else, check that no value sof type Sshould be of type Pii.e Sand Piare disjoint. - And if the check fails, then follow the same procedure for (Pi+1). References:
https://blog.knoldus.com/match-types-in-dotty/
CC-MAIN-2021-31
refinedweb
429
71.85
25 April 2012 11:32 [Source: ICIS news] (adds details, analyst comments in paragraphs 7-10) ?xml:namespace> It said that chemical margins troughed this year because of “the global excess supply and global demand weakness”, the company said in a statement. SCG’s overall earnings before interest, tax, depreciation and amortisation (EBITDA) declined by 24% year on year to Bt10.3bn, despite an 11% growth in sales to Bt102.9bn, it said. Its overall sales were boosted by higher volume growth and higher product prices in most business units, the firm added. For its chemicals business, net profit in the March quarter slumped 74% year on year to Bt1.24bn, with EBITDA down by 82% at Bt894m, SCG said. Sales from its chemicals unit – the company’s largest revenue generator in the first quarter – rose by 9% year on year to Bt52.9bn, it said. It said that its average ethylene price stood at $1,251/tonne in the first quarter of 2012, up $12/tonne on a year-on-year basis. For propylene, its average price fell by $98/tonne year on year to $1,281/tonne over the same period, citing weak demand for downstream polypropylene (PP) products, the company said. SCG’s combined sales volume of polyethylene (PE) and PP rose by 9% year on year to 433,000 tonnes in the first quarter of this year, SCG said. “Earnings of SCG should recover in the second quarter of this year as reflected in improving chemical spreads in April while demand of cement remains healthy,” said Naphat Chantaraserekul, a Thailand-bsaed analyst with DBS Vickers Securities. ($1 = Bt30
http://www.icis.com/Articles/2012/04/25/9553355/thai-scg-q1-net-profit-falls-35-on-weak-chemical-margins.html
CC-MAIN-2014-35
refinedweb
272
70.13
The second configuration at the core of Java 2 Micro Edition (J2ME) is the Connected Device Configuration, or CDC for short.The CDC is a superset of the Connected Limited Device Configuration (CLDC). It provides a much more conventional Java 2 runtime environment.: Note that, just like the CLDC, the CDC does not define any user interface classes or how applications are loaded and activated: these are left for the profiles to define. subset of J2SE 1.3 included in the CDC consists of classes from these packages:. Since the CDC is a superset of the CLDC, it includes the Generic Connection Framework (GCF). Unlike the CLDC, however, the CDC also requires GCF support for two specific connection types: files and datagrams. This makes sense because the CDC includes the file classes from the java.io package and the datagram classes from the java.net package. It is therefore straightforward for the device manufacturer to write GCF implementation classes that simply map GCF requests (using the file or datagram protocol at the start of a URL) into their java.io and java.net equivalents. Here is an example of opening a file for writing using the GCF: import java.io.*; import javax.microedition.io.*; try { String url = "file:/logs/mylog.txt"; OutputConnection conn = (OutputConnection) Connector.open( url, Connector.WRITE ); OutputStream out = conn.openOutputStream(); ..... // write to the output stream out.close(); conn.close(); } catch( IOException e ){ // handle error } Datagram support is a bit more complex, but quite similar. Why not just use the java.io and java.net classes directly? The GCF provides a consistent I/O model that works across all J2ME platforms that support the required protocols. If you don't need interoperability with J2SE, use the GCF whenever possible to open your I/O connections. Like the CLDC, the CDC is by itself a limited programming platform. Again, because it does not define any user interface classes or implement any I/O models, about all you can do for output is write to the System.out stream, which may or may not be captured to a console or file. The extra classes defined by one or more J2ME profiles are really required to write interactive applications. Sun has a reference implementation of the CDC hosted on Linux available for download from its website. See Sun's main CDC page for links to it and to the CDC specification. Next: The Importance of the Mobile Information Device Profile (MIDP) User groups have permission to reprint this article for free as described on the copyrights page.
http://www.ericgiguere.com/articles/understanding-the-cdc.html
crawl-002
refinedweb
426
58.38
Important: Please read the Qt Code of Conduct - How to make use of internationalization? This is main.cpp file #include <QGuiApplication> #include <QtGui> #include <QQuickView> #include <QTranslator> #include <QQmlContext> #include <QQmlProperty> #include <QCoreApplication> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQuickView view; QTranslator *translator1=new QTranslator(); translator1->load("xyz.ts"); QCoreApplication::installTranslator(translator1); view.setSource(QUrl::fromLocalFile("C:/Users/nisha.r/Desktop/untitled/asa.qml")); view.show(); return app.exec(); } This is asa.qml file import QtQuick 2.7 import QtQuick.Window 2.2 Rectangle{ Text { anchors.fill: parent text:qsTr("hello") } } ts file that is loaded is not reflected when executed. You must convert the .tsfile to a .qmfile using lrelease. Then load your .qmfile in your application. - dheerendra Qt Champions 2017 last edited by Hope you have included all your strings in cml using qstr. Run lupdate on the pro file. This generates the *.ts files. Now use Linquist tool & open the .ts file. Do all the conversions. Generate the *.qm(qm not QML). Now load the .qm file and install it as you done. This works. - ekkescorner Qt Champions 2016 last edited by @Nisha_R perhaps my blog post will give you some ideas. @dheerendra thank you it worked, i had missed giving a path for qm file. in load function. @ekkescorner i shall look into it, thank you.
https://forum.qt.io/topic/77426/how-to-make-use-of-internationalization
CC-MAIN-2021-10
refinedweb
224
64.17
At Sun, 7 Nov 2004 12:21:59 -0800 (PST), Matthew Dillon wrote: > > > :During the boot, interrputs are disabled and this shouldn't be a problem. > :And the interrupt vector is already initialized in fwohci_pci_attach() > :before fwochi_init() is called. > :It's a good idea that we should mask IT/IR interrupt before probing channels > :but it should have nothing to do with this problem. > : > :As interrupts are disable during the boot, it must not be a usual interrupt > :but a NMI. I think it's a PCI bus problem rather than RAM. > : > :Try the following patch, > : > :Index: fwohci_pci.c > :=================================================================== > :RCS file: /home/dcvs/src/sys/bus/firewire/fwohci_pci.c,v > :retrieving revision 1.15 > :diff -u -r1.15 fwohci_pci.c > :--- fwohci_pci.c 18 Jul 2004 12:37:03 -0000 1.15 > :+++ fwohci_pci.c 7 Nov 2004 19:47:52 -0000 > :@@ -238,6 +238,7 @@ > : PCIM_CMD_SERRESPEN | PCIM_CMD_PERRESPEN; > : #if 1 > : cmd &= ~PCIM_CMD_MWRICEN; > :+ cmd &= ~(PCIM_CMD_SERRESPEN | PCIM_CMD_PERRESPEN); > : #endif > : pci_write_config(self, PCIR_COMMAND, cmd, 2); > :... > : > :I suppose their code doesn't enable above flags. > :... > :/\ Hidetoshi Shimokawa > :\/ simokawa@xxxxxxxxxxx > > I think you've found it. All the OpenBSD code does is enable the bus > master bit. It doesn't touch any of the other bits. > > The original FreeBSD commit associated with this issue is: > > >revision 1.20 > >date: 2003/03/24 03:47:36; author: simokawa; state: Exp; lines: +6 -2 > >Safe PCI configuration. > >- Clear PCIM_CMD_MWRICEN: > > some chips seem to have problem with write invalidate. > > clearing this bit fixes SBP timeout problem. > > > >Tested by: Michael Reifenberger <Michael.Reifenberger@xxxxxxxx> > > > >- Set PCIM_CMD_SERRESPEN and PCIM_CMD_PERRESPEN > >- Moderate value for latency timer. > > He doesn't explain *WHY* he is turning on SERRESPEN and PERRESPEN. > Generally, however, any device with its own on-board memory (as these > devices have) is subject to parity errors on the PCI bus if that > memory is not completely cleared on boot. And that is what could be > happening here. Hmm, PERR and SERR indicates PCI bus parity errors and other fatal errors. I added it to detect broken hardwares. This is the first report of the error I have ever got. Are you sure it has something to do with clearing on-chip memory? Do you know how to clear them? > Note that in his commit message he had to turn off write-invalidate. > That's a sure sign of on-chip parity checked memory not being initialized. I thought PERR/SERR is independent of write-invalidate. Could you explain more? > I will role another ISO with the change and post when it's ready. Thanks, /\ Hidetoshi Shimokawa \/ simokawa@xxxxxxxxxxx
http://leaf.dragonflybsd.org/mailarchive/kernel/2004-11/msg00086.html
CC-MAIN-2014-42
refinedweb
424
69.07
TweenMax (AS3) - TweenLite on Steroids - Compatibility: Flash Player 9 and later (ActionScript 3.0) (Click here for the AS2 Version | Speed Comparison | Bezier Speed Comparison FEATURE COMPARISON USAGE - Description: Tweens the target's properties from whatever they are at the time you call the method to whatever you define in the variables parameter. - Parameters: - target : Object - Target object whose properties we're tweening - duration : Number - Duration (in seconds) of the tween - variables : Object - An object containing the end values of all the properties you'd like to have tweened (or if you're using the Tween.easing.Elastic.easeOut. The Default is Regular.easeOut. -. - volume : Number - To change a MovieClip's or SoundChannel's volume, just set this to the value you'd like the MovieClip/SoundChannel to end up at (or begin at if you're using TweenMax.from()). - tint : Number - To change a DisplayObject's tint/color, set this to the hex value of the tint you'd like the MovieClip to end up at(or begin at if you're using TweenMax.from()). An example hex value would be 0xFF0000. If you'd like to remove the color from a DisplayObject, just pass null as the value of tint. - frame : Number - Use this to tween a MovieClip to a particular frame. - bezier : Array - Bezier tweening allows you to tween in a non-linear way. For example, you may want to tween a DisplayObject. -) - renderOnStart : Boolean - If you're using TweenMax.from() with a delay and want to prevent the tween from rendering until it actually begins, set this special property to true. By default, it's false which causes TweenMax.from() to render its values immediately, even before the delay has expired. - overwrite : Boolean - If you do NOT want the tween to automatically overwrite any other tweens that are affecting the same target, make sure this value is false. - - Description: Exactly the same as Tween). -/MovieClip. You can optionally force it to immediately complete (which will also call the onComplete function if you defined one) - Parameters: - target : Object - Any/All tweens of this Object will be killed. - complete : Boolean - If true, the tweens for this object will immediately complete (go to the ending values and call the onComplete function if you defined one). - Description: Provides an easy way to kill all delayed calls to a particular function (ones that were instantiated using the TweenMax:0.5}, {time:1, y:300}]); - import gs.TweenMax; - import fl.motion.easing.Back; - TweenMax.to(clip_mc, 5, {alpha:0.5, x:120, ease:Back.easeOut,Max; - import fl.motion.easing.Elastic; - TweenMax.from(clip_mc, 5, {y:"-100", ease:Elastic.easeOut}); -MaxMax: - myButton.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver); - myButton.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut); - var scaleTween:TweenMax; - TweenMax.from(myButton, 2, {alpha:0, overwrite:false}); - function onMouseOver($e:MouseEvent):void { - TweenMax.removeTween(scaleTween); - scaleTween = TweenMax.to(myButton, 0.5, {scaleX:1.2, scaleY:1.2, overwrite:false}); - } - function onMouseOut($e:MouseEvent):void { - TweenMax.removeTween(scaleTween); - scaleTween = TweenMax.to(myButton, 0.5, {scaleX:1, scaleY:1,; - Why aren't my filters working? If you're using a filter that has an alpha property, try setting it to 1. The default alpha value is zero, so the filter may be working just fine, but you're not seeing it. is free. You're welcome to use it for commercial purposes - I only ask that you donate what you think the class is worth in your project(s), and consider joining Club GreenSock which gives you some bonus classes, updates, and more. If you want to use one (or more) of my classes in your commerical software product which would entail distributing the class files, please get my permission first by e-mailing me at jack -at- greensock.com. Need Help? Feel free to e-mail me a question.. on April 6th, 2008 at 12:13 pm Thank you sooooooooo much!!! That is simply “perfect” ;) on April 6th, 2008 at 5:02 pm I’m glad with this release! Thank you very much Jack! :) pd: bezierThrough is pretty cool, great idea (I never like the bezier system) on April 7th, 2008 at 5:46 am Great release - thank you! :) I especially like the new tween sequencing options which will save me a lot of time having to test delay and tween numbers and see which combination fits! Love the pause/resume too. I’ve used TweenLite in all my games to date, and this will replace it without hesitation. on April 7th, 2008 at 6:51 pm It’s amazing. Thanks a lot for your work. :-) on April 8th, 2008 at 3:29 am Hi Jack, First of all thanks for this great tweening engine! Just a notice to anyone who is experiencing problems tweening a “frame” property: I just upgraded from Tweenlite v 5.87 to the latest Version (6.1) and i found out that it didn’t work anymore. The problem was that i use TweenLite to tween a setter/getter called “frame” which TweenLite seems to work with internally on the target since version 6. Best regards, Thomas on April 8th, 2008 at 7:53 am Thanks! These classes are awesome! They have become an invaluable part of my AS3 coding arsenal . . . finding uses in almost every project on which I’m working. I made a donation today to support your work and encourage others to do the same. on April 8th, 2008 at 1:46 pm Nice job Jack! Very impressive! on April 8th, 2008 at 5:03 pm Unbelievable , great , beautiful work !! Thank you Jack !! it is what we were waiting for !! on April 8th, 2008 at 6:10 pm Absolutely brilliant, Jack. Much thanks =) on April 8th, 2008 at 6:15 pm Absolutely incredible. Thank you so much for all your releases. TweenLite especially has been magical, even in 3D. on April 8th, 2008 at 9:31 pm i don’t know what to say… this is just too good to be true. thank u so much, jack! on April 8th, 2008 at 10:12 pm Thank you so much for all of your hard work and for freely releasing TweenLite, it’s been a tremendous tool for me while learning and advancing my understanding of actionscript! :) on April 8th, 2008 at 10:38 pm This is really great. I really like the feature of tweening through beizer points. on April 9th, 2008 at 12:40 am Man…. you are THE MAN! I love your work and as always… its very impressive…. I’ve been tweening with tweenlite like crazy…. but now… its MAX-crazy time! keep up the great work… by the way… I love combining your tween engine with my new hobby (Papervision3d)… they work awsome together. on April 9th, 2008 at 8:23 am Awsome! I was fidling around, and guess what… bezier tweening is not just for position objects! you can bezier tween anything (i guess) as long as there are two pair of properties of an object. The two below tweens do the same thing. // there are two children on the stage called mmO and wwO import gs.TweenMax import fl.motion.easing.* var mm=1 var zz=100 var ww=1 mmO.x=wwO.x=mm mmO.y=wwO.y=zz TweenMax.to(wwO,2,{x:100,y:100,bezier:[{x:250,y:250}],ease:Linear.easeIn,onUpdate:tr}) TweenMax.to(this,2,{mm:100,zz:100,bezier:[{mm:250,zz:250}],ease:Linear.easeIn,onUpdate:tr}) function tr () { mmO.x=mm+10 mmO.y=zz+10 } on April 9th, 2008 at 11:01 am Have I overlooked any .fla source files that will show usage for things like sequencing with an array, tweening filter properties, etc. other than the ones above? Thanks! on April 9th, 2008 at 2:29 pm I’m so glad you brought that up, Stephanie. I just updated the samples that come with TweenMax so that you can see how to tween filters, basic properties, etc. There are now 4 FLA files included in the download. on April 10th, 2008 at 9:25 am Hey Jack, Amazing work. Can’t wait to take the new code for a spin. I’m definitely sending out some donation love your way. Quick question. Are the filesizes that you quote for each of the libraries cumulative? In other words, if I use TweenMax is it 8k or 17k (8k + 6k + 3k)? on April 10th, 2008 at 9:35 am Great question, Paul. The filesizes are TOTAL, not cumulative. So TweenMax combines TweenLite (3k) with TweenFilterLite (another 3k) with some new stuff (2k), adding up to a TOTAL of 8k. on April 10th, 2008 at 4:46 pm Omg, you are the god of Tween ^^ Very nice work :) TweenMax its very impressive. on April 11th, 2008 at 3:11 pm I agree with everyone else. TweenMax is the absolute greatest - now that it consolidates the other 2 engines, and still VERY small size. As a designer / flash developer, i highly recommend this to everyone! Thank you for all of your hard work. Keep it up! on April 18th, 2008 at 10:41 pm I’d like to praise you for THE greateste piece of programming I’ve seen in ActionScript… Small, fast, reliable… What else? ;) on April 24th, 2008 at 12:01 pm Again, you rock brother — TweenMax is a God send and just in the nick-o-time especially with the BezierTo and OrientToBezier funcs — fantastic, I’m already use this on Pro Projects right now — and yes I will donate as soon as I can paid from the client :) You deserve it, seriously. ROCK ON! Ozzy on April 24th, 2008 at 11:54 pm TweenMax is awesome! I made a nifty looping slideshow with crossfades: import gs.TweenMax; import fl.motion.easing.* TweenMax.allTo([mc1, mc2, mc3, mc4], 0, {autoAlpha:0, onCompleteAll:loop, overwrite:false}); function loop(): void{ TweenMax.allTo([mc1, mc2, mc3, mc4], 3, {autoAlpha:1, delayIncrement:3, onCompleteAll:loop, ease:Linear.easeOut, overwrite:false}); TweenMax.allTo([mc1, mc2, mc3, mc4], 1, {autoAlpha:0, delay:3, delayIncrement:3, ease:Linear.easeOut, overwrite:false}); } on May 5th, 2008 at 3:58 am Very amazing tweening engine. I replaced it with the Adobe tween class in my current project, and well.. Tweens where smooth again :). I’m going to develop futher with it, hoping to find the perfect tween engine in this. Keep on the good work!
http://blog.greensock.com/tweenmaxas3/
crawl-001
refinedweb
1,734
67.04
2016-01-13 07:05 AM Hi Team, I have written a attached workflow wherein i m creating a volume in first command, then Qtree part comes in. I dont want user to put the qtree name instead i have added a custom powershell command to get a "Qtree Name" from "DFS mgmt" because "Qtree Name" should be unique in the entire domain. I am able to get a "Qtree Name" from "DFS mgmt" but i need to use that name for further commands like "CIFS share creation and further on". Need help about how i can do this.? So in attached WorkFlow i get a qtree name in variable "$QtreeName" but how i can pass the value of this to qtree1 to use it in further commands? Solved! SEE THE SOLUTION 2016-01-13 09:07 AM Others may have others ideas, but you are in a place others hit often. You need the run-time results of one command to be useable in another subsequent comamnd of the workflow. People's first thought is getting the result into an MVEL namespace variable so you can then pass it to the subsequent command step. However, that is not possible (a longer story). WFA does have the ability for one command to create and set a workflow-global variable and a subsequent workflow command step can get to that variable ... using (check Developer Guide and check exact spelling of cmdlets): Set-WfaWorkflowParameter Get-WfaWorkflowParameter So something like: This probably means you can't use the built-in certified commands to cretae a qtree, share, etc (anything that needs to access myQtreeName). You will need to clone them and then modify them to use Get-WfaWorkflowParameter rather than a passed input parameter. 2016-01-18 09:06 AM Thanks Korns.
http://community.netapp.com/t5/OnCommand-Storage-Management-Software-Discussions/How-to-use-a-calculated-value-in-a-command-as-value-in-Parameter/td-p/114618
CC-MAIN-2018-13
refinedweb
299
66.37
Good day, every one. I'm just posting benchmark numbers for atomics patch. Hardware: 4 socket 72 core (144HT) x86_64 Centos 7.1 postgresql.conf tuning: shared_buffers = 32GB fsync = on synchronous_commit = on full_page_writes = off wal_buffers = 16MB wal_writer_flush_after = 16MB commit_delay = 2 max_wal_size = 16GB Results: pgbench -i -s 300 + pgbench --skip-some-updates Clients | master | atomics ========+=========+======= 50 | 53.1k | 53.2k 100 | 101.2k | 103.5k 150 | 119.1k | 121.9k 200 | 128.7k | 132.5k 252 | 120.2k | 130.0k 304 | 100.8k | 115.9k 356 | 78.1k | 90.1k 395 | 70.2k | 79.0k 434 | 61.6k | 70.7k Also graph with more points attached. On 2017-05-25 18:12, Sokolov Yura wrote: Hello, Tom. I agree that lonely semicolon looks bad. Applied your suggestion for empty loop body (/* skip */). Patch in first letter had while(true), but I removed it cause I think it is uglier: - `while(true)` was necessary for grouping read with `if`, - but now there is single statement in a loop body and it is condition for loop exit, so it is clearly just a loop. Optimization is valid cause compare_exchange always store old value in `old` variable in a same atomic manner as atomic read. Tom Lane wrote 2017-05-25 17:39:Sokolov Yura <funny.fal...@postgrespro.ru> writes: @@ -382,12 +358,8 @@ static inline uint64pg_atomic_fetch_and_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 and_){ uint64 old; - while (true) - { - old = pg_atomic_read_u64_impl(ptr); - if (pg_atomic_compare_exchange_u64_impl(ptr, &old, old & and_)) - break; - } + old = pg_atomic_read_u64_impl(ptr); + while (!pg_atomic_compare_exchange_u64_impl(ptr, &old, old & and_)); return old; } #endif FWIW, I do not think that writing the loops like that is good style. It looks like a typo and will confuse readers. You could perhaps write the same code with better formatting, eg while (!pg_atomic_compare_exchange_u64_impl(ptr, &old, old & and_)) /* skip */ ; but why not leave the formulation with while(true) and a break alone? (I take no position on whether moving the read of "old" outside the loop is a valid optimization.) regards, tom lane With regards, -- Sokolov Yura aka funny_falcon Postgres Professional: The Russian Postgres Company -- Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org) To make changes to your subscription:
https://www.mail-archive.com/pgsql-hackers@postgresql.org/msg316014.html
CC-MAIN-2018-43
refinedweb
357
76.82
Lesson 8 - Strings in the C language We've successfully avoided working with texts in our course. Until now, we have only worked with numbers and single characters. However, we'll need to work with text in most real-world applications. Texts are referred to as strings in programming (a string of characters). The reason we've put this topic off to the side is that C, as a low-level language, doesn't have any data type for storing text and it actually almost doesn't support them. Of course, we can work with texts in the C language, but it's a bit more complicated. Char array There are several ways to work with strings in the C language. We're going to introduce the simplest approach in this lesson - a static string which is an array of chars. Consider that we want to store the string "ICT.social", we would need to create the following array of the char type in memory: In each "box", there is a single character stored. Notice the extra box at the end, containing the \0 character which is the null character. All strings must end with it. Although C doesn't support strings as a language, it contains standard libraries for working with them. This is why we have to store strings as it's expected they'll look like. Meaning that an array representing a string must always be 1 item longer than the length of the text we're storing!. Note: Although it's beyond the range of today's lesson, let's mention that the null character is there to determine where the string ends. Aside from static arrays, we can also store strings of any length using pointers, as memory blocks of any length, and it wouldn't be possible without this little aid. We'll teach you everything further along in the courses. An alternative way to specify a string's length is to store it as a number before the first character. This system was used by the Pascal language, however, the null character is a much more common solution. Let's create a simple example. We'll store some text into a variable and print it to the console: {C_CONSOLE} char text[5] = {'m', 'o', 'o', 'n', '\0'}; printf("%s", text); {/C_CONSOLE} The result: Console application moon The good news is that the C language allows us to enter text in quotes which it then converts to a so-called string constant (a char array terminated by the \0 character). The code above can be rewritten to the following form: {C_CONSOLE} char text[5] = "moon"; printf("%s", text); {/C_CONSOLE} Notice that the array has to be 5 characters long even though the word "moon" is only 4 letters long. We can even let determining the length up to the C language: {C_CONSOLE} char text[] = "moon"; printf("%s", text); {/C_CONSOLE} Unfortunately, we're not able to assign a string constant to an already existing array: char text[5]; text = "moon"; // This line causes an error printf("%s", text); This is because it isn't possible for us to assign an array to another array. However, nothing is stopping us from assigning it character by character using a loop or to use functions for copying strings (more on that later on). Working with single characters We can work with strings in the same manners as with arrays (because they're actually arrays). Therefore, we are able to change the first character or shorten the string: {C_CONSOLE} char text[] = "moon"; text[0] = 'f'; text[3] = '\0'; printf("%s", text); {/C_CONSOLE} The result: Console application foo Changing the 4th character to \0 made the string terminate before that character. Always keep the null character in mind when editing strings, if you forget to assign it, the program won't know where the string ends and it'll access memory which doesn't belong to it. Reading/writing strings We can read or print strings as we're used to with other data types (we'll use the %s modifier). We'll create a string variable as a char array and specify a maximal length, e.g. 50 characters (which is 51 items). We omit the & characters when scanning variables using the %s modifier because we're already passing an address when passing arrays. The following program will let you enter your name and greet you: {C_CONSOLE} printf("Enter your name: "); char name[51]; scanf("%50s", name); printf("Hi %s, welcome!", name); {/C_CONSOLE} Notice how the maximal length is specified in the format of a string in the scanf() function. If we didn't specify it and encountered an exotic or just mean user, the characters would overflow from the array and break the program. Unfortunately, the scanf() function terminates the text when there is an empty space somewhere. If we wanted to read something like "John Smith" into a single variable, we'd need to modify the format string to not stop at anything other than line endings. Modify your line with the scanning to the following (the space at the beginning is really important since it won't keep white characters in the buffer): {C_CONSOLE} printf("Enter your name: "); char name[51]; scanf(" %50[^\n]s", name); printf("Hi %s, welcome!", name); {/C_CONSOLE} You may also encounter the functions gets() or fgets() used for reading text from the console. Avoid gets() since it doesn't allow us to limit the length of the text being entered, and fgets() has to be redirected to the standard input. Therefore, we'll get along using scanf() just fine. Standard string functions The C language specification provides many functions for working with strings which will make our programs more simple. To be able to use them, we need to include the string.h header file at the beginning of our file: #include <string.h> Note: since functions are named using abbreviations, I'll mention the original name for you as well to help you remember them better. strlen() - STRing LENgth We can determine the string's length using strlen(). It's the length of the visible part excluding the \0. #include <stdio.h> #include <string.h> int main(void) { printf("%d", strlen("moon")); // returns 4 } strcat - STRing conCATenate We're able to concatenate 2 strings into a single one using the strcat() function. Keep in mind that there has to be enough space for it in the first string. #include <stdio.h> #include <string.h> int main(void) { char text[20] = "moon"; strcat(text, " is in the sky"); // stores the string "moon is in the sky" to the text variable printf("%s", text); } strcpy() - STRing CoPY Since whole arrays cannot simply be copied, there is a function to clone a string into another variable. #include <stdio.h> #include <string.h> int main(void) { char text[5]; strcpy(text, "moon"); printf("%s", text); } strchr() - STRing CHaR We can search for a character in a string. It'll be searched from the beginning to the end and a pointer to it will be returned if the character is found. Although we can't work with pointers yet, it's enough for us now to know that if we subtract the string from the pointer, we'll get the position of the character we're looking for. If the text doesn't contain the character, we'll get a NULL value. #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char** argv) { char text[] = "Mr. X strikes again."; char *p = strchr(text, 'X'); // stores a pointer to the 'X' character in the string int position = p - text; if (p != NULL) { printf("Found at the position %d", position); } else { printf("Not found"); } return (EXIT_SUCCESS); } I guess you won't be surprised that the position is zero-based. strstr() - STRing subSTRing We can also search for a string (substring) in a string in the same manner as we would search for a single character. The function for it is called strchr() and is used in the exact same way. strcmp() - STRing CoMPare Compares 2 strings alphabetically and returns a negative number if the first string is before the second one, 0 if they're equal, and a positive number if the first one is after the second one. #include <stdio.h> #include <string.h> int main(void) { printf("%d", strcmp("alpha", "bravo")); // returns a negative number } We can also find other versions of the mentioned functions. If we wanted the C language to work with a string from the end (e.g. search for it starting from the end), the function for it contains a letter r in its name (as in reverse). Specifically, the function is named strrchr(). We can also limit the number of characters being processed using the letter n (as in number) and specifying said number as an additional parameter. If the string is longer, it'll only return the part which will be long as specified. Beware, this part doesn't contain the \0 character. Specifically, this function is called strncat(). In the next lesson, Strings in The C language - Working with single characters, we'll continue working with strings in the C language and make several example applications. Download Downloaded 1x (72.46 kB) Application includes source codes in language C No one has commented yet - be the first!
https://www.ict.social/cplusplus/c-language/basics/strings-in-the-c-language
CC-MAIN-2020-16
refinedweb
1,563
69.52
I have been given this assignment to be completed and I am stuck at the first step. Here are the requirements. I have 4 files: Parent.cs Child1.cs Child2.cs Form1.cs Parent is abstract class Modify child1.cs and child2.cs so that they are nested classes within Parent class Make sure child1 and child2 classes can only be created by Parent class Create a static method in Parent class which takes string parameter and if string is 'Child1' return child1 else return child2 Method in the form1.cs that creates and instance of parent class. I am not sure how to make them as nested classes ...if I need to create partial classes then how do I do that. How do I make sure that child classes can only be created by parent class? Thanks View Complete Post Hi, I am creating a simple CMS for learning purposes. It has a DAL, BLL and UI. The DAL contains non static methods which are accessed in the BLL layer. I have a factory pattern which creates instances of the DAL methods like this: public class Factory { public static T GetInstance<T>() where T : new() { return new T(); } } And they are accessed in the BLL like this: public void Save(Article article) { ArticleData artDate = GeepyFactory.GetInstance<ArticleData>(); } My question is, what additional logic should/usually go into the Factory class to make it favourable/a better solution over standard instantiation of a class like this ArticleDAL artDal = new ArticleDal(); ?? Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/35551-factory-pattern.aspx
CC-MAIN-2018-05
refinedweb
265
63.9
jGuru Forums Posted By: David_Pizon Posted On: Sunday, October 3, 2004 10:54 PM I am a Struts newbie attempting to write a login app. Most (if not all) of the examples I have found online use three JSP pages: I would like to change my app to have use only two JSP pages: I have an Action which validates user input and, if valid, invokes a bean to authenticate the user. I presume I need three findForwards in my Action: return (mapping.findForward(this.FORWARD_invalid)); return (mapping.findForward(this.FORWARD_incorrect)); return (mapping.findForward(this.FORWARD_success)); How do I let the login.jsp page know which error condition to display ("invalid field", "could not authenticate", or no error)? Am I on the right track?
http://www.jguru.com/forums/view.jsp?EID=1203130
CC-MAIN-2015-27
refinedweb
124
57.16
Creating modules Different languages provide different ways of modularizing code. In Python, we use modules to organize large programs. Python standard library uses modules extensively to organize related functions, classes, variables and constants. We have already used some built-in modules like math, datetime, random; etc a few times in the earlier lessons. If you have written a small program you don’t really need to organize your programs into modules, however, if your program is several pages long or you want to reuse your code, you should definitely use modules. So what is a module? A module is an ordinary Python file that ends with .py extension. We can define a group of classes, functions, variables, constants and so on inside a module. To reuse the classes or functions defined inside the module, we have to import the module in our program using the import statement. The syntax of import statement is as follows: where module_name is the name of the file without .py extension The import statement searches the module, parses and execute it’s content and makes it available to the client program. A client program or simply client is a program which uses classes, functions or variables defined in a module without knowing the implementation details. To refer to the module class, function or variables in the client program prefix it with the module’s name. For example, to call a function named timer() defined inside a module named great_module, in a client program do this: If import statement failed to find the module, ImportError error will be generated. Let’s take an example: Create a new file named my_module.py and add the following code to it. python101/Chapter-14/my_module.py Now we create a separate program (or client) named test_module.py in the same directory as my_module.py with the following code. python101/Chapter-14/test_module.py Output: In a module, identifiers used to name entities like class, function or variables must be unique. If two entities using the same name is found then the Python will use the last definition. Create a new file named reusing_identifiers.py and add the following code to it: python101/Chapter-14/reusing_identifiers.py The code is exactly the same as my_module.py, the only difference is that here we are defining another function named great_printer() at the end of the file. Now we have two functions using the same name ( great_printer). As a result, Python will use the last definition of great_printer() function. Create another client program named test_module2.py with the following code: python101/Chapter-14/test_module2.py Output: Importing Selected Identifiers The statement import my_module imports every identifier in the module to the client program. In some cases, we only want to use some specific names from the module. Let’s say from the module my_module.py, we only want to import doo_hickey() function and name variable in our client program. For situations like this, there exists another form of import statement which allows us to import only specific names from the module. Its syntax is: where name1, name2 and so on are names of the entities we want to import in our client program. Any code after this import statement can use name1, name2 and so on without prefixing it with the module name. Here is a program which imports only doo_hickey and name identifier from the module my_module. python101/Chapter-14/importing_selected_identifiers.py Output: In case you want to import every identifier into your client program do this: Here * indicates all identifiers. This statement is functionally equivalent to import module_name. The only difference is that the former one allows to access identifiers in a client program without prefixing it with the module name. Note: import module_name will not import names that start with a double underscore character.
https://overiq.com/python-101/modules-in-python/
CC-MAIN-2019-35
refinedweb
635
56.55
Are you sure? This action might not be possible to undo. Are you sure you want to continue? This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users. This is a practical guide with concise explanations, however the reader is supposed to know what s/he is doing. 1. System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3. File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4. Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. SSH SCP 7. RSYNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. VPN with SSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. SUDO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. Encrypt Files 10. Encrypt Partitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11. SSL Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13. SVN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. Useful Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15. Install Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. Convert Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18. Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19. Disk Quota 21. Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20. Shells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22. Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23. Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 20 23 25 26 27 27 30 31 34 36 40 41 43 43 45 46 48 50 52 Unix Toolbox revision 11 The latest version of this document can be found at. Replace .xhtml on the link with .pdf for the PDF version and with .book.pdf for the booklet version. On a duplex printer the booklet will create a small book ready to bind. Error reports and comments are most welcome - c@cb.vu Colin Barschel. — System — 1 SYSTEM Hardware (p2) | Statistics (p2) | Users (p3) | Limits (p3) | Runlevels (p4) | root password (p5) | Compile kernel (p6) Running kernel and system information # uname -a # cat /etc/SuSE-release # cat /etc/debian_version # Get the kernel version (and BSD version) # Get SuSE version # Get Debian version Use /etc/DISTR-release with DISTR= lsb (Ubuntu), redhat, gentoo, mandrake, sun (Solaris), and so on. # # # # # uptime hostname hostname -i man hier last reboot # # # # # Show how long the system has been running + load system's host name Display the IP address of the host. Description of the file system hierarchy Show system reboot history 1 .1 H ardware Informations Kernel detected hardware # dmesg # Detected hardware and boot messages # lsdev # information about installed hardware # dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 # Read BIOS Linux # # # # # # # # # # cat /proc/cpuinfo cat /proc/meminfo grep MemTotal /proc/meminfo watch -n1 'cat /proc/interrupts' free -m cat /proc/devices lspci -tv lsusb -tv lshal dmidecode # # # # # # # # # # CPU model Hardware memory Display the physical memory Watch changeable interrupts continuously Used and free memory (-m for MB) Configured devices Show PCI devices Show USB devices Show a list of all devices with their properties Show DMI/SMBIOS: hw info from the BIOS FreeBSD # # # # # # # # # sysctl hw.model sysctl hw sysctl vm dmesg | grep "real mem" sysctl -a | grep mem sysctl dev pciconf -l -cv usbdevs -v atacontrol list # # # # # # # # # CPU model Gives a lot of hardware information Memory usage Hardware memory Kernel memory settings and info Configured devices Show PCI devices Show USB devices Show ATA devices 1 .2 Load , s tatistics and messa ge s The following commands are useful to find out what is going on on the system. # # # # # top mpstat vmstat iostat systat 1 2 2 -vmstat 1 # # # # # display and update the top cpu processes display processors related statistics display virtual memory statistics display I/O statistics (2 s intervals) BSD summary of system statistics (1 s intervals) 2 — System — # # # # # # systat -tcp 1 systat -netstat 1 systat -ifstat 1 systat -iostat 1 tail -n 500 /var/log/messages tail /var/log/warn # # # # # # BSD tcp connections (try also -ip) BSD active network connections BSD network traffic through active interfaces BSD CPU and and disk throughput Last 500 kernel/syslog messages System warnings messages see syslog.conf 1 .3 Us ers # # # # # # # # # # # # id # last # who # groupadd admin # useradd -c "Colin Barschel" -g admin userdel colin # adduser joe # rmuser joe # pw groupadd admin # pw groupmod admin -m newmember # pw useradd colin -c "Colin Barschel" pw userdel colin; pw groupdel admin Show the active user id with login and group Show last logins on the system Show who is logged on the system Add group "admin" and user colin (Linux/Solaris) -m colin Delete user colin (Linux/Solaris) FreeBSD add user joe (interactive) FreeBSD delete user joe (interactive) Use pw on FreeBSD Add a new member to a group -g admin -m -s /bin/tcsh. # echo "Sorry no login now" > /etc/nologin # echo "Sorry no login now" > /var/run/nologin # (Linux) # (FreeBSD) 1 .4 Lim its asterisk hard nofile 409600 # Limit user processes # Limit application open files System wide Kernel limits are set with sysctl. Permanent limits are set in /etc/sysctl.conf. # # # # sysctl -a sysctl fs.file-max sysctl fs.file-max=102400 cat /etc/sysctl.conf # View all system limits # View max open files limit # Change max open files limit 3 — System — fs.file-max=102400 # cat /proc/sys/fs/file-nr # Permanent entry in sysctl.conf # # sysctl kern.maxfiles=XXXX kern.ipc.nmbclusters=32768 kern.maxfiles=65536 kern.maxfilesperproc=32768 kern.ipc.somaxconn=8192 # sysctl kern.openfiles # sysctl kern.ipc.numopensockets # # # # View all system limits maximum number of file descriptors Permanent entry in /etc/sysctl.conf Typical values for Squid # TCP queue. Better for apache/sendmail # How many file descriptors are in use # How many open sockets are in use See The FreeBSD handbook Chapter 111 for details. Solaris The following values in /etc/system will increase the maximum file descriptors per proc: set rlim_fd_max = 4096 set rlim_fd_cur = 1024 # Hard limit on file descriptors for a single proc # Soft limit on file descriptors for a single proc 1 .5 (the list is shown below) # chkconfig --list sshd # List all init scripts # Report the status of sshd 1. 4 — System — # chkconfig sshd --level 35 on # chkconfig sshd off # Configure sshd for levels 3 and update-rc.d update-rc.d shutdown -h sshd defaults # Activate sshd with the default runlevels sshd start 20 2 3 4 5 . stop 20 0 1 6 . # With explicit arguments -f sshd remove # Disable sshd for all runlevels # exit # shutdown -p now # shutdown -r now # # # # Go into single-user mode Go back to multi-user mode Shutdown and halt the system) 1 .6 Re s et sync; mount -o remount,ro / reboot # or delete the root password (/etc/shadow) # sync before to remount read only FreeBSD and Linux method 2 FreeBSD won't let you go away with the simple init trick. The solution is to mount the root partition from an other OS (like a rescue CD) and change the password on the disk. • Boot a live CD or installation CD into a rescue mode which will give you a shell. • Find the root partition with fdisk e.g. fdisk /dev/sda • Mount it and use chroot: # mount -o rw /dev/ad4s3a /mnt # chroot /mnt # chroot into /mnt 5 — System — # passwd # reboot Alternatively on FreeBSD, boot in single user mode, remount / rw and use passwd. # mount -u /; mount -a # passwd # reboot # will mount / rw 1 .7 Ke rnel modules Linux # lsmod # modprobe isdn # List all modules loaded in the kernel # To load a module (here isdn) FreeBSD # kldstat # kldload crypto # List all modules loaded in the kernel # To load a module (here crypto) 1 .8 Com p ile Kernel Linux # # # # # # # # # cd /usr/src/linux make mrproper make oldconfig make menuconfig make make modules make modules_install make install reboot # # # # # # # Clean everything, including config files Create a new config file from the current kernel or xconfig (Qt) or gconfig (GTK) Create a compressed kernel image Compile the modules Install the modules Install the kernel FreeBSD To modify and rebuild the kernel, copy the generic configuration file to a new name and edit it as needed. It is however also possible to edit the file GENERIC directly. # # # # # cd /usr/src/sys/i386/conf/ cp GENERIC MYKERNEL cd /usr/src make buildkernel KERNCONF=MYKERNEL make installkernel KERNCONF=MYKERNEL To rebuild the full OS: # # # # # # # # make buildworld make buildkernel make installkernel reboot mergemaster -p make installworld mergemaster reboot # Build the full OS but not the kernel # Use KERNCONF as above if appropriate # Compares only files known to be essential # Update all configuration and other files For small changes in the source, sometimes the short version is enough: # make kernel world # mergemaster # reboot # Compile and install both kernel and OS 6 — Processes — 2 PROCESSES Listing (p7) | Priority (p7) | Background/Foreground (p7) | Top (p7) | Kill (p8) 2 .1 Lis ting and PIDs Each process has a unique number, the PID. A list of all running process is retrieved with ps. # ps -auxefw # Extensive list of all running process However more typical usage is with a pipe or with pgrep: # ps axww | grep cron 586 ?? Is 0:01.48 /usr/sbin/cron -s # pgrep -l sshd # Find the PIDs of processes by (part of) name # fuser -va 22/tcp # List processes using port 22 # fuser -va /home # List processes accessing the /home partiton # strace df # Trace system calls and signals # truss df # same as above on FreeBSD/Solaris/Unixware # history | tail -50 # Display the last 50 used commands 2 .2 P riority # nice -n 5 top # nice +5 top # Stronger priority (/usr/bin/nice) # Weaker priority (/usr/bin/nice) # tcsh builtin nice (same as above!) 2 .3 Backg round/ Foregroun d When started from a shell, processes can be brought in the background and back to the foreground with [Ctrl]-[Z] (^Z), bg and fg. For example start two processes, bring them in the background, list the processes with jobs and bring one in the foreground. # ping cb.vu > ping.log ^Z # bg # jobs -l [1] - 36232 Running [2] + 36233 Suspended (tty output) # fg %2 # ping is suspended (stopped) with [Ctrl]-[Z] # put in background and continues running # List processes in background ping cb.vu > ping.log top # Bring process 2 back in foreground Use nohup to start a process which has to keep running when the shell is closed (immune to hangups). # nohup ping -i 60 > ping.log & 2 .4 T op The program top displays running information of processes. # top 7 — File System — While top is running press the key h for a help overview. Useful keys are: • u [user name] To display only the processes belonging to the user. Use + or blank to see all users • k [pid] Kill the process with pid. • 1 To display all processors statistics (Linux only) • R Toggle normal/reverse sort. 2 .5 Sig nals /Kill Terminate or send a signal with kill or killall. # ping -i 60 cb.vu > ping.log & [1] 4712 # kill -s TERM 4712 # killall -1 httpd # pkill -9 http # pkill -TERM -u www # fuser -k -TERM -m /home # # # # # same Kill Kill Kill Kill as kill -15 4712 HUP processes by exact name TERM processes by (part of) name TERM processes owned by www every process accessing /home (to umount) Important signals are: 1 HUP (hang up) 2 INT (interrupt) 3 QUIT (quit) 9 KILL (non-catchable, non-ignorable kill) 15 TERM (software termination signal) 3 FILE SYSTEM Disk info (p8) | Boot (p9) | Disk usage (p9) | Opened files (p9) | Mount/remount (p10) | Mount SMB (p11) | Mount image (p11) | Burn ISO (p11) | Create image (p12) | Memory disk (p13) | Disk performance (p13) 3 .1 P erm is sions Change permission and ownership with chmod and chown. The default umask can be changed for all users in /etc/profile for Linux or /etc/login.conf for FreeBSD. The default umask is usually 022. The umsak is subtracted from 777, thus umask 022 results in a permission 0f 755. 1 --x execute 2 -w- write 4 r-- read ugo=a # # # # # # # # chmod [OPTION] MODE[,MODE] FILE chmod 640 /var/log/maillog chmod u=rw,g=r,o= /var/log/maillog chmod -R o-r /home/* chmod u+s /path/to/prog find / -perm -u+s -print chown user:group /path/to/file chgrp group /path/to/file # Mode 764 = exec/read/write | read/write | read # For: |-- Owner --| |- Group-| |Oth| u=user, g=group, o=others, a=everyone # # # # # # # # MODE is of the form [ugoa]*([-+=]([rwxXst])) Restrict the log -rw-r----Same as above Recursive remove other readable for all users Set SUID bit on executable (know what you do!) Find all programs with the SUID bit Change the user and group ownership of a file Change the group ownership of a file 3 .2 Dis k information # # # # diskinfo -v /dev/ad2 hdparm -I /dev/sda fdisk /dev/ad2 smartctl -a /dev/ad2 # # # # information information Display and Display the about disk (sector/size) FreeBSD about the IDE/ATA disk (Linux) manipulate the partition table disk SMART info 8 — File System — 3 .3 Boot FreeBSD To boot an old kernel if the new kernel doesn't boot, stop the boot at during the count down. # unload # load kernel.old # boot 3 .4 Sys te m mount points/ D i sk usa ge # mount | column -t # df # cat /proc/partitions # Show mounted file-systems on the system # display free disk space and mounted devices # Show all registered partitions (Linux) Disk usage # # # # du du du ls -sh * -csh -ks * | sort -n -r -lSr # # # # Directory sizes as listing Total directory size of the current directory Sort everything by size in kilobytes Show files, biggest last 3 .5 Who ha s which files ope ne d This is useful to find out which file is blocking a partition which has to be unmounted and gives a typical error of: # umount /home/ umount: unmount of /home failed: Device busy # umount impossible because a file is locking home FreeBSD and most Unixes # fstat -f /home # fstat -p PID # fstat -u user # for a mount point # for an application with PID # for a user name Find opened log file (or other opened files), say for Xorg: # ps ax | grep Xorg | awk '{print $1}' 1252 # fstat -p 1252 USER CMD PID FD MOUNT root Xorg 1252 root / root Xorg 1252 text /usr root Xorg 1252 0 /var INUM 2 216016 212042 MODE drwxr-xr-x -rws--x--x -rw-r--r-- SZ|DV R/W 512 r 1679848 # lsof /home COMMAND PID USER tcsh 29029 eedcoba lsof 29140 eedcoba # List processes accessing /home FD cwd cwd TYPE DEVICE DIR 0,18 DIR 0,18 SIZE 12288 12288 NODE NAME 1048587 /home/eedcoba (guam:/home) 1048587 /home/eedcoba (guam:/home) 9 — File System — About an application: ps ax | grep Xorg | awk '{print $1}' 3324 # lsof -p 3324 COMMAND PID USER FD TYPE DEVICE Xorg 3324 root 0w REG 8,6 SIZE 56296 NODE NAME 3 .6 Mount/remount a file s y st e m For example the cdrom. If listed in /etc/fstab: # mount /cdrom Or find the device in /dev/ or with dmesg FreeBSD # mount -v -t cd9660 /dev/cd0c /mnt # mount_cd9660 /dev/wcd0c /cdrom # mount -v -t msdos /dev/fd0c /mnt # cdrom # other method # floppy Entry in /etc/fstab: # Device /dev/acd0 Mountpoint /cdrom FStype cd9660 Options ro,noauto Dump 0 Pass# 0 To let users do it: # sysctl vfs.usermount=1 # Or insert the line "vfs.usermount=1" in /etc/sysctl.conf Linux # mount -t auto /dev/cdrom /mnt/cdrom # mount /dev/hdc -t iso9660 -r /cdrom # mount /dev/sdc0 -t iso9660 -r /cdrom # typical cdrom mount command # typical IDE # / # mount -o ro / # Linux # FreeBSD Copy the raw data from a cdrom into an iso image: # dd if=/dev/cd0c of=file.iso 10 — File System — 3 .7 3 .8 Mount an image Linux loop-back # mount -t iso9660 -o loop file.iso /mnt # mount -t ext3 -o loop file.img /mnt # Mount a CD image # 3 .9 Cre ate and burn an ISO i m a ge This will copy the cd or DVD sector for sector. Without conv=notrunc, the image will be smaller if there is less content on the cd. See below and the dd examples (page 38). # dd if=/dev/hdc of=/tmp/mycd.iso bs=2048 conv=notrunc 11 — File System —" hw.ata.atapi_dma="1"2 can do this. It is in the FreeBSD ports in sysutils/bchunk. # bchunk imagefile.bin imagefile.cue imagefile.iso 3 .1 0 Create a file based ima ge For example a partition of 1GB using the file /usr/vdisk.img. FreeBSD # # # # # # dd if=/dev/random of=/usr/vdisk.img bs=1K count=1M mdconfig -a -t vnode -f /usr/vdisk.img -u 1 bsdlabel -w /dev/md1 newfs /dev/md1c mount /dev/md1c /mnt umount /mnt; mdconfig -d -u 1; rm /usr/vdisk.img # Creates device /dev/md1 # Cleanup the md device Linux # dd if=/dev/zero of=/usr/vdisk.img bs=1024k count=1024 # mkfs.ext3 /usr/vdisk.img 2. 12 — Network — # 3 .1 1 Create a memory file sy st e m A memory based file system is very fast for heavy IO application. How to create a 64 MB partition mounted on /memdisk: FreeBSD # mount_mfs -o rw -s 64M md /memdisk # umount /memdisk; mdconfig -d -u 0 md /memdisk mfs rw,-s64M # Cleanup the md device # /etc/fstab entry 0 0 Linux # mount -t tmpfs -osize=64m tmpfs /memdisk 3 .1 2 Dis k 4 NETWORK Routing (p14) | Additional IP (p14) | Change MAC (p14) | Ports (p14) | Firewall (p15) | IP Forward (p15) | NAT (p15) | DNS (p16) | DHCP (p17) | Traffic (p18) | QoS (p18) | NIS (p20) 4 .1 Debug ging (See also Tra f f i c a na l y si s) (pa ge 1 8 ) # # # # # # # # mii-diag eth0 # Show the link status (Linux) ifconfig fxp0 # Check the "media" field on FreeBSD arp -a # Check the router (or host) ARP entry (all OS) ping cb.vu # The first thing to try... traceroute cb.vu # Print the route path to destination mii-diag -F 100baseTx-FD eth0 # Force 100Mbit Full duplex (Linux) ifconfig fxp0 media 100baseTX mediaopt full-duplex # Same for FreeBSD netstat -s # System-wide statistics for each network protocol 13 — Network — 4 .2 Routing Print routing table # route -n # netstat -rn # route print # Linux # Linux, BSD and UNIX # # same as above with ip route route delete -net 192.168.20.0 netmask 255.255.255.0 Windows # Route add 192.168.50.0 mask 255.255.255.0 192.168.51.253 # Route add 0.0.0.0 mask 0.0.0.0 192.168.51.254 Use add -p to make the route persistent. 4 .3 Conf igure additional IP a ddr e sse s Linux # ifconfig eth0 192.168.50.254 netmask 255.255.255.0 # ifconfig eth0:0 192.168.51.254 netmask 255.255.255.0 # First IP # Second IP FreeBSD # ifconfig fxp0 inet 192.168.50.254/24 # First IP # ifconfig fxp0 alias 192.168.51.254 netmask 255.255.255.0 # Second IP Permanent entries in /etc/rc.conf ifconfig_fxp0="inet 192.168.50.254 netmask 255.255.255.0" ifconfig_fxp0_alias0="192.168.51.254 netmask 255.255.255.0" 4 .4 Change MAC address # ifconfig eth0 hw ether 00:01:02:03:04:05 # ifconfig fxp0 link 00:01:02:03:04:05 # Linux # FreeBSD 4 .5 P orts in use Listening open ports: 14 — Network — # # # # # # # # 4 .6 Fire wal l Check if a firewall is running (typical configuration only): Linux # iptables -L -n -v Open the iptables firewall # iptables -Z # iptables -F # iptables -X # iptables -P INPUT ACCEPT # iptables -P FORWARD ACCEPT # iptables -P OUTPUT ACCEPT # For status # # # # Zero the packet and byte counters in all chains Flush all chains Delete all chains Open everything 4 .7. 4 .8 NAT Network A ddress Tr a nsl a t i on 15 — Network — #" # Public interface or IP address to use. natd_flags="-s -m -u -dynamic -f /etc/natd.conf" Port forward with: # cat /etc/natd.conf same_ports yes use_sockets yes unregistered_only # redirect_port tcp insideIP:2300-2399 3300-3399 redirect_port udp 192.168.51.103:7777 7777 # port range 4 .9 /? # ipconfig /all # ipconfig /flushdns # Display help # See all information including DNS # Flush the DNS cache ;; SERVER: 192.168.51.254#53(192.168.51.254) 78.31.70.238 The router 192.168.51.254 answered and the response is the A entry. Any entry can be queried and the DNS server can be selected with @: # # # # dig dig dig dig MX google.com @127.0.0.1 NS sun.com @204.97.212.10 NS MX heise.de AXFR @ns1.xname.org cb.vu # To test the local server # Query an external server # Get the full zone (zone transfer) 16 — Network — The program host is also powerful. # host -t MX cb.vu # host -t NS -T sun.com # host -a sleepyowl.net # Get the mail MX entry # Get the NS record over a TCP connection # 4 .1 0 DHCP Linux Some distributions (SuSE) use dhcpcd as client. The default interface is eth0. # dhcpcd -n eth0 # dhcpcd -k eth0 # Trigger a renew #: 17 — Network — # ipconfig /renew # ipconfig /renew LAN # ipconfig /release WLAN # renew all adapters # renew the adapter named "LAN" # release the adapter named "WLAN" Yes it is a good idea to rename you adapter with simple names! 4 .1 1 Traf f ic analysis Bmon3 is a small console bandwidth monitor and can display the flow on different interfaces. Sniff with tcpdump # # # # # # # # # tcpdump tcpdump tcpdump tcpdump tcpdump tcpdump tcpdump tcpdump tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.168.16.54\) -l > dump && tail -f dump # Buffered output -i rl0 -w traffic.rl0 # Write traffic in binary file -r traffic.rl0 # Read from file (also for ethereal port 80 # The two classic commands host google.com -i eth0 -X port \(110 or 143\) # Check if pop or imap is secure -n -i eth0 icmp # Only catch pings 4) 4 .1 2 Traf f ic. 3. 4. 18 — Network — Linux For a 512 Kbit upload modem. # # # # tc tc tc tc qdisc add dev eth0 root tbf rate 480kbit latency 50ms burst 1540 -s qdisc ls dev eth0 # Status qdisc del dev eth0 root # Delete the queue # ipfw pipe 1 config bw 500Kbit/s # ipfw add pipe 1 ip from me to any # load the module if necessary # create a pipe with limited bandwidth # match ip dport 10000 0x3C00 flowid 1:1 # match ip dst 123.23.0.1 flowid 1:1 # 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 0 1 u32 \ use server port range or/and use server IP Status and remove with # tc -s qdisc ls dev eth0 # tc qdisc del dev eth0 root # queue status #) # echo "obase=16;(2^14)-1024" | bc # ending is 2^14 = 16384 # mask is 0x3C00 FreeBSD The max link bandwidth is 500Kbit/s and we define 3 queues with priority 100:10:1 for VoIP:ssh:all the rest. # # # # # # # # ipfw ipfw ipfw ipfw ipfw ipfw ipfw ipfw pipe 1 config bw 500Kbit/s queue 1 config pipe 1 weight 100 queue 2 config pipe 1 weight 10 queue 3 config pipe 1 weight 1 add 10 queue 1 proto udp dst-port 10000-11024 add 11 queue 1 proto udp dst-ip 123.23.0.1 # or/and use server IP add 20 queue 2 dsp-port ssh add 30 queue 3 from me to any # all the rest Status and remove with 19 — SSH SCP — # ipfw list # ipfw pipe list # ipfw flush # rules status # pipe status # deletes all rules but default 4 .1 3 NIS Debugging Some commands which should work on a well configured NIS client: # # # # ypwhich domainname ypcat group cd /var/yp && make # # # # get the connected NIS server name The NIS domain name as configured should display the group from the NIS server Rebuild the yp database 5 SSH SCP Public key (p20) | Fingerprint (p21) | SCP (p21) | Tunneling (p21) 5 .1 P ublic key authentication Connect to a host without password using public key authentication. The idea is to append your public key to the authorized_keys2 file on the remote host. For this example let's connect host-client to host-server, the key is generated on the client. • Use ssh-keygen to generate a key pair. ~/.ssh/id_dsa is the private key, ~/.ssh/ id_dsa.pub is the public key. •. • Create a key pair with the ssh.com client: Settings - User Authentication - Generate New.... • I use Key type DSA; key length 2048. • Copy the public key generated by the ssh.com client to the server into the ~/.ssh folder. • The keys are in C:\Documents and Settings\%USERNAME%\Application Data\SSH\UserKeys. • Use the ssh-keygen command on the server to convert the key: # cd ~/.ssh # ssh-keygen -i -f keyfilename.pub >> authorized_keys2 20 — SSH SCP — Notice: We used a DSA key, RSA is also possible. The key is not protected by a password. Using putty for Windows Putty5 is a simple and free ssh client for Windows. • Create a key pair with the puTTYgen program. • Save the public and private keys (for example Settings\%USERNAME%\.ssh). • Copy the public key to the server into the ~/.ssh folder: # scp .ssh/puttykey.pub root@192.168.51.254:.ssh/ into C:\Documents and • Use the ssh-keygen command on the server to convert the key for OpenSSH: # cd ~/.ssh # ssh-keygen -i -f puttykey.pub >> authorized_keys2 • Point the private key location in the putty settings: Connection - SSH - Auth 5 .2 Check f ingerprint 'l 5 .3 Se cure6. 5 .4 T unne ling # ssh -R destport:desthost:localport user@gate # ssh -X user@gate # To force X forwarding # desthost as seen from the gate # forwards your localport to destination 5. 6. 21 — SSH SCP —. • With putty use Source port=10.1.1.1:139. It is possible to create multiple loop devices and tunnel. On Windows 2000, only putty worked for me. • With the ssh.com client, disable "Allow local connections only". Since ssh.com will bind to all addresses, only a single share can be connected. Now create the loopback interface with IP 10.1.1.1: • # System->Control Panel->Add Hardware # Yes, Hardware is already connected # Add a new hardware device (at bottom). • # Install the hardware that I manually select # Network adapters # Microsoft , Microsoft Loopback Adapter. • Configure the IP address of the fake device to 10.1.1.1 mask 255.255.255.0, no gateway. • advanced->WINS, Enable LMHosts Lookup; Disable NetBIOS over TCP/IP. • #: • Are the ports forwarded: netstat -an? Look at 0.0.0.0:139 or 10.1.1.1:139 • Does telnet 10.1.1.1 139 connect? • You need the checkbox "Local ports accept connections from other hosts". •): 22 — VPN with SSH — # 6 6 .1: • Connect with SSH using the tunnel option -w •: 23 — VPN with SSH — cli># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 cli># ifconfig tun5 10.0.1.2 10.0.1.1 # Client is on Linux # Client is on FreeBSD The two hosts are now connected and can transparently communicate with any layer 3/4 protocol using the tunnel IP addresses. 6 .2 Conne ct) • Connect with SSH using the tunnel option -w. • Configure the IP addresses of the tunnel. Once on the server and once on the client. • Add the routing for the two networks. • If necessary, activate NAT on the private interface of the gate. The setup is started from gateA in netA. Connect from gateA to gateB Connection is started from gateA and commands are executed on gateB. gateB is on Linux gateA># gateB># gateB># gateB># gateB># ssh -w5:5 root@gateB ifconfig tun5 10.0.1.1 netmask 255.255.255.252 # Executed on the gateB shell route add -net 192.168.51.0 netmask 255.255.255.0 dev tun5 echo 1 > /proc/sys/net/ipv4/ip_forward # Only needed if not default gw iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE gateB is on FreeBSD gateA># gateB># gateB># gateB># gateB># gateA># ssh -w5:5 root@gateB ifconfig tun5 10.0.1.1 10.0.1.2 route add 192.168.51.0/24 10.0.1.2 sysctl net.inet.ip.forwarding=1 natd -s -m -u -dynamic -n fxp0 sysctl net.inet.ip.fw.enable=1 # Creates the tun5 devices # Executed on the gateB shell # Only needed if not default gw # see NAT (page 15) Configure gateA Commands executed on gateA: gateA is on Linux gateA># gateA># gateA># gateA># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 route add -net 192.168.16.0 netmask 255.255.255.0 dev tun5 echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE gateA is on FreeBSD gateA># gateA># gateA># gateA># gateA># ifconfig tun5 10.0.1.2 10.0.1.1 route add 192.168.16.0/24 10.0.1.2 sysctl net.inet.ip.forwarding=1 natd -s -m -u -dynamic -n fxp0 sysctl net.inet.ip.fw.enable=1 # see NAT (page 15). 24 — RSYNC — 7 'ssh 7 .1 Rs ync on Windows Rsync is available for Windows through cygwin or as stand-alone packaged in cwrsync7. 7. 25 — SUDO — appropriate. If the file authorized_keys2 does not exist yet, simply copy id_dsa.pub to authorized_keys2 and upload it. # # # # # ssh-keygen -t dsa -N '' rsync user@server:.ssh/authorized_keys2 . cat id_dsa.pub >> authorized_keys2 rsync authorized_keys2 user@server:.ssh/ del authorized_keys2 # # # # # Creates a public and a private key Copy the file locally from the server Or use an editor to add the key Copy the file back to the server Remove the local copy Now test it with (in one line): rsync -rv "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \ 'user/" \ 'user@server:My\ Documents/' pause 8 # sudo -u sysadmin whoami # Run the rc script as root # Run cmd as an other user 8 .1 Conf iguration 26 — Encrypt Files — User_Alias User_Alias Runas_Alias ADMINS DEVEL DBA = colin, luca, admin = joe, jack, julia = root,ADMINS DEVEL DEVEL rules ALL = (ALL) NOPASSWD: ALL DESKTOP = (ALL) NOPASSWD: ALL DMZ = (ALL) NOPASSWD: DEBUG # ADMINS can do anything w/o a password. # Developers have full right on desktops # 9 ENCRYPT FILES 9 .1 A s ingle file Encrypt and decrypt: # openssl des -salt -in file -out file.des # openssl des -d -salt -in file.des -out file Note that the file can of course be a tar archive. 9 .2 tar and encrypt a whol e di r e c t or y # tar -cf - directory | openssl des -salt -out directory.tar.des # openssl des -d -salt -in directory.tar.des | tar -x # Encrypt # Decrypt 9 .3 tar zip and encrypt a w hol e di r e c t or y # tar -zcf - directory | openssl des -salt -out directory.tar.gz.des # openssl des -d -salt -in directory.tar.gz.des | tar -xz # Encrypt # Decrypt • Use -k mysecretpassword after des to avoid the interactive password request. However note that this is highly insecure. • Use des3 instead of des to get even stronger encryption (Triple-DES Cipher). This uses also more CPU. 10 ENCRYPT PARTITIONS Linux with LUKS (p28) | Linux dm-crypt only (p28) | FreeBSD GELI (p28) | FBSD pwd only (p29). 27 — Encrypt Partitions — 1 0 .1 cryptsetup -y luksFormat /dev/sdc1 cryptsetup luksOpen /dev/sdc1 sdc1 mkfs.ext3 /dev/mapper/sdc1 mount -t ext3 /dev/mapper/sdc1 /mnt umount /mnt cryptsetup luksClose sdc1 # Optional. For paranoids only (takes days) # This destroys any data on sdc1 # create ext3 file system # dmsetup ls mkfs.ext3 /dev/mapper/sdc1 mount -t ext3 /dev/mapper/sdc1 /mnt umount /mnt/ cryptsetup remove sdc1 # or any other partition like /dev/loop0 # check it, will display: sdc1 (254, 0) # This is done only the first time! # Detach the encrypted partition Do exactly the same (without the mkfs part!) to re-attach the partition. If the password is not correct, the mount command will fail. In this case simply remove the map sdc1 (cryptsetup remove sdc1) and create it again. 1 0 .2 Fre e BSD The two popular FreeBSD disk encryption modules are gbde and geli. I now use geli because it is faster and also uses the crypto device for hardware acceleration. See The FreeBSD handbook Chapter 18.68 for all the details. The geli module must be loaded or compiled into the kernel: options GEOM_ELI device crypto # echo 'geom_eli_load="YES"' >> /boot/loader.conf # or as module: # or do: kldload geom_eli 8. 28 — Encrypt Partitions — geli init -s 4096 -K /root/ad1.key /dev/ad1 geli attach -k /root/ad1.key /dev/ad1 dd if=/dev/random of=/dev/ad1.eli bs=1m newfs /dev/ad1.eli mount /dev/ad1.eli /mnt # # # # # this key encrypts the mater key -s 8192 is also OK for disks DO make a backup of /root/ad1.key Optional and takes a long time Create file system Attach # geli attach -k /root/ad1.key /dev/ad1 # fsck -ny -t ffs /dev/ad1.eli # mount /dev/ad1.eli /mnt # In doubt check the file system mdconfig -at vnode -f /cryptedfile geli init /dev/md0 geli attach /dev/md0 newfs -U -m 0 /dev/md0.eli mount /dev/md0.eli /mnt umount /dev/md0.eli geli detach md0.eli # 1 GB file # encrypts with password only It is now possible to mount this image on an other system with the password only. # mdconfig -at vnode -f /cryptedfile # geli attach /dev/md0 # mount /dev/md0.eli /mnt 29 — SSL Certificates — 11). 1 1 .1 Proce dure • We need a certificate authority to sign our certificate. This step is usually provided by a vendor like Thawte, Verisign, etc., however we can also create our own. • Create a certificate signing request. This request is like an unsigned certificate (the public part) and already contains all necessary information. The certificate request is normally sent to the authority vendor for signing. This step also creates the private key on the local machine. • Sign the certificate with the certificate authority. • If necessary join the certificate and the key in a single file to be used by the application (web server, mail server etc.). 1 1 .2 Conf igure certs crl_dir database = = = = /usr/local/certs/CA $dir/certs $dir/crl $dir/index.txt # # # # Where everything is kept Where the issued certs are kept Where the issued crl are kept database index file. Make sure the directories exist or create them # # # # # mkdir -p /usr/local/certs/CA cd /usr/local/certs/CA mkdir certs crl newcerts private echo "01" > serial touch index.txt # Only if serial does not exist 1 1 .3 Create a certificate au t hor i t y 1 1 .4 Create a certificate si gni ng r e que st 30 — CVS — 1 1 .5. 1 1 .6 Create united certifica t e. • Open the private key (servernamekey.pem) with a text editor and copy the private key into the "servername.pem" file. •! 1 1 .7 Vie w certificate informa t i on To view the certificate information simply do: # openssl x509 -text -in servernamecert.pem # openssl req -noout -text -in server.csr # View the certificate info # View the request info 12 CVS Server setup (p31) | CVS test (p33) | SSH tunneling (p33) | CVS usage (p34) 1 2 .1 Server setup Initiate the CVS Decide where the main repository will rest and create a root cvs. For example /usr/local/cvs (as root): # # # # mkdir -p /usr/local/cvs setenv CVSROOT /usr/local/cvs cvs init cd /root # Set CVSROOT to the new location (local) # Creates all internal CVS config files 31 — CVS — # cvs checkout CVSROOT # cd CVSROOT edit config ( fine as it is) # cvs commit config cat >> writers colin ^D # cvs add writers # cvs edit checkoutlist # cat >> checkoutlist writers ^D # cvs commit # Checkout the config files to modify them # Create a writers file (optionally also readers) # Use [Control][D] to quit the edit # Add the file writers into the repository # Use [Control][D] to quit the: • Direct local access to the file system. The user(s) need sufficient file permission to access the CS directly and there is no further authentication in addition to the OS login. However this is only useful if the repository is local. •. • Remote access with pserver. --allow-root=/usr/local/cvs pserver cvs /usr/bin/cvs cvs \ # htpasswd -b passwd user2 password2 # -c creates the file 32 — CVS — 1 2 .2 Te s t For example: # setenv CVSROOT # setenv CVSROOT # setenv CVSROOT # setenv CVS_RSH # setenv CVSROOT :pserver:<username>@<host>:/cvsdirectory /usr/local/cvs :local:/usr/local/cvs :ext:user@cvsserver:/usr/local/cvs ssh :pserver:user@cvsserver.254:/usr/local/cvs # # # # # Used locally only Same as above Direct access with SSH for the ext access 1 2 .3 # ssh -L2401:cvs_server:2401 colin@gateway # Connect directly to the CVS server. Or: # 33 — SVN — 1 2 .4 CVS commands and usa ge cvs cvs cvs cvs cvs cvs cvs co myapp/tools co -r R1_1 myapp -q -d update -P update -A add newfile add -kb newfile commit file1 file2 commit -m "message" # # # # # # # # Will only checkout the directory tools Checkout myapp at release R1_1 (is sticky) A typical CVS update Reset any sticky tag (or date, option) Add a new file Add a new binary file Commit the two files only patch -p0 < patchfile patch -p1 < patchfile # Test the path without applying it # strip off the 1st level from the path 13 SVN Server setup (p34) | SVN+SSH (p35) | SVN over http (p35) | SVN usage (p36) Subversion (SVN)9 is a version control system designed to be the successor of CVS (Concurrent Versions System). The concept is similar to CVS, but many shortcomings where improved. See also the SVN book10. 1 3 .1 Server setup The initiation of the repository is fairly simple (here for example /home/svn/ must exist): # svnadmin create --fs-type fsfs /home/svn/project1 9. 10. 34 — SVN — Now the access to the repository is made possible with: • file:// Direct file system access with the svn client with. This requires local permissions on the file system. • svn:// or svn+ssh:// Remote access with the svnserve server (also over SSH). This requires local permissions on the file system. • 'Initial groupmod chown -R chmod -R subversion -A user1 subversion root:subversion /home/svn LoadModule dav_svn_module LoadModule authz_svn_module modules/mod_dav.so modules/mod_dav_svn.so] 35 — Useful Commands — project1-developers = joe, jack, jane # Give write access to the developers [project1:] @project1-developers = rw 1 3 .2 SVN commands and usa ge See also the Subversion Quick Reference Card11. Tortoise SVN12 'add newdir' Typical SVN commands # svn # # svn # svn # # # # # # svn svn svn svn svn svn co # Checkout the most recent version Tags and branches are created by copying mkdir # Create the tags directory copy -m "Tag rc1 rel." \ status [--verbose] # Check files status into working dir add src/file.h src/file.cpp # Add two files commit -m 'Added new class file' # Commit the changes with a message ls # List all tags move foo.c bar.c # Move (rename) files delete some_old_file # Delete files 14 USEFUL COMMANDS less (p36) | vi (p37) | mail (p37) | tar (p37) | dd (p38) | screen (p39) | find (p40) | Miscellaneous (p40) 1 4 .1 les s The less command displays a text document on the console. It is present on most installation. # less unixtoolbox.xhtml Some important commands are (^N stands for [control]-[N]): hH 11. 12. 36 — Useful Commands — 1 4 .2 vi Vi is present on ANY Linux/Unix installation and it is therefore useful to know some basic commands. There are two modes: command mode and insertion mode. The commands mode is accessed with [ESC], the insertion mode with i. Quit :w newfilename save the file to newfilename :wq or :x text dd D dw x u U delete current line Delete to the end of the line Delete word Delete character Undo last Undo all changes to current line 1 4 .3 m ail. 1 4 .4: 37 — Useful Commands — Create # # # # cd / tar -cf home.tar home/ tar -czf home.tgz home/ tar -cjf home.tbz home/ # archive the whole /home directory (c for create) # same with zip compression # tar tar tar tar -tzf home.tgz # look inside the archive without extracting (list) -xf home.tar # extract the archive here (x for extract) -xzf home.tgz # same with zip compression -xjf home.tgz # same with bzip2 compression -xjf home.tgz home/colin/file.txt # Restore a single file More advanced # # # # # tar tar tar tar tar c dir/ | gzip cvf - `find . -cf - -C /etc -cf - -C /etc -czf home.tgz | ssh user@remote 'dd of=dir.tgz' # arch dir/ and store remotely. -print` > backup.tar # arch the current directory. . | tar xpf - -C /backup/etc # Copy directories . | ssh user@remote tar xpf - -C /backup/etc # Remote copy. --exclude '*.o' --exclude 'tmp/' home/ 1 4 .5 dd The 'dd of=ad4s3e.gz' # also remote gunzip -dc ad4s3e.gz | ssh eedcoba@host 'dd 38 — Useful Commands — 'dd dd if=/dev/zero of=/dev/hdc dd if=/dev/urandom of=/dev/hdc kill -USR1 PID # # # # Delete MBR and partiton table Delete full disk Delete full disk better View dd progress (Linux only!) 1 4 .6 s cree n Screen has two main functionalities: • Run multiple terminal session within a single terminal. • A started program is decoupled from the real terminal and can thus run in the background. The real terminal can be closed and reattached later. Short start example start screen with: # screen Within the screen session we can start a long lasting program (like top). Detach the terminal and reattach the same terminal from an other machine (over ssh for example). # top Now detach with Ctrl-a Ctrl-d. Reattach the terminal with # screen -r or better: # screen -R -D Attach here and now. In detail this means: If a session is running, then reattach. If necessary detach and logout remotely first. If it was not running create it and notify the user. Screen commands (within screen) All screen commands start with Ctrl-a. • Ctrl-a ? help and summary of functions • Ctrl-a c create an new window (terminal) • Ctrl-a Ctrl-n and Ctrl-a Ctrl-p to switch to the next or previous window in the list, by number. • Ctrl-a Ctrl-N where N is a number from 0 to 9, to switch to the corresponding window. • Ctrl-a " to get a navigable list of running windows • Ctrl-a a to clear a missed Ctrl-a • Ctrl-a Ctrl-d to disconnect and leave the session running in the background • Ctrl-a x lock the screen terminal with a password 39 — Install Software — The screen session is terminated when the program within the running terminal is closed and you logout from the terminal. 1 4 .7 find find find find find find . -type f ! -perm -444 # Find files not readable by all . -type d ! -perm -111 # Find dirs not accessible by all /home/user/ -cmin 10 -print # Files created or modified in the last 10 min. . -name '*.[ch]' | xargs grep -E 'expr' # Search 'expr' in this dir and below. / -name "*.core" | xargs rm # Find core dumps and delete them / -name "*.core" -print -exec rm {} \; # Other syntax . \( -name "*.png" -o -name "*.jpg" \) -print # iname is not case sensitive find . \( -iname "*.png" -o -iname "*.jpg" \) -print -exec tar -rf images.tar {} \; find . -type f -name "*.txt" ! -name README.txt -print # Exclude README.txt files find /var/ -size +1M -exec ls -lh {} \; find /var/ -size +1M -ls # This is simpler find . -size +10M -size -50M -print find /usr/ports/ -name work -type d -print -exec rm -rf {} \; # Clean the ports Find files with SUID; those file have to be kept secure find / -type f -user root -perm -4000 -exec ls -l {} \; 1 4 .8 Mis ce l laneous # # # # # # # # # # # # # # # # # # rmdir /path/to/dir # Remove directory rm -rf /path/to/dir # Remove directory and its content (force) cp -la /dir1 /dir2 # Archive and hard link files instead of copy cp -lpR /dir1 /dir2 # Same for FreeBSD mv /dir1 /dir2 # Rename a directory 15 INSTALL SOFTWARE 1 5 .1 Lis t installed package s # rpm -qa # dpkg -l # pkg_info # List installed packages (RH, SuSE, RPM based) # Debian, Ubuntu # FreeBSD list all installed packages 40 — Convert Media — # pkg_info -W smbd # pkginfo # FreeBSD show which package smbd belongs to # Solaris 1 5 .2 Ad d/remove software Front ends: yast2/yast for SuSE, redhat-config-packages for Red Hat. # rpm -i pkgname.rpm # rpm -e pkgname # install the package (RH, SuSE, RPM based) # Remove package Debian # apt-get update # apt-get install emacs # dpkg --remove emacs # First update the package lists # Install the package emacs # Remove the package emacs FreeBSD # pkg_add -r rsync # pkg_delete /var/db/pkg/rsync-xx # Fetch and install rsync. # Delete the rsync package Set where the packages are fetched from with the PACKAGESITE variable. For example: # export PACKAGESITE= # or FreeBSD ports The port tree /usr/ports/ is a collection of software ready to compile and install. The ports are updated with the program portsnap. # # # # # portsnap fetch extract portsnap fetch update cd /usr/ports/net/rsync/ make install distclean make package # # # # # Create the tree when running the first time Update the port tree Select the package to install Install and cleanup (also see man ports) Make a binary package for the port 1 5 .3 Lib rary ldconfig -n /path/to/libs/ ldconfig -m /path/to/libs/ LD_LIBRARY_PATH # # # # List all needed runtime libraries Add a path to the shared libraries directories FreeBSD The variable set the link library path 16 CONVERT MEDIA Sometimes one simply need to convert a video, audio file or document to another format. 1 6 .1 Te xt encoding Text encoding can get totally wrong, specially when the language requires special characters like àäç. The command iconv can convert from one encoding to an other. 41 — Convert Media — #. 1 6 .2 Unix - DOS newlines Convert DOS (CR/LF) to Unix (LF) newlines within a Unix shell. See also dos2unix and unix2dos if you have them. # sed 's/.$//' dosfile.txt > unixfile.txt Convert Unix to DOS newlines within a Windows environment. Use sed from mingw or cygwin. # sed -n p unixfile.txt > dosfile.txt 1 6 .3 PDF to J peg and conc a t e na t e P D F f i l e s Convert a PDF document with gs (GhostScript) to jpeg (or png) images for each page. Also much shorter with convert Ghostscript can also concatenate multiple pdf files into a single one. # gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=all.pdf \ file1.pdf file2.pdf ... # On Windows use '#' instead of '=' 1 6 .4 1 6 .5 Cop y an audio cd The program cdparanoia13 13. 42 — Printing — 17 PRINTING 1 7 .1 18 DATABASES 1 8 .1 Pos tgreSQL Change root or a username password # psql -d template1 -U pgsql > alter user pgsql with password 'pgsql createdb -U pgsql -O bob bobdb dropdb bobdb dropuser bob # # # # -P will ask for password new bobdb is owned by bob Delete database bobdb Delete user bob The general database authentication mechanism is configured in pg_hba.conf Grant remote access The file $PGSQL_DATA_D/postgresql.conf specifies the address to bind listen_addresses = '*' for Postgres 8.x. The file $PGSQL_DATA_D/pg_hba.conf defines the access control. Examples: # TYPE host host DATABASE bobdb all USER bob all IP-ADDRESS 212.117.81.42 0.0.0.0/0 IP-MASK 255.255.255.255 METHOD password password to. Typically 43 — Databases — In this case the restore is started with the database postgres which is better when reloading an empty cluster. 1 8 .2 # mysql -u root mysql mysql> CREATE DATABASE bobdb; mysql> GRANT ALL ON *.* TO 'bob'@'%' IDENTIFIED BY 'p. '%'. 1 8 .1 SQLite SQLite14 is a small powerfull self-contined, serverless, zero-configuration SQL database. 14. 44 — Disk Quota — # sqlite database.db < dump.sql # dump # restore Convert 2.x to 3.x database sqlite database_v2.db .dump | sqlite3 database_v3.db 19 DISK QUOTA A disk quota allows to limit the amount of disk space and/or the number of files a user or (or member of group) can use. The quotas are allocated on a per-file system basis and are enforced by the kernel. 1 9 .1 # mount -o remount /home # mount rw,acl,user_xattr,usrquota 1 1 # 1 9 .2 Fre e BSD # mount /home /home ufs rw,noatime,userquota 2 2 # To remount the partition Enable disk quotas in /etc/rc.conf and start the quota. # grep quotas /etc/rc.conf enable_quotas="YES" check_quotas="YES" # /etc/rc.d/quota start # turn on quotas on startup (or NO). # Check quotas on startup (or NO). 45 — Shells — 1 9 .3 As s ign /dev/sda8 108 1000 hard 2000 inodes 1 soft 0 hard: '$3 > 499 {print $1}' /etc/passwd` # edquota -p refuser user1 user2 # Duplicate to 2 users Checks Users can check their quota by simply typing quota (the file quota.user must be readable). Root can check all quotas. # quota -u colin # repquota /home # Check quota for a user # Full report for the partition for all users 20 . 2 0 .1 bas h Redirects and pipes for bash and sh: 46 — Shells — # # # # # # # cmd 1> file cmd 2> file cmd 1>> file cmd &> file cmd >file 2>&1 cmd1 | cmd2 cmd1 2>&1 | cmd2 # # # # # # # Redirect stdout to file. Redirect stderr to file. Redirect and append stdout to file. Redirect both stdout and stderr to file. Redirects stderr to stdout and then to file. pipe stdout to cmd2 pipe stdout and stderr to cmd2 Modify your configuration in ~/.bashrc (it can also be ~/.bash_profile). The following entries are useful, reload with ". .bashrc". # 2 0 .2 tcs h Redirects and pipes for tcsh and csh (simple > and >> are the same as sh): # # # # cmd >& file cmd >>& file cmd1 | cmd2 cmd1 |& cmd2 # # # # Redirect both stdout and stderr to file. Append both stdout and stderr to file. pipe stdout to ../..' 47 — Scripting —). 21 SCRIPTING Basics (p48) | Script example (p49) | sed/useful commands (p49) The Bourne shell (/bin/sh) is present on all Unix installations and scripts written in this language are (quite) portable; man 1 sh is a good reference. 2 1 .1 Bas ics Variables and arguments Assign with variable=value and get content with $variable MESSAGE="Hello World" PI=3.1415 N=8 TWON=`expr $N * 2` TWON=$(($N * 2)) TWOPI=`echo "$PI * 2" | bc -l` ZERO=`echo "c($PI/4)-sqrt(2)/2" | bc -l` # Assign a string # Assign a decimal number # Arithmetic expression (only integers) # Other syntax # Use bc for floating point operations The command line arguments are $0, $1, $2, ... $# $* # $0 is the command itself # The number of arguments # All arguments (also $@) Special Variables $$ $? command if [ $? != 0 ]; then echo "command failed" fi mypath=`pwd` mypath=${mypath}/file.txt echo ${mypath##*/} echo ${mypath%%.*} var2=${var:=string} # The current process ID # exit status of last command # # # # Display the filename only Full path without extention Use var if set, otherwise use string assign string to var and then to var2. Constructs for file in `ls` do echo $file done count=0 while [ $count -lt 5 ]; do 48 — Scripting — echo $count sleep 1 count=$(($count + 1)) done myfunction() { find . -type f -name "*.$1" -print } myfunction "txt" # $1 is first argument of the function Generate a file MYHOME=/home/colin cat > testhome.sh << _EOF # All of this goes into the file testhome.sh if [ -d "$MYHOME" ] ; then echo $MYHOME exists else echo $MYHOME does not exist fi _EOF sh testhome.sh 2 1 fname=${file%.*} fext=${file#*.} # Assign the filename # Get the name of the file only # 2 1 .3 Some sed commands sed sed sed sed sed sed sed sed 's/string1/string2/g' -i 's/wroong/wrong/g' *.txt 's/\(.*\)1/\12/g' '/<p>/,/<\/p>/d' t.xhtml '/ *#/d; /^ *$/d' 's/[ \t]*$//' 's/^[ \t]*//;s/[ \t]*$//' 's/[^*]/[&]/' # # # # # # # # # Replace string1 with string2 Replace a recurring word with g Modify anystring1 to anystring2 Delete lines that start with <p> and end with </p> Remove comments and blank lines Remove trailing spaces (use tab as \t) Remove leading and trailing spaces Enclose first char with [] top->[t]op 49 — Programming — 2 1 .4 Some useful command$) 22 PROGRAMMING 2 2 .1 C bas ics strcpy(newstr,str) expr1 ? expr2 : expr3 x = (y > z) ? y : z; int a[]={0,1,2}; int a[2][3]={{1,2,3},{4,5,6}}; int i = 12345; char str[10]; sprintf(str, "%d", i); /* /* /* /* /* /* copy str to newstr */ if (expr1) expr2 else expr3 */ if (y > z) x = y; else x = z; */ Initialized array (or a[3]={0,1,2}; */ Array of array of ints */ Convert in i to char str */ 2 2 .2 C e xample A minimal c program simple.c: #include <stdio.h> main() { int number=42; printf("The answer is %i\n", number); } Compile with: # gcc simple.c -o simple # ./simple The answer is 42 2 2 .3 C++ basics *pointer &obj obj.x pobj->x // // // // // Object pointed to by pointer Address of object obj Member x of class obj (object obj) Member x of class pointed to by pobj (*pobj).x and pobj->x are the same 2 2 .4 C++ e xample As a slightly more realistic program in C++, let's create a class in its own header (IPv4.h) and implementation (IPv4.cpp) and create a program which uses the class functionality. The class 50 — Programming — has a member to convert an IP address in integer format to the known quad format. This is a minimal c++ program with a class and multi-source compile.; using namespace GenericUtils; IPv4::IPv4() {} IPv4::~IPv4() {} string IPv4::IPint_to_IPquad(unsigned long ip) { ostringstream ipstr; ipstr << ((ip &0xff000000) >> 24) << "." << ((ip &0x00ff0000) >> 16) << "." << ((ip &0x0000ff00) >> 8) << "." << ((ip &0x000000ff)); return ipstr.str(); } // use the namespaces // default constructor/destructor // member implementation // use a stringstream // Bitwise right shift The program simplecpp.cpp #include "IPv4.h" #include <iostream> #include <string> using namespace std; int main (int argc, char* argv[]) { string ipstr; unsigned long ipint = 1347861486; GenericUtils::IPv4 iputils; ipstr = iputils.IPint_to_IPquad(ipint); cout << ipint << " = " << ipstr << endl; return 0; } // // // // // define variables The IP in integer form create an object of the class call the class member print the result Compile and execute with: # g++ -c IPv4.cpp simplecpp.cpp # g++ IPv4.o simplecpp.o -o simplecpp.exe # ./simplecpp.exe 1347861486 = 80.86.187.238 # Compile in objects # Link the objects to final executable 51 — Online Help — Use ldd to check which libraries are used by the executable and where they are located. This command is also used to check if a shared library is missing or if the executable is static. # ldd /sbin/ifconfig 2 2 .5 Sim p le Makefile The corresponding} 23 ONLINE HELP 2 3 .1 2 3 .2 Other Unix/ Linux refe r e nc e s Rosetta Stone for Unix bhami.com/rosetta.html (a Unix command translator) Unix guide cross reference unixguide.net/unixguide.shtml Linux commands line list Short Linux reference That's all folks! This document: "Unix Toolbox revision 11" is licensed under a Creative Commons Licence [Attribution - Share Alike]. © Colin Barschel 2007-2008. Some rights reserved. 52
https://www.scribd.com/document/2345014/Unix-Linux-BSD-Cheat-Sheets-I
CC-MAIN-2018-17
refinedweb
9,088
64.3
Why not? OK, I guess my entry is going to get beaten by a circle and a stickman, but something like this happened every single time I went for technology during some kind of fast coding compo, so I think I'm used to it. It's okay. This is my competition and I haven't won once yet [append]Added a "Current Time" display on the time zone selector. This should alleviate a lot of the problems. -- Tomasu: Every time you read this: hugging! Ryan Patterson - <> KK, do think you could tell me what library you are using for the 3D? [EDIT]Is someone going to do the score count? KK, do think you could tell me what library you are using for the 3D? None and that's the beauty of my entry. It's simple raycaster with generated textures and sliding collisions 100% written during 1 hour. EDIT: Unless you meant my other projects, which are mostly AllegroGL+OpenGL and Direct3D from time to time. ________[ My LD48 entry ] [ My SpeedHack`04 entry ] [ TEAM ALLEGRO ] [ My TINS'05 entry - Snake ] I stand in awe of your Raycasting! Probably would have been best in a 2 or 3 hour comp. Also, could someone give me a link to where I can download OpenGL? Id have liked to try KK's, but sadly, It uses timeGetTime >:E -- Id have liked to try KK's, but sadly, It uses timeGetTime >:E Copy the code below, put it to a file named "winalleg.h" and place in the directory where you try to compile my entry. It should solve this problem. #include <sys/time.h> unsigned long long timeGetTime() { timeval T; gettimeofday(&T,0); return ((long long)T.tv_sec)*1000+T.tv_usec/1000; } 4191.cpp:224: warning: control reaches end of non-void function moose@natasha ~ $ ./4191 Shutting down Allegro due to signal #11 Segmentation fault (gdb) run Starting program: /home/moose/4191 Program received signal SIGSEGV, Segmentation fault. 0xb7eaf198 in _stub_bank_switch () from /usr/lib/liballeg.so.4.2 (gdb) bt #0 0xb7eaf198 in _stub_bank_switch () from /usr/lib/liballeg.so.4.2 #1 0x08048e7e in bmp_write_line (bmp=0x807a100, lyne=0) at al386gcc.h:46 #2 0x08048eba in _putpixel32 (bmp=0x807a100, (gdb) edit: append: Program received signal SIGSEGV, Segmentation fault. 0xb7ed149d in _stub_bank_switch (bmp=0x0, y=134718072) at cmisc.c:29 29 return (uintptr_t)bmp->line[y]; Current language: auto; currently c (gdb) bt #0 0xb7ed149d in _stub_bank_switch (bmp=0x0, y=134718072) at cmisc.c:29 #1 0x08048e7e in bmp_write_line (bmp=0x807a278, lyne=0) at al386gcc.h:46 #2 0x08048eba in _putpixel32 (bmp=0x807a278, OK, so where do I download OpenGL? I did a Google search, but I can't find the actual download for the library. OpenGL comes with your operating system. Your compiler should generally include OpenGL headers. Shutting down Allegro due to signal #11Segmentation fault Well, I have no idea what _putpixel32 does on your system, but for me it always behaved as "(((*int)(bmp->line[y]))[x]=color)" macro. Maybe I did something wrong, but I never thought you actually had to do anything extra to use _putpixel32 with memory bitmap. It should be working afaik. Maybe theres a bug in the C version? I dunno. CGames: BAFServ has been PHP 5.0.4 since the big reimage. Before that it was 5.1. BAF.cc [blog] | SantaHack 2011! It comes with windows XP? Yes, OpenGL comes with Windows XP, and its header files come with all respectable compilers. However, the version of OpenGL that comes with Windows XP is very old and mostly done in software. You will want to get drivers for your graphics card so that OpenGL is done in hardware, which odds are you have already done. I think 30th same time would awesome. Does anyone else have a problem with 30th at 1800 UTC? CGames: BAFServ has been PHP 5.0.4 [bafserv.com] since the big reimage. Before that it was 5.1. Tomasu: Maybe check the linking consistency of your Allegro? Did you upgrade gcc without recompiling? Does anyone else have a problem with 30th at 1800 UTC? I might be out for that weekend, but I'm not completely sure at the moment. Sounds good! I am definitely in. Competition link. Why don't you guys make sure the times are right before the day of the compo, eh? I added a "Current Time" field on the prefs page, so it should be easier. One problem with the "trigonometric functions" rule: I don't know how to use them. Also, is anyone going to do a score count? Onewing: 7Kikaru: 7CGamesPlay: 6Krzysztof: 4 Two first place winners! Good job, everybody. Let's keep this thread going until the 30th Wow! I'm first again! (counting from the other end of the list, but who cares) Congratulations to all entrants! Did you upgrade gcc without recompiling? Nein. its a new install... I can try reinstalling it. but I dunno. The 30th eh? I might be out of town then. Actually, I hope I'm out of town. ------------Solo-Games.org | I finally put my "Block the Block" game on my site! Come on, you're the only other one who has been in all 3
http://www.allegro.cc/forums/thread/587326/11
crawl-003
refinedweb
874
76.93
Please give me a Idea to sort the following array. #!/usr/local/bin/perl my @array = ( '1-1', '2-5', '1-10', '1-3','2-1'); print "value :" , $_ , ":\n" foreach ( sort @array ); [download] value :1-1: value :1-10: value :1-3: value :2-1: value :2-5: [download] value :1-1: value :1-3: value :1-10: value :2-1: value :2-5: [download] 2005-12-18 Retitled by Arunbear, as per consideration. Original title: 'Interpreting each and element of the array efficiently' Something like this? my @sorted = map { $_->[2] } sort { $a->[0] <=> $b->[0] or $a->[1] <=> $b->[1] } map { [ split( /-/, $_ ), $_ ] } @unsorted; [download] ...untested, but it ought to work. The biggest problem is figuring out the best use of whitespace in making such a construct look pretty. Update: For the record, I just tested it, and yes, it works as advertised. ;) The Schwartzian Transform isn't really a necessary part of it all, but to me, it makes it easier to read than if I had put all the splitting in the sort code block. Also, the or is used for "fall through". If the first comparison evaluates to equality, the logic falls through to the second comparison. Update-2: Here is it without the Schwartzian Transform. ...maybe it's not that ugly after all, though as the data set grows it may become less efficient: my @sorted = sort { my @a = split /-/, $a; my @b = split /-/, $b; $a[0] <=> $b[0] or $a[1] <=> $b[1] } @unsorted; [download] Dave my @array = ( '1-1', '6', '2-5', '1-10', '7', '1-3','2-1'); [download] ...expanding on my version "without Schwartzian Transform": my @sorted = sort { my @a = split /-/, $a; my @b = split /-/, $b; $a[0] <=> $b[0] or ( defined( $a[1] ) && defined( $b[1] ) and $a[1] <=> $b[1] ) } @unsorted; [download] As before, the worst part is figuring out how to tab the whole thing to keep it readable. ;) You need the defined test so that fall-through doesn't occur on single-term items. Update: Hmm, there is a problem here though. You didn't define whether "6" should come before, after, or between "6-0" and "6-10". My solution didn't define it either, which means that the definition of the problem is inadequate, and that the solution is equally inadequate. But the point to all this is that you can hand-craft your sort routine. ...just think through what you want it to do, and craft your code. I need to get some sleep, so I'll leave you in the capable hands of the rest of the PerlMonks. :) You can do it, really. Dig in and let us know when you get stuck. sorry for changing the requirement again what will happen if the array contains as follows: my @array = ( '1-1', '6', '2-5', '1-10', '7', '1-3','2-1'); [download] #!. It may, or it will? I guess what I am asking is, when does it pay to do the S.T. and why? Does it pay in this case? (I mean, if the data set was a lot larger?) UPDATE: Maybe an answer at Re: When does it pay to use the schwartzian transform? I think you want Sort::Naturally. But if it's just for this restricted task, then of course you can roll your own code. Well, you can try your hand at the general problem too. Having asked this very question myself some time ago in clpmisc I'll point you there: search for "sorting strings numerically"; e.g.: Benjamin Goldberg's reply and this thread. Unfortunately I cannot get from Google all the relevant posts in one thread. You may view the original node and the consideration vote tally. Didn't you just say exactly the same thing here? ...and this was my reply. No need to double-post. use Sort::Key qw(keysort); my @array = ( '1-1', '2-5', '2', '6', '1-10', '1-3','2-1'); my @sorted = keysort { pack "N*", split /-/, $_ } @array; [download] use Sort::Key::Natural 'natsort'; my @sorted = natsort @array; [download] use strict; use warnings; ### Randomly generate numbers my @array; for (0..100) { my @n; push @n, (int rand 15) + 1; for (0..((int rand 3) - 1)) { push @n, int rand 15; } push @array, join '-', @n; } ### Sort the numbers my @arr = map { $_ = join '-', @$_ } sort { mysort($a, $b) } map { $_ = [split '-'] } @array; print join "\n", @arr; ### mysort does the actual comparisons sub mysort { my ($s1, $s2) = ($#{$_[0]}, $#{$_[1]}); for (0..($s1 < $s2 ? $s2 : $s1)) { no warnings; return $_ if $_ = $_[0][$_] <=> $_[1][$_]; } ### N comes before N-0 return ($s1 < $s2 ? -1 : ($s2 > $s1 ? 1 : 0)); } [download] Edit: I will say, however, that yours looked the most promising. I tried it first, and was unhappy when I found I'd have to install a module to see how fast it ran :\ Hell yes! Definitely not I guess so I guess not Results (49 votes), past polls
http://www.perlmonks.org/index.pl?node_id=517195
CC-MAIN-2014-52
refinedweb
835
80.41
Markdown Comes Alive! Part 1, Basic Editor Building a markdown editor using Phoenix LiveView. In my last post, I covered what LiveView is at a high level. In this series, we’re going to dive deeper and implement a LiveView powered Markdown editor called Frampton. This series assumes you have some familiarity with Phoenix and Elixir, including having them set up locally. Check out Elizabeth’s three-part series on getting started with Phoenix for a refresher. This series has a companion repository published on GitHub. Get started by cloning it down and switching to the starter branch. You can see the completed application on master. Our goal today is to make a Markdown editor, which allows a user to enter Markdown text on a page and see it rendered as HTML next to it in real-time. We’ll make use of LiveView for the interaction and the Earmark package for rendering Markdown. The starter branch provides some styles and installs LiveView. Rendering Markdown Let’s set aside the LiveView portion and start with our data structures and the functions that operate on them. To begin, a Post will have a body, which holds the rendered HTML string, and title. A string of markdown can be turned into HTML by calling Post.render(post, markdown). I think that just about covers it! First, let’s define our struct in lib/frampton/post.ex: defmodule Frampton.Post do defstruct body: "", title: "" def render(%__MODULE{} = post, markdown) do # Fill me in! end end Now the failing test (in test/frampton/post_test.exs): describe "render/2" do test "returns our post with the body set" do markdown = "# Hello world!" assert Post.render(%Post{}, markdown) == {:ok, %Post{body: "<h1>Hello World</h1>\n"}} end end Our render method will just be a wrapper around Earmark.as_html!/2 that puts the result into the body of the post. Add {:earmark, "~> 1.4.3"} to your deps in mix.exs, run mix deps.get and fill out render function: def render(%__MODULE{} = post, markdown) do html = Earmark.as_html!(markdown) {:ok, Map.put(post, :body, html)} end Our test should now pass, and we can render posts! [Note: we’re using the as_html! method, which prints error messages instead of passing them back to the user. A smarter version of this would handle any errors and show them to the user. I leave that as an exercise for the reader…] Time to play around with this in an IEx prompt (run iex -S mix in your terminal): iex(1)> alias Frampton.Post Frampton.Post iex(2)> post = %Post{} %Frampton.Post{body: "", title: ""} iex(3)> {:ok, updated_post} = Post.render(post, "# Hello world!") {:ok, %Frampton.Post{body: "<h1>Hello world!</h1>\n", title: ""}} iex(4)> updated_post %Frampton.Post{body: "<h1>Hello world!</h1>\n", title: ""} Great! That’s exactly what we’d expect. You can find the final code for this in the render_post branch. LiveView Editor Now for the fun part: Editing this live! First, we’ll need a route for the editor to live at: /editor sounds good to me. LiveViews can be rendered from a controller, or directly in the router. We don’t have any initial state, so let's go straight from a router. First, let's put up a minimal test. In test/frampton_web/live/editor_live_test.exs: defmodule FramptonWeb.EditorLiveTest do use FramptonWeb.ConnCase import Phoenix.LiveViewTest test "the editor renders" do conn = get(build_conn(), "/editor") assert html_response(conn, 200) =~ "data-test=\"editor\"" end end This test doesn’t do much yet, but notice that it isn’t live view specific. Our first render is just the same as any other controller test we’d write. The page’s content is there right from the beginning, without the need to parse JavaScript or make API calls back to the server. Nice. To make that test pass, add a route to lib/frampton_web/router.ex. First, we import the LiveView code, then we render our Editor: import Phoenix.LiveView.Router # … Code skipped ... # Inside of `scope "/"`: live "/editor", EditorLive Now place a minimal EditorLive module, in lib/frampton_web/live/editor_live.ex: defmodule FramptonWeb.EditorLive do use Phoenix.LiveView def render(assigns) do ~L""" <div data-test=”editor”> <h1>Hello world!</h1> </div> """ end def mount(_params, _session, socket) do {:ok, socket} end end And we have a passing test suite! The ~L sigil designates that LiveView should track changes to the content inside. We could keep all of our markup in this render/1 method, but let’s break it out into its own template for demonstration purposes. Move the contents of render into lib/frampton_web/templates/editor/show.html.leex, and replace EditorLive.render/1 with this one liner: def render(assigns), do: FramptonWeb.EditorView.render("show.html", assigns). And finally, make an EditorView module in lib/frampton_web/views/editor_view.ex: defmodule FramptonWeb.EditorView do use FramptonWeb, :view import Phoenix.LiveView end Our test should now be passing, and we’ve got a nicely separated out template, view and “live” server. We can keep markup in the template, helper functions in the view, and reactive code on the server. Now let’s move forward to actually render some posts! Handling User Input We’ve got four tasks to accomplish before we are done: - Take markdown input from the textarea - Send that input to the LiveServer - Turn that raw markdown into HTML - Return the rendered HTML to the page. Event binding To start with, we need to annotate our textarea with an event binding. This tells the liveview.js framework to forward DOM events to the server, using our liveview channel. Open up lib/frampton_web/templates/editor/show.html.leex and annotate our textarea: <textarea phx-</textarea> This names the event ( render_post) and sends it on each keyup. Let’s crack open our web inspector and look at the web socket traffic. Using Chrome, open the developer tools, navigate to the network tab and click WS. In development you’ll see two socket connections: one is Phoenix LiveReload, which polls your filesystem and reloads pages appropriately. The second one is our LiveView connection. If you let it sit for a while, you’ll see that it's emitting a “heartbeat” call. If your server is running, you’ll see that it responds with an “ok” message. This lets LiveView clients know when they've lost connection to the server and respond appropriately. Now, type some text and watch as it sends down each keystroke. However, you’ll also notice that the server responds with a “phx_error” message and wipes out our entered text. That's because our server doesn’t know how to handle the event yet and is throwing an error. Let's fix that next. Event handling We’ll catch the event in our EditorLive module. The LiveView behavior defines a handle_event/3 callback that we need to implement. Open up lib/frampton_web/live/editor_live.ex and key in a basic implementation that lets us catch events: def handle_event("render_post", params, socket) do IO.inspect(params) {:noreply, socket} end The first argument is the name we gave to our event in the template, the second is the data from that event, and finally the socket we’re currently talking through. Give it a try, typing in a few characters. Look at your running server and you should see a stream of events that look something like this: There’s our keystrokes! Next, let’s pull out that value and use it to render HTML. Rendering Markdown Lets adjust our handle_event to pattern match out the value of the textarea: def handle_event("render_post", %{"value" => raw}, socket) do Now that we’ve got the raw markdown string, turning it into HTML is easy thanks to the work we did earlier in our Post module. Fill out the body of the function like this: {:ok, post} = Post.render(%Post{}, raw) IO.inspect(post) If you type into the textarea you should see output that looks something like this: Perfect! Lastly, it’s time to send that rendered html back to the page. Returning HTML to the page In a LiveView template, we can identify bits of dynamic data that will change over time. When they change, LiveView will compare what has changed and send over a diff. In our case, the dynamic content is the post body. Open up show.html.leex again and modify it like so: <div class="rendered-output"> <%= @post.body %> </div> Refresh the page and see: Whoops! The @post variable will only be available after we put it into the socket’s assigns. Let’s initialize it with a blank post. Open editor_live.ex and modify our mount/3 function: def mount(_params, _session, socket) do post = %Post{} {:ok, assign(socket, post: post)} end In the future, we could retrieve this from some kind of storage, but for now, let's just create a new one each time the page refreshes. Finally, we need to update the Post struct with user input. Update our event handler like this: def handle_event("render_post", %{"value" => raw}, %{assigns: %{post: post}} = socket) do {:ok, post} = Post.render(post, raw) {:noreply, assign(socket, post: post) end Let's load up and see it in action. Nope, that's not quite right! Phoenix won’t render this as HTML because it’s unsafe user input. We can get around this (very good and useful) security feature by wrapping our content in a raw/1 call. We don’t have a database and user processes are isolated from each other by Elixir. The worst thing a malicious user could do would be crash their own session, which doesn’t bother me one bit. Check the edit_posts branch for the final version. Conclusion That’s a good place to stop for today. We’ve accomplished a lot! We’ve got a dynamically rendering editor that takes user input, processes it and updates the page. And we haven’t written any JavaScript, which means we don’t have to maintain or update any JavaScript. Our server code is built on the rock-solid foundation of the BEAM virtual machine, giving us a great deal of confidence in its reliability and resilience. In the next post, we’ll tackle making a shared editor, allowing multiple users to edit the same post. This project will highlight Elixir’s concurrency capabilities and demonstrate how LiveView builds on them to enable some incredible user experiences.
https://www.viget.com/articles/markdown-comes-alive-part-1-basic-editor/
CC-MAIN-2021-43
refinedweb
1,740
67.55
Created on 2015-10-29 10:10 by terry.reedy, last changed 2016-11-11 00:10 by terry.reedy. This issue is now closed. In python, 'import tkinter; tkinter.font' fails with AttributeError. In IDLE, it does not, which is a bug, This lead to a Stackoverflow question 'Why does my code run in IDLE but not with Python'? The issue is that importing modules in a package has the side-effect of adding the module name to the package namespace. IDLE's user process runs idlelib/run.py. While *run* does not import tkinter submodules, it imports other modules that do, and the net effect is to add colorchooser, commondialog, dialog, filedialog, font, messagebox, and simpledialog to the tkinter namespace, linked to the corresponding module objects. None are needed in normal operation. My first thought was to refactor so that the additions, which run does not need, are not added. My second thought seemed simpler. Delete them (in run.py) after the imports. But it turns out that after deleting a submodule attribute re-import does not work right; the name addition only happens when a module is created, not when found in the sys.modules cache. >>> import tkinter; import tkinter.font # imagine this in run.py >>> tkinter.font <module tkinter.font...> >>> del tkinter.font # and this in run also, after all imports >>> import tkinter.font # imagine this in user code >>> tkinter.font # and then this Traceback (most recent call last): # it does not work as it should File "<stdin>", line 1, in <module> AttributeError: module 'tkinter' has no attribute 'font' Scratch that idea, and return to refactoring. An obvious culprit in run.py is the import of PyShell. This leads to the import of nearly all of idlelib. However, there are only 4 shared objects actually used, and I believe they could just as well be defined in run (or even in rpc.py or something) and imported from run into PyShell. Then the PyShell import could be deleted. I still need to look at the other imports. On startup, user sys.modules also has about 50 other (non-idlelib) stdlib modules not imported by python itself. Not importing PyShell in the 2nd process should reduce this number and speed up IDLE startup, which takes several seconds, first time after boot up, on Windows. It would be good to only import into the user process what is actually needed. (Initially importing into the idle process only what is needed to start would also be good, but a separate issue.) In 2.7, Tkinter is not a package, so I do not believe it is directly affected by this issue. On the other hand, it also imports too much. So backporting changes to keep things mostly synchronized should benefit 2.7 startup time also. This (restructuring/refactoring to minimize the subprocess imports) does definitely sound like the right approach. There will be other benefits to breaking up PyShell a bit too.. #8231 will benefit if indirect imports of configHandler and idleConf into the user process can be eliminated. I do not currently believe it is needed. Not importing PyShell will go part way. AutoComplete imports idleConf to get the popup delay. run imports AutoComplete to access fetch_completions -- in particular, the part after 'else', after the logic to determine which process the code is in and if in the idle process, whether to fetch in the idle process (-n) or user process. Fetch_completions is a function and not properly a method -- it only uses self to access get_entity. Get_entity is a two line function the also should not be a method. It is only called at the one place and the only reason to not put in inline would be for testing. The code after 'else' could be made a function in a separate module and the AutoComplete import eliminated. CallTip does not import idleConf, nor does CallTipWindow or HyperParser or PyParse. To continue: CallTips.Calltips has a similar here-or-there logic that decides where to execute the actual get-calltip-logic. In this case, get_entity and get_argspec are already functions rather than methods (I changed get_entity from method to function in 02b4c62ce393.) The functions could be moved into a different module with the completions function. RemoteDebugger imports Debugger which imports WindowList, ScrolledList, and macosxSupport, all without idleConf imports. RemoteObjectBrowser import rpc, both without idleConf. run also imports rpc. StackViewer imports TreeWidget and ObjectBrowser, which are not issues. It also imports PyShell for PyShellFileList, which would be an issue, except that this is only for the htest function _stack_viewer. I will move the test-specific import into the function, as is my current policy. IOBinding is imported for IOBinding.encoding. The code that calculates this could be put anywhere. This is fortunate because IOBinding imports idleConf and three tkinter modules. Conclusion: moving about 2-300 lines of code (about 6 objects) from PyShell, AutoComplete, and IOBinding into run (currently about 400 lines) would eliminate idleConf from the user process. I did not check tkinter imports for all the above, but it might also fix the tkinter namespace problem. The subprocess command is built in PyShell.ModifiedInterpreter method build_subprocess_arglist (l.404). It imports run and calls run.main(args). The test for this issue would be to import run and check that sys.modules does not contain configHandler and that tkinter does not contain any of its possible submodules. New changeset a37ea1d56e98 by Terry Jan Reedy in branch '2.7': Issue #25507: move test-specific imports to test function (idlelib.IOBinding). New changeset 38b6b7253ba1 by Terry Jan Reedy in branch '3.4': Issue #25507: move test-specific imports to test function (idlelib.IOBinding). Ouch. Moving the idleConf import was a blunder. It disabled printing in 2.7.11, 3.4.4, and 3.5.1. When I revert, I will also augment the htest to test the printing and save-as functions. Still have to remember to run it though. This sort of functional test is not the main intended use of htests. When refactoring for this issue, automated tests should be added, with mocks used to avoid consequential actions that cannot be part of a buildbot test. For print_window, '''pipe = os.popen(command, "r")''' () should be replaced by '''pipe = runcommand(command)''' and 'def runcommand(command): return os.pipe(command, 'r')''' (with subprocess used instead?) added at module level. Then runcommand can be replaced by a mock when testing, and the value of the passed command checked. New changeset 34ca24fa1b4a by Terry Jan Reedy in branch '2.7': Issue #25507: revert incorrect movement of idleConf import in a37ea1d56e98. New changeset 86105a109830 by Terry Jan Reedy in branch '3.5': Issue #25507: revert incorrect movement of idleConf import in c548ad75160c. 'import tkinter; tkinter.messagebox' should also fail, but currently work in IDLE. See, and my answer there. According to, this code from tkinter import filedialog root = Tk() ran in 3.4.3. After the patch for 3.5.1 (and 3.4.4, 2.7.11) it raises NameError in 3.5.2. same problem with filedialog. The SO question and that brought the problem to my attention was in June 2015.. The message I just unlinked had the wrong url. New changeset 93d325c64104 by Terry Jan Reedy in branch 'default': Issue #25507: Move 4 objects from pyshell to run and switch inports. First step. Patch moves 4 objects from pyshell to run and reverses run importing pyshell to pyshell importing run. This initially failed because run imports stackbrowser and the stackbrowser import of something from pyshell failed. Since the import is only needed for htest, I just moved it into the htest code. Removing 'import pyshell' from run avoids 'import tkinter.messagebox' in pyshell. It also reduces len(sys.modules) in the user process by 37 from 193 to 156. In #27515, Nick Coughlin said that 'del a.b', would work if sys.modules('a.b') is also deleted -- unless a.b objects to being reloaded. This seems not a problem for the current 8 tkinter submodules. The attached tkimports.py runs without error. I am not going to patch 2.7, which does not have the bug, just for the import reduction. The last patch could be applied to 3.5 since it does not remove anything from PyShell. Putting the three warning functions in a class and making the warning global a class attribute (a future issue) would be a different matter. run_autocomplete.diff is a preliminary patch for moving the completion list function into run.py and reversing the imports. However, the assert in test_autocomplete, line 103 newly fails because the call to open_completions in autocomplete_event (line 85) returns None. The None comes from l. 155. comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return None I do not yet know why moving the one function causes the completion lists for re to be blank. I am going to shelve this approach and return to deletion. New changeset 8df5200064c4 by Terry Jan Reedy in branch '3.5': Issue #25507: IDLE no longer runs buggy code because of its tkinter imports. New changeset af602a891892 by Terry Jan Reedy in branch 'default': Issue #25507: Merge from 3.5 with ttk replacing colorchooser. I decided to fix this issue for both 3.5 and 3.6 by deleting the submodules both from tkinter and sys.modules (as discussed in #27515). I used a new version of tkimports.py to check the result of user imports after the patch. When this file loaded into IDLE and run with F5, the dir listing for each submodule, after previous import and deletion in run startup, is the same as when the file is run with "<python-path> tkimports". I opened #27534 to continue run import reduction. I consider 93d325c64104 and run_autocomplete.diff to be part of that issue. PS: the test suite run without error on my Win10, 32bit build. I am thinking about addin a test. New changeset 137c7b92360e by Terry Jan Reedy in branch '2.7': Issue #25507: Add back import needed for 2.x encoding warning box. Import is only needed for the warning issued when someone using IDLE 2.x puts a non-ascii character into code being edited and tries to save without adding an encoding declaration.
https://bugs.python.org/issue25507
CC-MAIN-2019-39
refinedweb
1,711
68.77
>Submitter-Id: net >Originator: >Organization: net >Confidential: no >Synopsis: unable to build 1.11.1p1 with gssapi/kserver support >Severity: non-critical >Priority: medium >Category: cvs >Class: sw-bug >Release: cvs-1.11.1p1 >Environment: System: Linux blade.devel.redhat.com 2.4.3-12smp #1 SMP Fri Jun 8 14:38:50 EDT 2001 i686 unknown Architecture: i686 >Description: Unable to build 1.11.1p1 with gssapi/kserver support due to CVS_Username not being declared in server.c >How-To-Repeat: configure with --with-krb4 or --with-gssapi, attempt to compile >Fix: here's a short patch to 1.11.1p1: --- cvs-1.11.1p1/src/server.c Thu Apr 19 15:34:04 2001 +++ cvs-1.11.1p1/src/server.c Tue Jun 19 17:37:04 2001 @@ -95,27 +95,31 @@ #include <grp.h> #endif /* HAVE_INITGROUPS */ -# ifdef AUTH_SERVER_SUPPORT +# if defined (HAVE_KERBEROS) || defined (AUTH_SERVER_SUPPORT) || defined (HAVE_GSSAPI) # ifdef HAVE_GETSPNAM # include <shadow.h> # endif /* The cvs username sent by the client, which might or might not be the same as the system username the server eventually switches to run as. CVS_Username gets set iff password authentication is successful. */ char *CVS_Username = NULL; + +# ifdef AUTH_SERVER_SUPPORT /* Used to check that same repos is transmitted in pserver auth and in later CVS protocol. Exported because root.c also uses. */ static char *Pserver_Repos = NULL; /* Should we check for system usernames/passwords? Can be changed by CVSROOT/config. */ int system_auth = 1; # endif /* AUTH_SERVER_SUPPORT */ + +#endif /* HAVE_KERBEROS || AUTH_SERVER_SUPPORT || HAVE_GSSAPI */ /* While processing requests, this buffer accumulates data to be sent to
http://lists.gnu.org/archive/html/bug-cvs/2001-06/msg00227.html
CC-MAIN-2014-41
refinedweb
252
51.04
Java local variable type inference last modified July 13, 2020 Java local variable type inference tutorial shows the new feature of Java 10 — local variable type inference. Type inference is the ability of a compiler to infer the data type from the right side of an assigment. Java 10 Java 10 was released on March 20, 2018. It brings several Java Enhancement Proposals (JEPs). The JEP 286 is called local variable type inference. JEP 296 This document improves the developer experience by reducing the ceremony associated with writing Java code, while maintaining Java's commitment to static type safety, by allowing developers to elide the often-unnecessary manifest declaration of local variable types. It introduces a new var keyword, which can be used on the left side of the assignment operation. Java automatically infers the necessary data type from the right side of the assignment. Java local type variable inference example In the following example, we are going to create a simple Java console application in which we test the new feature. $ wget $ tar xzvf jdk-10_linux-x64_bin.tar.gz $ mv jdk-10 ~/bin We download the Oracle JDK and open the archive. We move the installation directory to a new directory of our choice. $ ~/bin/jdk-10/bin/java --version java 10 2018-03-20 Java(TM) SE Runtime Environment 18.3 (build 10+46) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode) We verify the version of Java. $ mkdir -p src/com/zetcode bin $ touch src/com/zetcode/JavaNewsEx.java $ tree . ├── bin └── src └── com └── zetcode └── JavaNewsEx.java We create the directory structure. package com.zetcode; import java.util.List; public class JavaNewsEx { public static void main(String[] args) { var name = "Jonathan"; System.out.printf("The word %s has %d characters%n", name, name.length()); var age = 34; age += 12; System.out.println(age); var words = List.of("cloud", "fine", "pen", "dog", "temper", "sky", "book"); System.out.println(words); } } This is the soruce code of the example. var name = "Jonathan"; A new variable name is defined. We use the var keyword. The type is String, which is inferred from the string literal. $ ~/bin/jdk-10/bin/javac -d bin src/com/zetcode/JavaNewsEx.java $ ~/bin/jdk-10/bin/java -cp bin com.zetcode.JavaNewsEx The word Jonathan has 8 characters 46 [cloud, fine, pen, dog, temper, sky, book] We compile and run the example. In this tutorial, we have used the new feature of Java 10 — the local variable type inference. You might also be interested in the following related tutorials: Convenience Factory Methods for Java Collections and Java tutorial.
https://zetcode.com/articles/javavariabletypeinference/
CC-MAIN-2021-21
refinedweb
437
51.34
How to combine applets and thereading to create a simple animation, why there is flickering and what is solution for it moving object animation. How would you make a rotating banner using applet and therads. This topic comes at the end of Applet programming, we hope you have gone through both our previous articles on Applet and you also know the threading concepts if not so we suggest you move back a little and study following. Java Multi Threading - Basic Concepts Java Multi Threading - Advance Concepts Java Applet Programming - First Step to Applets Java Applet Programming - Playing with Utilities We hope that by now you are quite familiar with the threads as well as applets. So here is the final part of our applet series which will help you with the applets as well as thread concept. We are now going to make a moving banner, which will be moving like a HTML marquee however this will be accomplished by using repaint() method of awt which is commonly known for animation purposes in Java. The biggest con you'll find in the application is flickering, which occurs because of the repainting but our focus will remain on the login however there is a technique which is used by Java community to avoid the flickering effect, this is known as "Double Buffering". Let us now move on to the program but before that, let us tell you what you are going to learn from this program. The program creates and applet in which it will take message from the param tag and will render it on the applet window. Then, using the thread we will move it from right to left and when it will cross the left boundary it will restart from far right. We will be using repaint method in the run() to move the applet and message will be moved only for the x-axis so that y-axis remains constant. import java.applet.Applet; import java.awt.*; public class FirstApplet extends Applet implements Runnable{ private Thread th; private int x; private boolean flag; private String msg,tag; public void init(){ x = 400; flag = true; th = new Thread(this); msg = getParameter("examsmyantra"); tag = getParameter("tagline"); } public void start(){ if(!flag){ th.resume(); flag = true; } else{ th.start(); } } public void stop(){ th.suspend(); flag = false; } public void destroy(){ } public void run(){ try{ while(true){ if((x+ msg.length()) < 0){ x=500; } x-=2; Thread.sleep(100); repaint(); } } catch(InterruptedException ie){ System.out.println(ie); } } public void paint(Graphics g){ g.drawString(msg, x, 100); showStatus(tag); } } /* <applet code="FirstApplet" width="500" height="200"> <param name="examsmyantra" value="" > <param name="tagline" value="Study with Awesomeness" > </applet> */ I hope you noticed the use of suspend and resume method call in the program. These are the methods from the Thread class, the purpose it to temporarily suspend the execution and resume whenever we want. We have used it here because we don't want our thread to keep running even when we are not watching it or using it, we mean when the applet is minimized. So we use suspend and when it starts again by the virtue of resume function. We have used a flag variable which is just to check the status of the thread so that we only use the proper function. So when you run it you will see the Applet like this. As an exercise we suggest you to draw various other drawing objects like rectangle and circle, and move them instead of string. you may find more about the drawing objects in the class Graphics, use following command to find out the method signature, javap java.awt.Graphics.
http://www.examsmyantra.com/article/55/java/the-applet-and-threading-blending-an-animation
CC-MAIN-2019-09
refinedweb
612
58.32
The latest version of Zeus has support for the DCD D language autocomplete client and server utilities. NOTE: Other Zeus, D language specific features can be found here: Using the dfmt with Zeus Using the Dscanner (D Language) inside Zeus Using the D Programming Language with Zeus Example of Dot Completion Example of Brace Completion Example of Display Document Comment The DCD Display Document Comment is done by this Zeus macro: To use that macro you need to bind it to a keyboard key. Code: Select all dcd_display_doc.py Consider this sample D code where the | indicates the cursor location: Running that display macro results in the following tooltip: Code: Select all module main; import std.stdio; import std.datetime; /******************************* * This is a D Doccumment for the TestStruct structure. * * This comment is displayed in a tool tip. */ struct TestStruct { int test; } void main() { TestStruct| } Example of Find Declaration Consider this code: Placing the cursor on the StopWatch word and running the goto declaration script will take you to this file: Code: Select all import std.stdio; import std.datetime; int main(string[] args) { StopWatch sw = StopWatch(AutoStart.yes); return 0; } and to this code location: Code: Select all C:\dmd2\src\phobos\std\datetime.d Setup Instructions Code: Select all @safe struct StopWatch { public: .... To make this work do the following: - Make sure you are running Zeus version 3.97t or better: - Download an build the DCD client and server utilities - Make sure the DCD client and server executables are somewhere in the PATH - Start Zeus and use the Options, Document Types menu to edit the D document type, selecting the Triggers panel - Use the dcd_intellisense.py script for Dot Autocomplete - Use the dcd_intellisense.py script for Brace Autocomplete - Use the dcd_intellisense.py script for Autocomplete - Use the dcd_goto_declaration.py script for Goto Definition and Goto Declaration - Make sure the DCD server is running - Edit some D code and you should see intellisense on the dot key and the open bracket key Use the Options, Editor Options menu and select the editor Triggers panel. For the Application Starting use the dcd_app_starting.lua script. For the Application Closing use the dcd_app_closing.lua script. With these scripts in place Zeus will manage the starting and stopping of the DCD server.
http://www.zeusedit.com/phpBB3/viewtopic.php?t=7020
CC-MAIN-2020-50
refinedweb
378
54.22
Provided by: manpages-dev_5.05-1_all NAME adjtime - correct the time to synchronize the system clock SYNOPSIS #include <sys/time.h> int adjtime(const struct timeval *delta, struct timeval *olddelta); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): adjtime(): Since glibc 2.19: _DEFAULT_SOURCE Glibc 2.19 and earlier: adjtime() │ Thread safety │ MT-Safe │ └──────────┴───────────────┴─────────┘ CONFORMING TO 4.3BSD, System V. NOTES The adjustment that adjtime() makes to the clock is carried out in such a manner that the clock is always monotonically increasing. Using adjtime() to adjust the time prevents the problems that can be caused for certain applications (e.g., make(1)) by abrupt positive or negative jumps in the system time. adjtime() is intended to be used to make small adjustments to the system time. Most systems impose a limit on the adjustment that can be specified in delta. In the glibc implementation, 5.05 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.ubuntu.com/manpages/focal/en/man3/adjtime.3.html
CC-MAIN-2021-49
refinedweb
174
59.9
replace pandas dataframe with a unique id I got a dataframe with millions of entries, with one of the columns 'TYPE' (string). There is a total of 400 values for this specific column and I want to replace the values with integer id starting from 1 to 400. I also want to export this dictionary 'TYPE' => id for future reference. I tried with to_dict but it did not help. Anyway can do this ? 1 answer - answered 2018-01-14 10:04 MaxU Option 1: you can use pd.factorize: df['new'] = pd.factorize(df['str_col'])[0]+1 Option 2: using category dtype: df['new'] = df['str_col'].astype('category').cat.codes+1 or even better just convert it to categorical dtype: df['str_col'] = df['str_col'].astype('category') and when you need to use numbers instead just use category codes: df['str_col'].cat.codes thanks to @jezrael for extending the answer - for creating a dictionary: cats = df['str_col'].cat.categories d = dict(zip(cats, range(1, len(cats) + 1))) PS category dtype is very memory-efficient too See also questions close to this topic - Python package issue on Debian 9 I have got a virtual server, on this server I installed a Debian 9.3. I installed python2.7.13 following this instruction (how to install python 2.7 on debian9) I tried to run my code, but of course it isn't working, because I have to install first the modules. So i started with the selenium (its just an example..) , and when I installed it with "sudo pip install selenium" nothing change. I get this information : "Requirement already satisfied : selenium in /usr/local/lib/python2.7/site-packages", but I want to start my program from /usr/src/Python-2.7.13 (like in the code) so i get this error message that "No module named selenium"".. What am I wrong? How can I solve this problem? Some information about the system: pip --version : pip 9.0.1 from /usr/local/lib/python2.7/site-packages (python 2.7) python --version : Python 2.7.13 - Can we create objects for abstract class in python There is some confusion with abstract class in python, can we create object for abstract class in python? - Matplotlib runtime error: MATPLOTLIBDATA not a directory I've built a pyqt4 application with matplotlib plots on Linux. I'm creating an installer for this application with pyinstaller. The installer got created successfully but, on executing the exe I get following error, RuntimeError: Path in environment MATPLOTLIBDATA not a directory How to fix this error? Thanks, - How to calculate running total and reset when value change with Python? I want to calculate running total of Promo, and reset running total when Promo changes. How can I achieve this with Python and Pandas? Thanks very much! Id Date Promo Running_Total 0 19 2015-07-09 0 0 1 18 2015-07-10 0 0 2 17 2015-07-11 0 0 3 16 2015-07-13 1 1 4 15 2015-07-14 1 2 5 14 2015-07-15 1 3 6 13 2015-07-16 1 4 7 12 2015-07-17 1 5 8 11 2015-07-18 0 0 9 10 2015-07-20 0 0 10 9 2015-07-21 0 0 11 8 2015-07-22 0 0 12 7 2015-07-23 0 0 13 6 2015-07-24 0 0 14 5 2015-07-25 0 0 15 4 2015-07-27 1 1 16 3 2015-07-28 1 2 17 2 2015-07-29 1 3 18 1 2015-07-30 1 4 19 0 2015-07-31 1 5 - Conditionally creating rows in pandas A 0 a-7,5,1,6,63,101,39,1 1 c-2,7,10,12,27,40,71,78 I have a dataframe quite similar to the one above. The letters preceding the -in each row represents an id Each of the comma separated values represent an entry in the dataframe. How do i conditionally format this row such that I end up getting something like: id A 0 a 7 0 a 5 0 a 1 0 a 6 0 a 63 0 a 10 1 c 2 1 c 10 1 c 12 1 c 27 1 c 40 - how to split dict column from pandas data frame The above link providing some solution to my answer But i have same problem with little different in input. here my DF: df = pd.DataFrame({'a':[1,2,3], 'b':[[{'c':1},{'c':3}], {'d':3}, {'c':5, 'd':6}]}) My dict again contains list of dicts for Key "b". My expected O/P : [a c c1 d 0 1 1.0 3 NaN 1 2 NaN NaN 3.0 2 3 5.0 NaN 6.0][1] Could you please help. - how does numpy.linalg.norm ord=2 work? I am new to Numpy. I couldn't understand the use of ord=2 in numpy.linalg.norm. For example, what is the difference between: np.linalg.norm(np.array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]])) and np.linalg.norm(np.array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]]),2) In Numpy documentation, it is given that ord =2 means 2-norm (largest sing. value). I couldn't understand what is meant by largest singular value. Could you explain? - - Spliting cells from 2 columns to rows I have a dataset which looks as follows Cus_ID Event Day 1 Event1~Event2~Event3~Event4 1~1~1~1 2 Event3~Event4~Event5~Event6 1~2~3~4 the output i'm trying to get would be: Cus_ID | Event | Day | EventSplit|Day split ---------------------------------------------------------------------------- 1 | Event1~Event2~Event3~Event4| 1~1~1~1 | Event1 |1 1 | Event1~Event2~Event3~Event4| 1~1~1~1 | Event2 |1 1 | Event1~Event2~Event3~Event4| 1~1~1~1 | Event3 |1 1 | Event1~Event2~Event3~Event4| 1~1~1~1 | Event4 |1 2 | Event3~Event4~Event5~Event6| 1~2~3~4 | Event3 |1 2 | Event3~Event4~Event5~Event6| 1~2~3~4 | Event4 |2 2 | Event3~Event4~Event5~Event6| 1~2~3~4 | Event5 |3 2 | Event3~Event4~Event5~Event6| 1~2~3~4 | Event6 |4 I am trying to parse this data and split it into a new row if a specific delimiter appears. Those delimiter is '~'. that is spliting Event and Day column in to new column name as Eventsplit and day split I have done following code But i dont know How do i do it for both the columns at one go Can any body help. This is approach no. 1 I tried import pandas as pd import numpy as np data =pd.read_csv("SeqData.csv") def pre(data, c): event_col = data[c].str.split('~') clst = event.values.tolist() lens = [len(l) for l in clst] EventSplit = pd.DataFrame({c: np.concatenate(clst)}, data.index.repeat(lens)) return data.drop(c, 1).join(EventSplit ).reset_index(drop=True) Data_df = pre(data, 'Event') Approach no_2 Tried EventSplit= data.Event.str.split('~',expand=True).stack() Day_split = data.Day.str.split('~',expand=True).stack() new_data = data.join(pd.Series(index=Day_split .index.droplevel(1), data=Day_split .values, name='Day_split ')) new_data = data.join(pd.Series(index=EventSplit.index.droplevel(1), data=EventSplit.values, name='EventSplit'))
http://codegur.com/48248490/replace-pandas-dataframe-with-a-unique-id
CC-MAIN-2018-05
refinedweb
1,219
65.42
let's face reality, the status of storages in the Web is a mess. localStorage is a synchronous API not suitable at all to store data. WebSQL has been abandoned, still the only option, as non experimental, in Safari, Chrome, and Opera. Firefox is trying to support IndexedDB which right now is the most messed up API ever: loads of inconsistencies across platforms, included different versions of Firefox itself. Internet Explorer 10, the one not even out yet, has insignificant market sharing 'till now. My proposal to bring WebSQL back through Firefox extension has been banned, after approval, due potential securities issues ... so, what the hell we have to do in order to use a proper storage that is not ultra-complicated to understand, learn, and use? localStorage and sessionStorage have been around for quite a while and many developers are using these for any sort of task, including any sort of data stored in these synchronous storage without considering that: localStorage.clear()in the page your script is, your whole logic will magically fuck up without any notification (also because the event "storage" is completely randomly implemented) localStorageare using direct property access, completely obtrusive for any sort of shimmable solution you would like to implement, plus 99% of the time these tutorials are not using a try{}catch(e){}statement around every single localStorage.setItem(key, value)call, which means your business logic is already broken What if you have nothing new to learn, using exactly the same API the WebStorage offer, except how to handle callbacks? This is what is this project about, a basically identical API borrowed directly from the Web Storage one, with a couple of extra arguments per each asynchronous method such callback and errorback, where both are even optional. First of all, the main purpose of this project is to use any asynchronous possibility available in the browser through a key/value pairs based interface where both keys and values should be strings. It is not the purpose of this script to provide any JSON shim in your code, but of course as you have probably used JSON already to store data in a generic storage, you can do the same with this implementation, remembering to JSON.stringify(yourDataObject) before you store it. Back to the asynchronous concept, Where there is no possibility, the localStorage or even document.cookie is used as fallback so that even IE6 should work "without problems", whenever you decided to harakiri supporting latter browser. The very first option, if available, is the WebSQL storage, the best thing ever destroyed by W3C, the most cross platform, for both Desktop and Mobile, storage possibility. IndexedDB would be the other option where WebSQL is not available. This order might change in the future preferring IndexedDB as first option. All others will fallback into localStorage or document.cookie and I am not discarding at all the possibility to use a SharedObject from the Flash Player world ... but, you know, I have abandoned Flash Player about 6 years ago and if I can make it without it, now that would be cool! What else? Oh well, it's easy! asyncStorage.create("myDBName", function (db, numberOfEntries) { // database created, time to rock'n'roll! var callback = function (value, key) { if (value === "true") { // do amazing stuff for the very first time } // do whatever you want to }; // check how many values you have stored so far if (numberOfEntries === 0) { // add some default entry db.setItem("neverLoaded", "true", callback); } else { db.setItem("neverLoaded", "false", callback); } }); Above is just an example of easiness provided by this asynchronousStorage but here few main pros: localStorage.clear(), performed by another library, will not erase your whole data. db.clear()aim is to clean only data you stored and nobody else. db.lengthand, since length is synchronous, db.key(index)to retrieve the keyassociated to that index. create(name, callback) creates a new database with specific name in order to, somehow, simulate namespaces in the storage itself. callback(db, numberOfEntries) will be fired once the database has been created. create(name, callback, errorback) does the same, except you might want to handle potential errors during database creation (user denied, not enough space, etc). create(name, callback, errorback, size) does the same, except you might want to specify in advance the size of the database. This overload works as expected with WebSQL only. db.setItem(key, value[, callback[, errorback]]) set an item in the storage and calls callback(value, key, db) once the operation is completed. The errorback is called if something went wrong during this operation. db.getItem(key[, callback[, errorback]]) retrieves a value from the storage, callback(value, key, db) is called once the operation is completed where the value is exactly null wherever key was not set before db.removeItem(key[, callback[, errorback]]) remove an item from the storage, calls callback(key, db) once succeeded db.clear([callback[, errorback]]) remove all keys associated to your database name, the one used to create the storage at the very beginning. callback(db, numberOfEntries) will be triggered once the operation has been completed, same signature of the storage creation for functions reusability. db.key(index) returns synchronously the associated key for that index. This is necessary to make easier for developers loops over all keys as they do already with the localStorage, i.e. function isItLastOne() { if (!--i) { doAgainAllStuff(); } } for (var i = 0; i < db.length; i++) { db.removeItem(db.key(i), isItLastOne); } db.length returns the length of all stored keys in your database name db.name returns the name you chose for this storage instance db.type returns the type of the database you are using such WebSQL, IndexedDB (not yet), localStorage, and cookie And this is pretty much it ... wanna test? this page should be green
https://www.npmjs.com/package/asyncStorage
CC-MAIN-2017-39
refinedweb
964
53.81
What's new in Solaris 11.1? By Karoly Vegh-Oracle on Oct 31, 2012 Solaris 11.1 is released. This is the first release update since Solaris 11 11/11, the versioning has been changed from MM/YY style to 11.1 highlighting that this is Solaris 11 Update 1. Solaris 11 itself has been great. What's new in Solaris 11.1? Allow me to pick some new features from the What's New PDF that can be found in the official Oracle Solaris 11.1 Documentation. The updates are very numerous, I really can't include all. I. New AI Automated Installer RBAC profiles have been introduced to enable delegation of installation tasks. II. The interactive installer now supports installing the OS to iSCSI targets. III.: IV. The new command svcbundle helps you to create SMF manifests without having to struggle with XML editing. (btw, do you know the interactive editprop subcommand in svccfg? The listprop/setprop subcommands are great for scripting and automating, but for an interactive property editing session try, for example, this: svccfg -s svc:/application/pkg/system-repository:default editprop ) V. pfedit: Ever wondered how to delegate editing permissions to certain files? It is well known "sudo /usr/bin/vi /etc/hosts". VI. rsyslog, the popular logging daemon (filters, SSL, formattable output, SQL collect...) has been included in Solaris 11.1 as an alternative to syslog. VII: Zones: Solaris Zones - as a major Solaris differentiator - got lots of love in terms of new features: - ZOSS - Zones on Shared Storage: Placing your zones to shared storage (FC, iSCSI) has never been this easy - via zonecfg. - parallell updates - with S11's bootenvironments: - Zones got RDSv3 protocol support for InfiniBand, and IPoIB support with Crossbow's anet (automatic vnic creation) feature. - NUMA I/O support for Zones: customers can now determine the NUMA I/O topology of the system from within zones. - Automated security/audit reporting, with builtin reporting templates e.g. for PCI (payment card industry) audits. - PAM is now configureable on a per-user basis instead of system wide, allowing different authentication requirements for different users - SSH in Solaris 11.1 now supports running in FIPS 140-2 mode, that is, in a U.S. government security accredited fashion. - SHA512/224 and SHA512/256 cryptographic hash functions are implemented in a FIPS-compliant way - and on a T4 implemented in silicon! That is, goverment-approved cryptography at HW-speed. - Generally, Solaris is currently under evaluation to be both FIPS and Common Criteria certified. IX. Networking, as one of the core strengths of Solaris 11, has been extended with: - Data Center Bridging (DCB) - not only setups where network and storage share the same fabric (FCoE, anyone?) can have Quality-of-Service requirements. DCB enables peers to distinguish traffic based on priorities. Your NICs have to support DCB, see the documentation, and additional information on Wikipedia. - DataLink MultiPathing, DLMP, enables link aggregation to span across multiple switches, even between those of different vendors. But there are essential differences to the good old bandwidth-aggregating LACP, see the documentation: - VNIC live migration is now supported from one physical NIC to another on-the-fly X. Data management: - FedFS, (Federated FileSystem) is new, it relies on Solaris 11's NFS referring mechanism to join separate shares of different NFS servers into a single filesystem namespace. The referring system has been there since S11 11/11, in Solaris 11.1 FedFS uses a LDAP - as the one global nameservice to bind them all. - The iSCSI initiator now uses the T4 CPU's HW-implemented CRC32 algorithm - thus improving iSCSI throughput while reducing CPU utilization on a T4 - Storage locking improvements are now RAC aware, speeding up throughput with better locking-communication between nodes up to 20%! XI: Kernel performance optimizations: - The new Virtual Memory subsystem ("VM2") scales now to 100+ TB Memory ranges. - The memory predictor monitors large memory page usage, and adjust memory page sizes to applications' needs - OSM, the Optimized Shared Memory allows Oracle DBs' SGA to be resized online XII: The Power Aware Dispatcher in now by default enabled, reducing power consumption of idle CPUs. Also, the LDoms' Power Management policies and the poweradm settings in Solaris 11 OS will cooperate. XIII: x86 boot: upgrade to the (Grand Unified Bootloader) GRUB2.. XIV: Improved viewing of per-CPU statistics of mpstat. This one might seem of less importance at first, but nowadays having better sorting/filtering possibilities on a periodically updated mpstat output of 256+ vCPUs can be a blessing. XV: Support for Solaris Cluster 4.1: The What's New document doesn't actually mention this one, since OSC 4.1 has not been released at the time 11.1 was. But since then it is available, and it requires Solaris 11.1. And it's only a "pkg update" away. ...aand I seriously need to stop here. There's a lot I missed, Edge Virtual Bridging, lofi tuning, ZFS sharing and crypto enhancements, Solaris 11.1 Documentation using the "Feedback" button there. Both the Solaris engineers and the documentation writers are eager to hear your input. Feel free to comment about this post too. Except that it's too long ;) wbr, charlie Your post is too long. :) Looks like we all have a lot of both reading and using to do here... Thanks for the maxi-mini update. ;) Posted by Nathan on November 01, 2012 at 04:12 AM CET # Here how i can securely migrate solaris10 production to solaris11 ? Posted by guest on January 04, 2013 at 09:19 PM CET # I'm not quite sure what you mean by *securely* migrating s10 to s11. You can't upgrade Solaris 10 to Solaris 11, too many things have changed (packaging, etc). What is your goal with the migration? Generally for consolidation there are two options: - You install Solaris 11 on the target platform, and migrate the Solaris 10 install (global or non-global zone) into a Solaris 10-branded zone running on Solaris 11. You can read about Solaris 10 branded zones in the documentation, here: Additionally, you can run these Solaris 10 branded zones in a Solaris 10-branded zonecluster fashion too, with Solaris Cluster 4.1, making the services HA. - The other option is, if you are consolidating HardWare platforms to migrate the Solaris 10 bare metal installation to an LDom on a T-SPARC platform: ...though the latter is not quite migration to S11, but rather virtualizing a physical-server installation. Posted by Karoly Vegh on January 04, 2013 at 09:30 PM CET #
https://blogs.oracle.com/orasysat/entry/what_s_new_in_solaris
CC-MAIN-2015-32
refinedweb
1,093
56.45
Hi, guys.I am new to c++ programming and I've got a question about the cin.ignore() function I found in a program that displays the number of digits in a number entered by the user. This is the code: Code:#include <iostream> using namespace std; int main() { unsigned int n; int count = n; while (true) { cout << "Please enter an integer: "; if (cin >> n) break; cin.clear(); cin.ignore( 1000, '\n' ); // I don't understand what's in the braces: 1000 and '\n' :confused: cout << " It's not correct! "; } cout << " You entered the number " << n << ".\n"; while ( n > 0 ) n /= 10,count ++ ; cout << "Your number has " << count << " digits."; return 0; } I really hope you can explain me that line with cin.ignore() ( I know that adding cin.ignore clears the new line from the stream but what is with 1000? )and when is the perfect time to use it and as well the while(true) loop used in the program. I really want to understand these things so please explain me . Thanks in advance !
https://cboard.cprogramming.com/cplusplus-programming/140259-cin-ignore.html
CC-MAIN-2017-17
refinedweb
175
83.15
The Data Science Lab Suppose you have a collection of e-mail messages from users of your product or service. You don't have time to read every message so you want to programmatically determine if the tone of each message is positive ("great service") or negative ("you guys are terrible"). This is an example of sentiment analysis. In this article I show you how to get started with sentiment analysis using the Keras code library. Take a look at the demo program in Figure 1. The demo uses the well-known IMDB movie review dataset. The dataset has a total of 50,000 reviews divided into a 25,000-item training set and a 25,000-item test set. Half of the reviews are positive and half are negative. The demo program creates and trains an LSTM (long, short term memory) network. LSTMs are deep neural networks that are designed specifically for sequence input, such as sentences which are sequences of words. The model achieves 90.25 percent accuracy on the training data (22,563 correct and 2,437 wrong) and 82.06 percent accuracy on the test data. After training, the model is used to classify a new, previously unseen tiny movie review of, "The movie was a great waste of my time." The prediction probability value is 0.1368 and because that value is less than 0.5, the model correctly predicts the review is negative. This article assumes you have intermediate or better programming skill with a C-family language and a basic familiarity with machine learning but doesn't assume you know anything about LSTM networks. All the demo code is presented in this article. The source code is also available in the download that accompanies this article. All normal error checking has been removed to keep the main ideas as clear as possible. Installing Keras Keras is a code library that provides a relatively easy-to-use Python language interface to the relatively difficult-to-use TensorFlow library. Installing Keras involves three one another. For my demo, I installed the Anaconda3 4.1.1 distribution (which contains Python 3.5.2), TensorFlow 1.7.0 and Keras 2.1.5. The Demo Program The clean simplicity of Notepad. Listing 1: The Sentiment Analysis Demo Program Structure # imdb_lstm.py # LSTM for sentiment analysis on the IMDB dataset # Anaconda3 4.1.1 (Python 3.5.2) Keras 2.1.5 TensorFlow 1.7.0 import numpy as np import keras as K import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' def main(): # 0. get started print("IMDB sentiment analysis using Keras/TensorFlow") np.random.seed(1) tf.set_random_seed(1) # 1. load data into memory # 2. define and compile LSTM model # 3. train model # 4. evaluate model # 5. save model # 6. use model to make a prediction if __name__=="__main__": main() The demo program is named imdb_lstm.py and it starts by importing the NumPy, Keras, TensorFlow and OS packages. You don't need to explicitly import TensorFlow, but the demo program does so just to be able set the global TensorFlow random seed. The OS package is used just to suppress an annoying startup message. Working with the raw IMDB data is difficult because it's structured as 50,000 individual text files where the sentiment (negative = 0, positive = 1) is part of each file name. However, the Keras library has a built-in sub-module named datasets that can import the IMDB training and test datasets: # 1. load data max_words = 20000 print("Loading data, max unique words = %d words\n" % max_words) (train_x, train_y), (test_x, test_y) = \ K.datasets.imdb.load_data(seed=1, num_words=max_words) The load_data() function reads all 50,000 movie reviews into memory. The seed parameter controls the randomization for the order of the reviews. The num_words parameter sets a limit on how many distinct words are allowed. Each movie review is preprocessed by converting words to all lower-case letters. All punctuation characters, except for the single-quote character, are removed. This retains important contraction words such as can't and don't. Each word of a review is converted into a unique integer ID where 4 is used for the most frequent word in the training data ("the"), 5 is used for the second most common word ("and") and so on. A value of 0 is reserved for padding. A value of 1 is used to indicate the beginning of a sequence/sentence. Words that aren't among the most common 20,000 words are assigned a value of 2 and are called out-of-vocabulary (OOV) words. A value of 3 is reserved for custom usage. After the reviews are encoded and loaded into memory, they receive additional processing: max_review_len = 80 train_x = K.preprocessing.sequence.pad_sequences(train_x, truncating='pre', padding='pre', maxlen=max_review_len) test_x = K.preprocessing.sequence.pad_sequences(test_x, truncating='pre', padding='pre', maxlen=max_review_len) The pad_sequences() function performs two operations. First, movie reviews that have more than 80 words are truncated to exactly 80 words in length by removing excess words from the beginning of the review. You can remove excess words from the end of reviews by specifying truncating='post'. Second, any movie review that has fewer than 80 words is padded up to exactly 80 words by adding 0 values to the beginning of the review. You can pad at the end of reviews by specifying padding='post'. Defining the LSTM Model The demo program prepares the creation of an LSTM model with this code: # 2. define model print("Creating LSTM model") e_init = K.initializers.RandomUniform(-0.01, 0.01, seed=1) init = K.initializers.glorot_uniform(seed=1) simple_adam = K.optimizers.Adam() embed_vec_len = 32 # values per word The e_init and init objects set up the way in which the LSTM weights and biases will be initialized. The demo program creates an Adam ("adaptive moment estimation") optimizer object. Adam is a very good general-purpose optimizer for many types of deep neural networks. Alternatives include RMSprop, Adagrad and Adadelta. Although it is possible to feed integer-encoded sentences directly to an LSTM network, better results are obtained by converting each integer ID into a vector of real values. For example, the word "the" has index value 4 but will be converted to a vector like (0.1234, 0.5678, . . 0.3572). This is called a word embedding. The idea is to construct vectors so that similar words, such as "man" and "male," have vectors that are numerically close. The length of the vector must be determined by trial and error. The demo uses size 32 but for most problems a vector size of 100 to 500 is more common. The LSTM network is defined like so:')) There are three main ways to create word embeddings for an LSTM network. One approach is to use an external tool such as Word2Vec to create the embeddings. A second approach is to use a set of pre-built embeddings such as GloVe ("global vectors for word representation"), which is constructed using the text of Wikipedia. The demo program uses the third approach, which is to create embeddings on the fly. These embeddings will be specific to the vocabulary of the problem scenario. After specifying an Embedding() layer, the demo program sets up an LSTM() layer. LSTMs are fantastically complex software modules. You can get a rough idea of how LSTMs work by examining the diagram in Figure 2. The x(t) object is the input at time t, which is a word embedding. The output is h(t). Unlike regular neural networks, LSTMs have state, which allows them to handle sentences where the next word depends on the previous words. In the diagram, c(t) is the cell state at time t. Notice that the output, h(t), depends on the current input x(t) as well as the previous output h(t-1) and the cell state c(t). Remarkable! The LSTM network has a final Dense() layer that crunches the output of the LSTM() layer down to a single numeric value between 0.0 and 1.0. An output value less than 0.5 maps to a classification of 0 which is a negative review, and an output greater than 0.5 maps to a positive (1) review. In situations where your sentiment analysis is multi-valued, you can use one-hot encoding such as negative = (1, 0, 0), neutral = (0, 1, 0), positive = (0, 0, 1). After the LSTM network is defined, it is readied for use: model.compile(loss='binary_crossentropy', optimizer=simple_adam, metrics=['acc']) print(model.summary()) The summary() method displays the number of weights and biases that the model has, as shown in Figure 1. The demo has 693,301 weights and biases, where the majority (20,000 distinct words * 32 vectors per word = 640,000) of them are part of the embedding layer. Training, Evaluating and Saving the LSTM Model The LSTM sentiment analysis model is trained with these statements: # 3. train model bat_size = 32 max_epochs = 3 print("\nStarting training ") model.fit(train_x, train_y, epochs=max_epochs, batch_size=bat_size, shuffle=True, verbose=1) print("Training complete \n") The batch size, 32, is a hyperparameter and a good value must be determined by trial and error. The demo program uses an artificially small number of training epochs, 3, to keep the size of the output display small. A more realistic value would be 10 to 100 epochs. The verbose=1 argument tells Keras to display loss/error and current model accuracy on every training epoch. After training completes, the model is evaluated: # 4. evaluate model loss_acc = model.evaluate(test_x, test_y, verbose=0) print("Test data: loss = %0.6f accuracy = %0.2f%% " % \ (loss_acc[0], loss_acc[1]*100)) The evaluate() method returns a list of values where the first value at index [0] is always the (required) loss function, which is binary cross entropy in this case. The remaining values in the list are optional metrics specified in the call to the compile() method, in this case, just the classification accuracy at index [1]. The trained model is saved using these statements: # 5. save model print("Saving model to disk \n") mp = ".\\Models\\imdb_model.h5" model.save(mp) This code assumes there is a sub-directory named Models. Keras saves models in the hierarchical data format (HDF) version 5, which you can think of as somewhat similar to a binary XML. A saved model can be loaded from a different program using the keras.models.load() method. Using the LSTM Model to Make a Prediction The demo program prepares a new, previously unseen movie review: # 6. use model print("New review: \'the movie was a great waste of my time\'") d = K.datasets.imdb.get_word_index() review = "the movie was a great waste of my time" Recall that the Keras format for movie reviews expects all lower-case letters, with all punctuation removed except the single-quote character. The get_word_index() function returns a Python dictionary object that was created from the 25,000-item training data. The dictionary is 1-base indexed and constructed by word frequency. For example, d["the"] = 1, d["and"] = 2. Next, the words in the new review are converted to integer ID values: words = review.split() review = [] for word in words: if word not in d: review.append(2) else: review.append(d[word]+3) Recall that words that are rare (not among the 20,000 most common) or aren't in the training data have a special ID value of 2. Also, each ID is offset by 3 to make room for special values 0, 1, 2 and 3. The demo concludes by truncating/padding the review and computing the predicted sentiment: review = K.preprocessing.sequence.pad_sequences([review], truncating='pre', padding='pre', maxlen=max_review_len) prediction = model.predict(review) print("Prediction (0 = negative, 1 = positive) = ", end="") print("%0.4f" % prediction[0][0]) The predict() method returns a single value in an array-of-arrays object, so the prediction probability is located at indices [0][0]. Wrapping Up Sentiment analysis is a very difficult problem. As recently as about two years ago, trying to create a custom sentiment analysis model wouldn't have been feasible unless you had a lot of developer resources, a lot of machine learning expertise and a lot of time. Instead, you'd likely have had to use a canned approach from a service such as Azure Cognitive Services text analytics. But now, even though sentiment analysis is a very challenging problem, the existence of neural network libraries like Keras with built-in LSTM functionality has made custom sentiment analysis feasible.
https://visualstudiomagazine.com/articles/2018/11/01/sentiment-analysis-using-keras.aspx
CC-MAIN-2022-40
refinedweb
2,100
57.57
Hello everyone, I need a little help from you guys. I need to find the position of some strings , these strings store in a file named "queryfile" , from an other file named "datafile". However, my programe just work on a single "word" , can't find the position of phrase or sentence. Thank you so much! my program #include <stdio.h> #include <string.h> int main() { FILE *queryfile; queryfile = fopen("op2query.txt","r"); FILE *datafile; datafile = fopen("op2data.txt","r" ); int i = 1; char word[99]; char search[99]; if(queryfile==NULL) { printf("Error in reading Query File"); } if(datafile==NULL) { printf("Error in reading Data File"); } while (!feof(queryfile)) { fscanf(queryfile,"%s", &search); while(!feof(datafile)){ fscanf(datafile,"%s", &word); if (strcmp(word,search)==0){ printf("\n %i %s ", i, search); rewind(datafile); i=1; break; } else i++; } } fclose(datafile); fclose(queryfile); return 0; } op2query.txt wisdom season age of foolishness op2data result 18 wisdom 40 season 16 age 5 of 24 foolishness THANK YOU!!!!!
https://www.daniweb.com/programming/software-development/threads/494973/i-need-a-little-help
CC-MAIN-2018-13
refinedweb
165
68.77
[ ] solprovider commented on COCOON-2068: ------------------------------------- Hi Carlsten, I changed the code and comment for this entry after thinking for a moment. Thanks for the quick response. My environment is SAP Portal. The best method to install Cocoon would be as a servlet in the WAS, but that is politically improbable so I am converting Cocoon to a PAR. ("Portal Archive" PAR = SAP Portal's corruption of the EAR standard. I have not investigated Sun's "Provider Archive" PAR.) A PAR may be more flexible than a servlet. SAP does not worry about standards so this will be fun. My effort should also discover issues typically unnoticed by people using the Jetty or Tomcat environments (as in yesterday's report.) Adding the correct directories to the ClassLoader would be good, but I have yet to find a method to create the directory paths to where the files are located. The files in a PAR are distributed to several directories. The SAP method is to use "ResourceBundles", but that is more customization than should be necessary. Next is architecting how to call getResource from ClassUtils using the ServletContext rather than the ClassLoader because the ClassLoader cannot find files in the JAR calling it. Creating a generic solution is difficult because Cocoon isolates the servlet class. I may void the warranty with that patch. > Add failover for loading classes. > --------------------------------- > > Key: COCOON-2068 > URL: > Project: Cocoon > Issue Type: Improvement > Components: * Cocoon Core > Affects Versions: 2.1.10 > Reporter: solprovider > Priority: Minor > > The ClassLoader from currentThread.getContextClassLoader() was unable to retrieve classes in my environment. Add fallback to standard Java class loading. > NOTE: The two "set" lines would work in either order. I believe Cocoon is using a custom ClassLoader to dynamically load changes so the custom method must be tried first. (The auto-reload ability will be lost for environments using the fallback, but at least they will be able to use Cocoon.) > public class ClassUtils{ > public static Class loadClass(String className) throws ClassNotFoundException{ > Class ret; > try{ > ret= ClassUtils.getClassLoader().loadClass(className); > }catch(ClassNotFoundException e){ > ret= Class.forName(className); > } > return ret; > } > } -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200705.mbox/%3C20842183.1180018516511.JavaMail.jira@brutus%3E
CC-MAIN-2015-22
refinedweb
368
58.28
dirent.h - format of directory entries #include <dirent.h> The internal format of directories is unspecified. The <dirent.h> header defines the following data type through typedef: - DIR - A type representing a directory stream. It also defines the structure dirent which includes the following members: ino_t d_ino file serial number char d_name[] name of entry The type ino_t is defined as described in <sys/types.h>. The character array d_name is of unspecified size, but the number of bytes preceding the terminating null byte will not exceed {NAME_MAX}. The following are declared as functions and may also be defined as macros. Function prototypes must be provided for use with an ISO C compiler. int closedir(DIR *); DIR *opendir(const char *); struct dirent *readdir(DIR *); int readdir_r(DIR *, struct dirent *, struct dirent **); void rewinddir(DIR *); void seekdir(DIR *, long int); long int telldir(DIR *); None. None. closedir(), opendir(), readdir(), rewinddir(), seekdir(), telldir(), <sys/types.h>.
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/dirent.h.html
crawl-003
refinedweb
154
55.64
Variables in Python generally have a lifetime of their own. Or rather, the Python runtime interpreter handles object lifetime with automated garbage collection, leaving you to concentrate on more important things. Like Resource lifetime, which is much more interesting. Python provides some facilities for handling the deterministic clean-up of certain objects, because sometimes it’s necessary to know that it has happened at a specific point in a program. Things like closing file handles, releasing sockets, committing database changes – the usual suspects. In this article I will explore Python’s tools for managing resources in a deterministic way, and demonstrate why it’s easier and better to use them than to roll your own. Why you need it Python, like many other languages, indicates runtime errors with exceptions, which introduces interesting requirements on state. Exceptions are not necessarily visible directly in your code, either. You just have to know they might occur. Listing 1 shows a very basic (didactic) example. If an exception occurs between lines (1) and (3), the data won’t get committed to the database, the connection to the database will not be closed, and will therefore ‘leak’. This could be a big problem if this function or other functions like it get called frequently, say as the backend to a large web application. This wouldn’t be the best way to implement this in any case, but the point is that the db.execute() statement can throw all kinds of exceptions. You might then try to explicitly handle the exceptions, as shown in Listing 2, which ensures the database connection is closed even in the event of an exception. Closing a connection without explicitly committing changes will cause them to be rolled back. It is a bit messy, and introduces some other questions such as: what happens if the sqlite3.connect method throws an exception? Do we need another outer-try block for that? Or expect clients of this function to wrap it in an exception handler? Fortunately, Python has already asked, and answered some of these questions, with the Context Manager. This allows you to write the code shown in Listing 3. The connection object from the sqlite3 module implements the Context Manager protocol, which is invoked using the with statement. This introduces a block scope, and the Context Manager protocol gives objects that implement it a way of defining what happens when that scope is exited. In the case of the connection object, that behaviour is to commit the (implicit, in this case) transaction if no errors occurred, or roll it back if an exception was raised in the block. Note the explicit call to db.close() outside of the with statement’s scope. The only behaviour defined for the connection object as Context Manager is to commit or roll back the transaction when the scope is exited. This construct doesn’t say anything at all about the lifetime of the db object itself. It will (probably) be garbage collected at some indeterminate point in the future. You can do it too This customer database library might have several functions associated with it, perhaps including facilities to retrieve or update customer details, report orders and so on. Perhaps it’s better represented as a type, exposing an interface that captures those needs. See Listing 4 for an example. Unfortunately, the line containing the with statement provokes an error similar to this: File "customerdb.py", line 21, in <module> with Customers( dbname ) as db: AttributeError: __exit__ You can’t use with on just any type you create. It’s not a magic wand, either: the changes won’t get committed to the database if commit() is not called! However, the Context Manager facility isn’t limited to just those types in the Python Standard Library. It’s implemented quite simply, as seen in Listing 5. The __init__() method is still there, but just saves the name away for later use. When the with statement is executed, it calls the object’s __enter__() method, and binds the return to the as clause if there is one: in this case, the db variable. The main content of the original construction method has been moved to the __enter__() method. Lastly, when the with statement block scope is exited, the __exit__() method of the managed object is called. If no exceptions occurred in the block, then the three arguments to __exit__() will be None. If an exception did occur, then they are populated with the type, value and stack trace object associated with the exception. This implementation essentially mimics the behaviour of the sqlite3 connection object, and rolls back if an exception occurred. Returning a false-value indicates to the calling code that any exception that occurred inside the with block should be re-raised. Returning None counts – and is only explicitly specified here for the purposes of explaining it. A Python function with no return statement is implicitly None. Returning a true-value indicates that any such exception should be suppressed. Consistent convenience Having to explicitly close the connection after the block has exited is a bit of a wart. We could decide that our own implementation of the __exit__() method invokes close() on the connection object having either committed or rolled back the changes, but there is a better way. The contextlib module in the Python Standard Library provides some convenient utilities to help with exactly this, including the closing function, used like this: from contextlib import closing with closing( Customers( dbname ) ) as db: db.addCustomerOrder( customer, order ) It will automatically call close() on the object to which it’s bound when the block scope is exited. Python File objects also have a Context Manager interface, and can be used in a with statement too. However, their behaviour on exit is to close the file, so you don’t need to use the closing utility for file objects in Python. with open( filename ) as f: contents = f.read() So much for consistency! It’s a little odd having to know the internal behaviour of a given type’s Context Manager implementation (and the documentation isn’t always clear on which types in the Standard Library are Context Managers), but sometimes the price of convenience is a little loss of consistency. To reiterate the point about lifetime, even though the connection and file objects in the previous two examples have been closed, the lifetimes of the objects has not been affected. When one isn’t enough Sometimes it’s useful to associate several resources with a single Context Manager block. Suppose we want to be able to import a load of customer order data from a file into the database using the facility we’ve already made. In Python 3.1 and later, this can be achieved like this: with closing( Customers( dbname ) ) as db, \ open( 'orders.csv' ) as data: for line in data: db.addCustomerOrder( parseOrderData( line ) ) If you’re stuck using a version of Python earlier than that, you have to nest the blocks like this: with closing( Customers( dbname ) ) as db: with open( 'orders.csv' ) as data: for line in data: db.addCustomerOrder( parseOrderData( line ) ) Either syntax gets unwieldy very quickly with more than two or three managed objects. One approach to this is to create a new type that implements the Context Manager protocol, and wraps up multiple resources, leaving the calling code with a single with statement on the wrapping type, as shown in Listing 6. That really is a little clunky, however you look at it, since it’s fairly obvious that the class has multiple responsibilities, and exposes the managed objects publicly, amongst other things. There are better ways to achieve this, and we will return to this shortly. Common cause Having implemented a (basic) facility to import data from a file to our database, we might like to extend the idea and optionally read from the standard input stream. A simple protocol for this might be to read sys.stdin if no filename is given, leading to code like this: with options.filename and \ open( options.filename ) or sys.stdin as input: # do something with the data That’s all very well, but is a little arcane, and closing the standard input handle when it completes might be considered bad manners. You could go to all the bother of reinstating the standard input handle, or redirecting it some other way, but that too seems more complicated than what is required. Python’s contextlib module has another handy utility to allow you to use a generator function as a Context Manager, without going to the trouble of creating a custom class to implement the protocol. It is used to decorate a function, which must yield exactly one value to be bound to the as clause of a with statement. Actions to perform when the block is entered are put before the yield, actions to perform when the block is exited are put after the yield. It follows the basic pattern shown in Listing 7: (1) will be called when the with statement is entered. It’s the equivalent of the __enter__() method (2) will be called when the block is exited. It’s the equivalent of the __exit__() method This allows us to define a couple of factory functions for our inputs, as shown in Listing 8. Since opening a ‘real’ file returns an object that is already a Context Manager, the function for that isn’t decorated. Likewise, since we do not want to perform any action on the sys.stdin object on exit, that function has no behaviour after the yield. It should be clear that the Context Manager protocol is more general purpose than just for performing some clean-up action when leaving a scope. Exception safety is the primary purpose of the Context Managers, but the __enter__() and __exit__() methods can contain any arbitrary behaviour, just as the decorated function can perform any actions before and after the yield statement. Examples include tracking function entry and exit, and logging contexts such as those Chris Oldwood shows in C# [Oldwood]. Many and varied As previously mentioned, it’s sometimes necessary to manage multiple resources within a single block. Python 3.1 and later support this by allowing multiple Context Manager objects to be declared in a single with statement, but this becomes cluttered and unmanageable quickly. You can, as we demonstrated, create your own Context Manager type, but that too can be less than ideal. Once again, Python 3.3 answers the question with another contextlib utility, the ExitStack. It manages multiple Context Manager objects, and allows you to declare them in a tidy (and indentation-saving) manner. See Listing 9. Objects have their __exit__() method called, in the reverse order to which they were added, when the block is exited. The ExitStack can manage a runtime-defined collection of context managers, such as this example taken directly from the Python 3.4 documentation [Python]: with ExitStack() as stack: files = [ stack.enter_context( open( fname ) ) \ for fname in filenames ] # All opened files will automatically be closed # at the end of the with statement, even if # attempts to open files later in the list raise # an exception Conclusion Python’s Context Managers are a convenient and easy-to-use way of managing Resource Lifetimes, but their utility goes beyond that, due to the flexible way they are provided. The basic idea is not a new one – even in Python, where it was first introduced in version 2.5 – but some of these facilities are only available in later versions of the language. The examples given here were tested using Python 3.4. Exception safety facilities like the Python Context Manager are common to many languages that feature the use of exceptions to indicate errors, because this introduces the need for some local clean-up in the presence of what is (in effect) a non-local jump in the code. They are, however, useful for things beyond this need, and Python provides several useful utilities to help manage the complexity this brings. References [Python] Python 3.4 Documentation. [Oldwood] Oldwood, Chris. Causality,
https://accu.org/index.php/journals/2250
CC-MAIN-2019-22
refinedweb
2,022
61.36
If you run Exchange PowerShell commands remotely, it goes into the Exchange's IIS first, from there into WinRM and yet from there to the server's local PowerShell. C:\netsh http show servicestate Snapshot of HTTP service state (Server Session View): ----------------------------------------------------- Server session ID: FF00000120000001 Version: 1.0 State: Active Properties: Max bandwidth: 4294967295 Timeouts: Entity body timeout (secs): 120 It means, the remote WinRM serer knows immediatelly tha tyou do not have access. The HTTPS 5986 is not created by default even on Windows 2012. If you're receiving access denied errors and you're working with a work group, you should look at the options for allowing Basic authentication or Digest Authentication, possibly the option for unencrypted The error is the same. –kubusz Mar 2 '11 at 12:50 add a comment| up vote 0 down vote If you execute this command in Powershell console: PS C:\Windows\system32> winrm quickconfig Small interruption - sorry for not mentioning it yet. Visit our UserVoice Page to submit and vote on ideas! And as soon as I type, winrm quick config, I receive access is denied - So anybody here who already used Win 7's WinRM? Monday, June 14, 2010 1:24 PM Reply | Quote 1 Sign in to vote The administrator account used for the console must have a non blank password. This indicates that the target server failed to decrypt the ticket provided by the client. I got the following error message: Windows could not start the Windows Remoteverwaltung(WS-Verwaltung) on local computer.Error 1079: The account specified for this service is different from thefrom the account specified for But we are not particually intersted with the IIS WinRM Extension here, so forget about it. Note that computers in the TrustedHosts list might not be authenticated. –kubusz Mar 2 '11 at 12:41 | show 3 more comments up vote 0 down vote I have seen it Worked like a charm! Set-wsmanquickconfig Access Is Denied The second are WMI namespace permissions. You can download it for Windows 7 and Windows Server 2008 as well, but I would rather not do it as it is not yet supported with Exchange 2012, SharePoint 2010 So I downloaded the Microsoft Windwos Server 2003 Support Pack and used the "setspn.exe". In the following text, we will cover mainly WinRM 2.0, which is included with Windows 7 and Windows Server 2008 R2 while you can download it (as part of Windows Management I had this issue and did not have a blank password. You list some basic service info from command line by using SC command and its parameters such as QUERY, QC or QSIDTYPE as in the following output: C:\sc query winrm SERVICE_NAME: Winrm Logs To jump to the last selected command use Ctrl+]. share|improve this answer answered Dec 12 '11 at 7:30 Jay Bazuzi 420412 1 windows 7 home, blank password was my issue! –Chris Stavropoulos Dec 15 '12 at 20:35 add a Keep in mind what you are doing, opening WinRM via HTTP/HTTPS. Only then you need to adjust WMI namespace security. Then, as yourself, launch a cmd prompt, andrunas /user:Administrator cmd. Winrm Error Number: -2147024891 0x80070005 If youput in"gpedit.msc" at a command line, that takes you to a configuration settings tool that will allow you to configure WinRM. Winrs Error Access Is Denied I got the following error message: Windows could not start the Windows Remoteverwaltung (WS-Verwaltung) on local computer. Wednesday, April 07, 2010 7:31 PM Reply | Quote 1 Sign in to vote "Run As" local, not Domain Administrator After many sleepless nights it solved this error for me!!!!! ))))))) I didn't need to start cmd with elevated privilages to perform "winrm get" command. I am running it as an elevated user with the same result. You would also get the same output on Windows 2008 R2 and older system if you enabled remote access with the winrm qc (or exactly winrm quickconfig): C:\winrm enumerate winrm/config/listener Listener Winrm Permissions Here are the steps I took. Wednesday, July 11, 2012 7:54 PM Reply | Quote 0 Sign in to vote I have found for those trying to configure PS and WinRM on their local machine for remote See here: Here are the steps I took: 1) Using a local account within Local Administrators group, Right-click CMD.EXE, 'Run as Administrator' 2) Within Elevated CMD prompt ran the following weblink The most obvious way is to right click on the Command Prompt option in the menu and select the "Run as Administrator" option in the menu that comes up. In short, run the following from a command prompt (launched as Administrator): > reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f After that, re-launch the Powershell prompt as admin Enter Pssession Access Denied This problem occurs because two or more computer accounts have the same service principal name (SPN) registered. My password is not blank Does one of those fix your issue? Not only Windows 2012 have the WinRM listener enabled, they also have a firewall exception for the port opened by default. Enabling firewall exception for WS-Management traffic (for http only) Steps to fix: 1) Click on start menu >> Administrative tools >> Windows Firewall and Advanced security 2) Click on inbound rules I have Windows 7 installed and configure it for workgroup not domain. Winrm Get Config This includes: 1. Output N in base -10 What are the benefits of an oral exam? Enabling firewall exception for WS-Management traffic (for http only). –kubusz Mar 2 '11 at 12:40 Do you want to continue? [Y] Yes [A] Yes to All [N] No [L] It first authenticates the user and verify the SDDL for the particular provider before forwarding requests to the provider at all. check over here Probably because of its standard and simple to implement HTTP SOAP protocol. HTTP.SYS listening technology is the very important part of WinRM operation, so you should be able to query and verify its state before we proceed with actual WinRM configuration: C:\netsh http I believe it's doing exactly the same as Enable-PSRemoting in PowerShell –user978511 Nov 28 '11 at 8:08 It gives the same result: Access is denied –Peter Lundsby Nov 28 I wanted to make it as simple as possible. Maybe it remained in Windows 2012 to maintain backward compatibility. Good luck. client (in a workgroup) and a Server 2008 R2 machine. Examples I have already mentioned are WMI, PowerShell, event forwarding or server manager. What's the male version of "hottie"? All rights reserved.Newsletter|Contact Us|Privacy Statement|Terms of Use|Trademarks|Site Feedback Developer Network Developer Network Developer :CreateViewProfileText: Sign in Subscriber portal Get tools Downloads Visual Studio SDKs Trial software Free downloads Office resources SharePoint What the hell is SDDL? PowerShell, WMI or the Event Forwarding are all implemented as the WinRM providers. Much thanks to Jaewoo Park for his answer. All the same, WinRM registers /WSMan URI with HTTP.SYS. If you install Windows Management Framework 3.0 on Windows 2008 R2, there is no built-in group called Remote Management Users and WMF 3.0 so installs the WinRMRemoteWMIUsers__ group manually. Run cmdas an administratorand issue "reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f"and then "winrm quickconfig" this should work.
http://smartnewsolutions.com/access-is/winrm-quickconfig-message-access-is-denied.html
CC-MAIN-2017-26
refinedweb
1,243
50.16
I spent the week before last wondering around the Microsoft campus talking to the .NET team and various Program and Product Managers. Redmond campus is beautiful but Seattle can be a little grey and wet. Here's a strange thing: I have a friend from Australia who has just spent 8 weeks travelling around Europe and North America. Even though Europe has experienced the biggest floods in 50 years, my friend saw no rain - there was literally a hole in the clouds that followed him around. He comes to Toronto and instead of bleak, grey rainy icy days we get sunshine. Up to Montreal and the snow stops and again, sunshine. And back home in Australia? Torrential rain and floods. Our hometown has had only 3 days in the last month where it hasn't rained. So when he tells me he will be in Seattle the same week I don't bother packing the umbrella - even though it's winter and scant weeks ago Seattle was under water. He's a mystery, but he makes travelling a whole lot more convenient. Thanks Alan - love your work. So what's the big news this week? Well, nothing really huge, just incremental titbits on the continuing .NET theme. The .NET SDK and Visual Studio.NET are now in beta (and I’m sure many of you have now downloaded these), with beta 2 due sometime in March. They are working on getting final versions as soon as possible with a summer release the most likely date. Visual Studio.NET beta 1 is a massive improvement on the PDC release bits (I think the change file is 9Mb!). It's a lot more stable and you can actually do real things, instead of being forced to stick to the tried and tested demos. Even so, you'll still find problems with the beta. It still crashes sometimes, it's still a little slow in places, and some of the APIs will also change, but some of the pop-up error messages are pretty amusing. Remember - it's a beta! If there were no problems with it then it would have already been released. A lot of names are changing. WinForms are now Windows Forms (due to a pesky little name conflict with another company) and this name will again change soon. ASP+ is now ASP.NET, ADO+ is now ADO.NET, and GDI+ is still GDI+. I predict it will soon be GDI.NET. Remember - you heard that first here! Some namespaces have changed between PDC and beta 1, and will again change between beta 1 and beta 2. I'll try and put my sketchy notes into some semblance of order. Many of my notes are filled with strange snippets like "Grilled cheez!!" and "Steal all the mouse balls at MS and hold them to ransom. Mwahaha!". There was some long days and the coffee in Seattle is a tad stronger than I'm used to... The Microsoft.
http://www.codeproject.com/Articles/848/Redmond-Again-Part-1?fid=1710&df=90&mpp=10&sort=Position&spc=None&tid=13476
CC-MAIN-2014-42
refinedweb
497
83.36
Lemon is an LALR(1) parser generator for C. It does the same job as "bison" and "yacc". But Lemon is not a bison or yacc clone. Lemon uses a different grammar syntax which is designed to reduce the number of coding errors. Lemon also uses a parsing engine that is faster than yacc and bison and which is both reentrant and threadsafe. (Update: Since the previous sentence was written, bison has also been updated so that it too can generate a reentrant and threadsafe parser.) Lemon also implements features that can be used to eliminate resource leaks, making*", requests it (via the %extra_argument directive),: 1 ParseTree *ParseFile(const char *zFilename){ 2 Tokenizer *pTokenizer; 3 void *pParser; 4 Token sToken; 5 int hTokenId; 6 ParserState sState; 7 8 pTokenizer = TokenizerCreate(zFilename); 9. (All error-handling code is omitted)./or underscore characters that begins with.: The destructor can do whatever it wants with the value of the non-terminal, but its design is to deallocate memory or other resources held by that non-terminal.. More commonly, the value is used to build some larger structure, and we don't want to destroy it, which is why the destructor is not called in this circumstance. Destructors help avoid memory leaks by automatically freeing allocated objects when they go out of scope. To do the same using yacc or bison is much more difficult.(). The %fallback directive specifies an alternative meaning for one or more tokens. The alternative meaning is tried if the original token would have generated a syntax error. The %fallback directive was added to support robust parsing of SQL syntax in SQLite. The SQL language contains a large assortment of keywords, each of which appears as a different token to the language parser. SQL contains so many keywords that it can be difficult for programmers to keep up with them all. Programmers will, therefore, sometimes mistakenly use an obscure language keyword for an identifier. The %fallback directive provides a mechanism to tell the parser: "If you are unable to parse this keyword, try treating it as an identifier instead." The syntax of %fallback is as follows: %fallback ID TOKEN... . In words, the %fallback directive is followed by a list of token names terminated by a period. The first token name is the fallback token — the token to which all the other tokens fall back to. The second and subsequent arguments are tokens which fall back to the token identified by the first argument. The %if, %ifdef, %ifndef, %else, and %endif directives are similar to #if, #ifdef, #ifndef, #else,.
http://chiselapp.com/user/andy/repository/sqlite-andy/doc/trunk/doc/lemon.html
CC-MAIN-2021-10
refinedweb
428
54.42
Le jeudi 30 septembre 2004 à 20:55 +0200, Jaime Peñalba a écrit : > Hi again, > > I have been looking trought different debian versions, and that "# > define CLONE_NEWNS 0x00020000" is present on sid (unstable), but not > in "woody", the stable version wich is the one that servers are > running. > > So i was wondering if i include that define for files > /usr/include/linux/sched.h and /usr/include/bits/sched.h on debian > woody that seems to use the same addresses on sid for the present > defines, could cause any worse to further compilations or something, i > dont think so, but please let me know, because as i said im not a > skilled c coder. > woody doesn't seem to be a good choice to run a 2.6 kernel plus udev anyway, so I won't support that in the trunk. sarge should be ok, like sid. but you can easily workaround the problem by adding the following at the head of the main.c : #ifndef CLONE_NEWNS #define CLONE_NEWNS 0x00020000 #endif regards, -- christophe varoqui <christophe varoqui free fr>
http://www.redhat.com/archives/dm-devel/2004-September/msg00034.html
CC-MAIN-2014-49
refinedweb
178
78.28
From: Marco Costalba (mcostalba_at_[hidden]) Date: 2008-06-04 16:43:15 Under fusion namespace we can write vector<int, double, string> v(1, 2.4, "hello"); print_type( at_c<2>(v) ); // prints string print_value( at_c<2>(v) ); // prints "hello" But number 2 in our example must be a compile time constant, we cannot write int idx = 2; at_c<idx>(v); // compile error here Sometime accessing an element in a fusion sequence indexed by a runtime variable could be useful, something like the following: vector<int, double, string> v(1, 2.4, "hello"); int idx; cout << "Give me an index" << endl; cin >> idx; apply_at(v, idx, print_type); // prints string if idx == 2, or int if idx == 0 apply_at(v, idx, print_value); // prints "hello" if idx == 2, or 1 if idx == 0 Because I didn't find something similar in fusion and I needed that for code I'm writing I cooked up my solution, it's very easy and if someone is interested I can post it. Marco P.S: If someone could point me to an already available solution it would be appreciated ;-) I just missed it. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2008/06/138393.php
CC-MAIN-2020-50
refinedweb
209
57.1
From: David Cameron (dave.bc_at_[hidden]) Date: 2005-11-02 03:04:04 I've been writing some code to serialize and deserialize boost::numeric::ublas::matrixs. While writing unit tests for it I found out about the boost::numeric::ublas::equals function in matrix_assign.hpp. I was relieved, because I had previously been using a templated function to compare matrices. Unfortunately, it doesn't work for me with matrix<int>s. Consider the following cppunit test code: void testMatrixEqualsOperator() { using namespace boost::numeric::ublas; matrix<double> test; test.resize(3,3); CPPUNIT_ASSERT( equals(test,test) ); matrix<int> test1; test.resize(4,4); CPPUNIT_ASSERT( equals(test1,test1) ); } The first four lines work. Adding the next three lines causes the unit tests to fail with an Abort. This is not the standard way CppUnit records a failed test, it must be something failing inside the call to equals(). Previous messages referring to the equals() function argued that it wasn't ready for use because there was rarely a need to compare matrices in real applications. I would argue that it should be working as intended, if only to allow for proper unit testing of code that uses matrices. Here is the function I have been using instead. It works well for me with doubles and ints. Although, I imagine it is not particularly fast. E is for Element. template<class E> bool areMatricesEqual( boost::numeric::ublas::matrix<E> lhs, boost::numeric::ublas::matrix<E> rhs) { using boost::numeric::ublas; if (&lhs == &rhs) return true; if (lhs.size1() != rhs.size1()) return false; if (lhs.size2() != rhs.size2()) return false; typename matrix<E>::iterator1 l(lhs.begin1()); typename matrix<E>::iterator1 r(rhs.begin1()); while (l != lhs.end1()) { if (*l != *r) return false; ++l; ++r; } return true; } I am using gcc-3.3 on ubuntu-5.04 running on an AthlonXP. I'd be happy to provide any more info to help track down the bug. Assuming it is one. -- David Cameron University of British Columbia Boost list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
http://lists.boost.org/Archives/boost/2005/11/96235.php
crawl-002
refinedweb
360
53.78
Buffer overflows are some of the oldest and most important attacks against computer technology. These types of attacks are commonly associated with low level languages (like C and C++), but are not exclusive to them. Despite the importance of understanding this type of attack, there are still a large number of technical people who still don't fully understand it. Hopefully, this article will give you some basic insight into how buffer overflows work and why they are useful/dangerous. This guide will attempt to give you a very basic understanding on the concepts behind these attacks, but please bare in mind: due to a variety of protection mechanisms that are built into modern systems it is actually much more difficult to exploit modern systems using these attacks than it used to be. (If you are reading this to play The Hacker's Sandbox, then everything here is still applicable.) So what is a buffer overflow? Buffer overflows are attacks that allow for an unintentional (by design) change in the logical flow of an application. When information needs to be stored in memory, it will either land in the stack, or (for long-term and dynamic data) the heap. (This article will deal specifically with Stack overflows, though similar concepts will apply to the heap as well.) The stack is a region of memory that gets created on every thread that your application is running on. It works using a Last-In, First Out (LIFO) model, where data is said to be either pushed onto or popped off of the stack. When an application wants to store data into a buffer, it will allocate memory on the stack to be filled for that purpose. It can later be manipulated or moved to the heap as needed. The danger comes in when the application tries to write more data to the stack than has been allocated for the buffer. In this instance, an application can overwrite other important locations in memory, causing the program to corrupt or the logical flow of the program to change. Examining the stack To understand this a little better, let's take a look at an abstraction of the stack. You can easily visualize the stack using the following parts: [BUFFER][STACK_FRAME_POINTER][RETURN_ADDRESS] Image that you have three cards that you want to put down in the buffer. Card A, Card B, and Card C. You can push them down one at a time, first Card A, then Card B, last Card C. You will now have a buffer on the stack that looks like this: - Card C - Card B - Card A If you wanted to then access Card B, first you would have to pop Card C off of the stack in order to access it. This is the basis for memory management on the stack, and is crucial to understand for understanding buffer overflows. We can take this a step further and see how a real-world function would work with the stack. I am going to use the mmap() system function exposed by the Linux kernel. Looking at the man pages, you can see the function looks like this: void *mmap( void *addr, size_t length, int prot, int flags, int fd, off_t offset ); If we were to call this function, first we would push the return variable, then we would push each argument onto the stack in reverse order, and finally we would make the call to mmap(). (In this case, the function is void, so no return variable will be pushed.) Abstractly, it would look something like this: PUSH off_t offset PUSH int fd, PUSH int flags, PUSH int prot, PUSH size_t length, PUSH void *addr, CALL mmap Once finished, our actual stack will look like this: void *addr, size_t length, int prot, int flags, int fd, off_t offset Don't worry about the actual data here, the important part is that you understand how the stack works to be able to understand how to exploit it. This is all well and good, but how does it actually help you to control the flow of a program? Well, In addition to holding the buffer, the stack also holds a frame pointer, and the address to return to after a function has finished executing. Let's take another look at that stack: [BUFFER][STACK_FRAME_POINTER][RETURN_ADDRESS] Did you notice it? The buffer is placed on the stack before the return address. If we could keep pushing data onto to buffer until it overflows into the RETURN_ADDRESS, we would change where the program thinks it should be jumping back to. A little bith of math Ok, so now we know the theory behind overflowing buffers, but how do we know how much data we need to actually exploit this? The truth is, that depends on a few factors, such as your architecture. Computers of different architectures will follow this same stack model, but their memory allocation won't always be the same. You see, every machine architecture has a minimum amount of storage it needs to allocate. Think of it in terms of blocks. A system can only reserve 1 block at a time. If your program were to request only half a block worth of data, the system would need to reserve a full block to satiate that request. On a 32 bit system, this block is going to be 32 bits. On a 64 bit system, each block will be 64 bits. So if we were to request 1 byte of data (8 bits), on a 32 bit system, we would end up reserving 4 bytes (32 bits), while on a 64 bit system, we would end up reserving 8 bytes (64 bits). In order to actually change the RETURN_ADDRESS, first we would need to fill our complete buffer (all of the space reserved for us), then we would need to overflow the stack pointer (this will usually be 1 block of space), and finally we would be able to overwrite the RETURN_ADDRESS (also 1 block in size.) To complicate this matter more, modern compilers will often use padding on the buffers which will depend on various factors (such as data type and size) which will effect the reserved memory size. Often, the easiest way to determine how large your buffer is would be to open your application in a debugger and actually look at the asembly. If you are playing The Hacker's Sandbox, assume that there is no padding from the compiler. Some practical examples The following is a small C application (overflow.c) which will have no measures in place to protect it from buffer overflows. #include <string.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { char buf[10]; strcpy(buf,argv[1]); return 0; } void the_shell() { printf("pwned! "); system("/bin/sh"); } This program is pretty simple. It takes the first argument into the program and places that into a buffer that is 10 bytes long. Notice that there is also a function called the_shell() which never actually gets called. The code exists inside of it, however, to spawn a shell running as the owner of the program. (The truth is, this would be a pretty useless program in real life, but it suits our demonstration very well.) We could easily try to compile this into a program called overflow. For the purposes of this demonstration, we will be compiling on a 32 bit architecure: $ gcc -o overflow overflow.c Note: This compile would be incomplete on a modern machine. Modern compilers, like gcc, would have multiple mechanisms in place, like a stack guard and NX memory regions, which you would need to disable and/or bypass in order to successfully exploit your binaries. Now, we can try playing around with this for a bit. If we passed an argument of 10 characters (say 0000000000), we will notice the program does nothing, and simply exists. However, if we pass a much longer argument, of say 30 characters, it will crash. The application crashes because key pieces of data become corrupt (like our return address, which likely now points to a non-existant region of memory), and the logical flow of the program can not continue. So how do we send just enough data to overflow the stack and change the flow of execution without crashing the program? Let's try to fill the stack just enough to trick it into returning to our hidden function the_shell(). Conceptually, we will need to fill the stack so it looks like this on our 32 bit system: [garbage data] 12 bytes [garbage data] 4 bytes [address of the_shell] 4 bytes Remember, when the buffer requests 10 bytes, the smallest amount of 32 bit blocks (4 bytes) we can use is 3. Thus, 4 bytes X 3 = 12 bytes. First, we would fire up our binary in a debugger. We'll use gdb for this example; just launch it against our executable to get an interactive debugging shell: $ gdb overflow (gdb) We know from our source example that we want to try to find the location of the_shell() to fire off our attack. We can simply use gdb's disassembly command to dump out that function, and see what address the begining of the function has been mapped to. (gdb) disas the_shell Dump of assembler code for function the_shell: 0x080484a4 <+0>: push %ebp 0x080484a5 <+1>: mov %esp,%ebp 0x080484a7 <+3>: sub $0x18,%esp 0x080484aa <+6>: movl $0x8048560,(%esp) 0x080484b1 <+13>: call 0x8048350 <puts@plt> 0x080484b6 <+18>: movl $0x8048567,(%esp) 0x080484bd <+25>: call 0x8048360 <system@plt> 0x080484c2 <+30>: leave 0x080484c3 <+31>: ret End of assembler dump. (gdb) Here, we can see that the entry point for the_shell is 0x080484a4. We're almost there! Before we can execute our attack, we need to push the address onto the stack in the correct order. Remember, our input is being placed on the stack by strcpy() 1 byte at a time. As a result, our bytes are going to look reversed in a dump from the way we would expect to see it. Therefore, we are going to need to input the bytes (one at a time) in reverse order: 0xa4 0x84 0x04 0x08 Putting this all together Finally, we're ready to launch the attack. We'll need to send garbage data to overflow the buffer (12 bytes for the buffer + 4 bytes for the SFP), and then our payload. We can easily just use 0's for our garbage data. Unfortunately, 0x08 and 0x04 are not printable characters, so we will need to find some way to inject these bytes into our program. A lot of hackers tend to like using a C, Perl, or Python program to do this. Personally, I just tend to use the echo command inside my Bash shell (but feel free to use whatever suits you best). Using the -e flag for echo, I can allow escaped sequences in my strings, and -n will suppress appending newline characters. $ ./overflow 0000000000000000$(echo -ne "xa4x84x04x08") pwned! $ Success! We've been able to alter the flow of execution in our binary to run the hidden shell code. Again, if if you trying this on a modern system, there are a few more safe guards that need to be taken into consideration before this will work. For example, you would probably need to disable the NX flag from your binaries (you can use execstack on Linux systems to do this.) But if you are playing The Hacker's Sandbox, you won't need to worry about any of that. For additional information on running buffer overflows against modern systems, I would recommend reading Smashing the Stack in 2011.
http://www.unix-ninja.com/
CC-MAIN-2014-42
refinedweb
1,948
66.98
Posts Tagged ‘raspberry pi’. Spectre Attacks on ARM Devices Introduction I predicted that 2018 would be a very bad year for data breaches and security problems, and we have already started the year with the Intel x86 specific Meltdown exploit and the Spectre exploit that works on all sorts of processors and even on some JavaScript systems (like Chrome). Since my last article was on Assembler programming and most of these type exploits are created in Assembler, I thought it might be fun to look at how Spectre works and get a feel for how hackers can retrieve useful data out of what seems like nowhere. Spectre is actually a large new family of exploits so patching them all is going to take quite a bit of time, and like the older buffer overrun exploits, are going to keep reappearing. I’ve been writing quite a bit about the Raspberry Pi recently, so is the Raspberry Pi affected by Spectre? After all it affects all Android and Apple devices based on ARM processors. The main Raspberry Pi operating system is Raspbian which is variant of Debian Linux optimized for the Pi. A recent criticism of Raspbian is that it is still 32-Bit. It turns out that running the ARM in 32-bit mode eliminates a lot of the Spectre attack scenarios. We’ll discuss why this is in the article. If you are running 64-Bit software on the Pi (like running Android) then you are susceptible. You are also susceptible to the software versions of this attack like those in JavaScript interpreters that support branch prediction (like Chromium). The Spectre hacks work by exploiting how processor branch prediction works coupled with how data is cached. The exploits use branch prediction to access data it shouldn’t and then use the processor cache to retrieve the data for use. The original article by the security researchers is really quite good and worth a read. Its available here. It has an appendix at the back with C code for Intel processors that is quite interesting. Branch Prediction In our last blog post we mentioned that all the data processing assembler instructions were conditionally executed. This was because if you perform a branch instruction then the instruction pipeline needs to be cleared and restarted. This will really stall the processor. The ARM 32-bit solution was good as long as compilers are good at generating code that efficiently utilize these. Remember that most code for ARM processors is compiled using GCC and GCC is a general purpose compiler that works on all sorts of processors and its optimizations tend to be general purpose rather than processor specific. When ARM evaluated adding 64-Bit instructions, they wanted to keep the instructions 32-Bit in length, but they wanted to add a bunch of instructions as well (like integer divide), so they made the decision to eliminate the bits used for conditionally executing instructions and have a bigger opcode instead (and hence lots more instructions). I think they also considered that their conditional instructions weren’t being used as much as they should be and weren’t earning their keep. Plus they now had more transistors to play with so they could do a couple of other things instead. One is that they lengthed the instruction pipeline to be much longer than the current three instructions and the other was to implement branch prediction. Here the processor had a table of 128 branches and the route they took last time through. The processor would then execute the most commonly chosen branch assuming that once the conditional was figured out, it would very rarely need to throw away the work and start over. Generally this larger pipeline with branch prediction lead to much better performance results. So what could go wrong? Consider the branch statement: if (x < array1_size) y = array2[array1[x] * 256]; This looks like a good bit of C code to test if an array is in range before accessing it. If it didn’t do this check then we could get a buffer overrun vulnerability by making x larger than the array size and accessing memory beyond the array. Hackers are very good at exploiting buffer overruns. But sadly (for hackers) programmers are getting better at putting these sort of checks in (or having automated or higher level languages do it for them). Now consider branch prediction. Suppose we execute this code hundreds of times with legitimate values of x. The processor will see the conditional is usually true and the second line is usually executed. So now branch prediction will see this and when this code is executed it will just start execution of the second line right away and work out the first line in a second execution unit at the same time. But what if we enter a large value of x? Now branch prediction will execute the second line and y will get a piece of memory it shouldn’t. But so what, eventually the conditional in the first line will be evaluated and that value of y will be discarded. Some processors will even zero it out (after all they do security review these things). So how does that help the hacker? The trick turns out to be exploiting processor caching. Processor Caching No matter how fast memory companies claim their super fast DDR4 memory is, it really isn’t, at least compared to CPU registers. To get a bit of extra speed out of memory access all CPUs implement some sort of memory cache where recently used parts of main memory are cached in the CPU for faster access. Often CPUs have multiple levels of cache, a super fast one, a fast one and a not quite as fast one. The trick then to getting at the incorrectly calculated value of y above is to somehow figure out how to access it from the cache. No CPU has a read from cache assembler instruction, this would cause havoc and definitely be a security problem. This is really the CPU vulnerability, that the incorrectly calculated buffer overrun y is in the cache. Hackers figured out, not how to read this value but to infer it by timing memory accesses. They could clear the cache (this is generally supported and even if it isn’t you could read lots of zeros). Then time how long it takes to read various bytes. Basically a byte in cache will read much faster than a byte from main memory and this then reveals what the value of y was. Very tricky. Recap So to recap, the Spectre exploit works by: - Clear the cache - Execute the target branch code repeatedly with correct values - Execute the target with an incorrect value - Loop through possible values timing the read access to find the one in cache This can then be put in a loop to read large portions of a programs private memory. Summary The Spectre attack is a very serious new technique for hackers to hack into our data. This will be like buffer overruns and there won’t be one quick fix, people are going to be patching systems for a long time on this one. As more hackers understand this attack, there will be all sorts of creative offshoots that will deal further havoc. Some of the remedies like turning off branch prediction or memory caching will cause huge performance problems. Generally the real fixes need to be in the CPUs. Beyond this, systems like JavaScript interpreters, or even systems like the .Net runtime or Java VMs could have this vulnerability in their optimization systems. These can be fixed in software, but now you require a huge number of systems to be patched and we know from experience that this will take a very long time with all sorts of bad things happening along the way. The good news for Raspberry Pi Raspbian users, is that the ARM in the older 32-Bit mode isn’t susceptible. It is only susceptible through software uses like JavaScript. Also as hackers develop these techniques going forwards perhaps they can find a combination that works for the Raspberry, so you can never be complacent.. C Programming on the Raspberry Pi Introduction I blogged on programming Fortran a few articles ago, this was really a tangent. I installed the Code::Blocks IDE to do some C programming, but when I saw the Fortran support I took a bit of a side trip. In this article I want to get back to C programming on the Raspberry Pi. I’ve been a C programmer for much of my professional career starting at DREA and then later on various flavours of Unix at Epic Data and then doing Windows programming at a number of companies including Computer Associates/Accpac International/Sage. I’ve done a lot of programming in the object oriented extensions to C including C++, Java, C# and Objective-C. But I think at heart I still have a soft spot for C and enjoy the fun things you can do with pointers. I think there are a lot of productivity benefits to languages like Java and C# which take away the most dangerous features of C (like memory pointers and memory allocation/deallocation), I still find C to be very efficient and often a quick way to get things done. Admittedly I do all my programming these days in Python, but sometimes Python is frustratingly slow and then I miss C. In this article we’ll re-implement in C our flashing LED program that I introduced here. We’ve now run the same program in Python, Scratch, Fortran and C. The Raspberry Pi is a great learning environment. If you want to learn programming on very inexpensive equipement, the Raspberry Pi is really excellent. GCC and C The Gnu Compiler Collection (GCC) is the main C compiler for Linux development and runs on many other platforms. GCC supports many programming languages now, but C is its original and main language. The GCC C Compiler implements the 2011 C language standard C11 along with a large collection of extensions. You can define compiler flags to enforce strict compliance to the standards to improve portability, but I tend to rely on GCC portability instead. A number of the extensions are very handy like being able to define the loop variable inside a for statement which is a feature from C++. Code::Blocks Although you don’t need an IDE to do C development, you can just edit the source files in any text editor then use GNU Make to do the build. Then run the GNU Debugger separately to do any debugging. But generally it’s a bit easier to use an IDE especially for debugging. Code::Blocks is a popular IDE that runs on the Raspberry Pi (and many other things), it’s fairly light weight (certainly compared to Eclipse, XCode or Visual Studio) and has all the standard IDE features programmers expect. A number of people recommend programming on a more powerful computer (like a good Mac or Windows laptop) and then just transferring the resulting executable to the Pi to run and test. For big projects this might have some productivity benefits, but I find the Pi is up to the task and can quite happily develop directly on the Raspberry Pi. Accessing the GPIO From C you have quite a few alternatives in how to access the GPIO. You can open /dev/mem and get a direct memory mapping to the hardware registers. This requires running as root, but it is more direct. I’m going to go the same route as I did for the Fortran program and use the easier file access from the Raspbian GPIO device driver. This one works pretty well and doesn’t require root access to use. A good web page with all the ways to access the GPIO from various languages including C is here. If you want to see how to access GPIO hardware registers directly, go for it. Like the Fortran program I needed a delay after opening the main devices file and before accessing the separate file created for the GPIO pin. There seems to be a bit of a race condition here that needs to be avoided. Otherwise a fairly simple C program and accessing the GPIO is pretty standard as accessing Linux devices go. C Code Here is the C code for my little flashing lights program. Three source files main.c and then gpio.h and gpio.c for the gpio access routines. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include “gpio.h” int main() { int i; int sleepTime = 200000; if (-1 == GPIOExport(17) || -1 == GPIOExport(27) || -1 == GPIOExport(22)) return(1); // Necessary sleep to allow the pin // files to be created. usleep(10000); /* * Set GPIO directions */ if (-1 == GPIODirection(17, OUT) || -1 == GPIODirection(27, OUT) || -1 == GPIODirection(22, OUT)) return(2); for ( i = 0; i < 10; i++ ) { if (-1 == GPIOWrite(17, HIGH)) return(3); usleep(sleepTime); if (-1 == GPIOWrite(17, LOW)) return(3); if (-1 == GPIOWrite(27, HIGH)) return(3); usleep(sleepTime); if (-1 == GPIOWrite(27, LOW)) return(3); if (-1 == GPIOWrite(22, HIGH)) return(3); usleep(sleepTime); if (-1 == GPIOWrite(22, LOW)) return(3); } return( 0 ); } // gpio.h #define IN 0 #define OUT 1 #define LOW 0 #define HIGH 1 extern int GPIOExport(int pin); extern int GPIOUnexport(int pin); extern int GPIODirection(int pin, int dir); extern int GPIORead(int pin); extern int GPIOWrite(int pin, int value); /* gpio> #include “gpio.h”); } Summary This was a quick little introduction to C development on the Raspberry Pi. With the GCC compiler, Code::Blocks, GNU Debugger and GNU Make you have all the tools you need for serious C development. I find the Raspberry Pi is sufficiently powerful to do quite a bit of development work with good productivity. As a learning/teaching environment its excellent. It’s really amazing what you can do with a $35 single board computer.
https://smist08.wordpress.com/tag/raspberry-pi/
CC-MAIN-2019-09
refinedweb
2,346
59.94
First of all, I'm really excited that GTK2HS 0.9.12 now allows launching SOE apps using GHCI. However, in the code below the blue and green triangle should render on top of each other, but the green triangle is rendered incorrectly. Being a newbie, I hesitate to file a bug report... Can anyone reproduce this? Maybe it works fine on unix? Thanks, Peter module Main where import Graphics.SOE.Gtk shape = [(200,100), (200,200), (100,200), (200,100)] main = runGraphics $ do w <- openWindow "Buggy polgon fill?" (300,300) setGraphic w $ (withColor Red $ polyline shape) `overGraphic` (withColor Green $ drawRegion $ createPolygon shape) drawInWindow w $ (withColor Red $ polyline shape) `overGraphic` (withColor Blue $ polygon shape) waitForClose w closeWindow w waitForClose w = do e <- getWindowEvent w case e of Closed -> return () otherwise -> waitForClose w
http://www.haskell.org/pipermail/haskell-cafe/2007-August/030930.html
CC-MAIN-2014-41
refinedweb
132
57.67
We have recently upgraded our database to Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production. Now we occasionally get the error in one of our APEX applications ORA-01031: insufficiënt privileges The apex application is using a user connection pool. When an Apex page is submitted we clear the context variables so the user won’t use each other’s settings. The context variables to be cleared are selected from V$CONTEXT. For some reason the context variable DRIXMD (namespace DR$APPCTX) is now (since the upgrade to 11.2) also shown in v$context. The package used in our code is not allowed to set variables in namespace DR$APPCTX and is raising the error. My question is: Is it a normal feature to see these context variables in V$CONTEX and if not is there a fix available? And if yes, can anyone clarify this? Thanks in advance.
https://community.oracle.com/thread/2560178
CC-MAIN-2015-32
refinedweb
155
66.84
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. [SOLVED]: Default country name ... how to? Hello everyone. Recently, I found that I would like to have country name set as default so user will not have to pick it from list (because most of our customers are local - UK). So to do it I modified class in res_country.py ... class Country(osv.osv): _name = 'res.country' _description = 'Country' def _get_country_name(self): res = self.env['res.country'].search([('name','=','United Kingdom')]) print res return res _columns = { 'name': fields.char('Country Name', help='The full name of the country.', required=True, translate=True), 'code': fields.char('Country Code', size=2, help='The ISO country code in two chars.\n' 'You can use this field for quick search.'), 'address_format': fields.text('Address Format', help="""You can state here the usual format to use for the \ addresses belonging to this country.\n\nYou can use the python-style string patern with all the field of the address \ (for example, use '%(street)s' to display the field 'street') plus \n%(state_name)s: the name of the state \n%(state_code)s: the code of the state \n%(country_name)s: the name of the country \n%(country_code)s: the code of the country"""), 'currency_id': fields.many2one('res.currency', 'Currency'), 'image': fields.binary("Image"), 'country_group_ids': fields.many2many('res.country.group', 'res_country_res_country_group_rel', 'res_country_id', 'res_country_group_id', string='Country Groups'), } _sql_constraints = [ ('name_uniq', 'unique (name)', 'The name of the country must be unique !'), ('code_uniq', 'unique (code)', 'The code of the country must be unique !') ] _defaults = { 'address_format': "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s", 'name': _get_country_name, } I was hoping that it is so easy to achieve but unfortunately .... is not. How can I achieve it ? Would anyone tell me what is the best method ? Don't know why I tried to achieve it in such complicated way .... ;) I'm glad you got it working. Just in case you or anyone reading this wants to do it via the UI, the trick is to populate the field BEFORE opening the Set Defaults popup: This method makes a record in Settings --> Technical --> Actions --> User Defined Defaults: By removing the User, it becomes the default for ALL USERS (or you can just select that on the popup in the first place). Awesome, Thank you Ray. Are you sure this or similar method also works in v8.0 ? From: Dr Obx Sent: 3/20/2016 2:39 PM To: Ray Carnes Subject: Re: Re: [SOLVED]: Default country name ... how to? About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now The easiest way is via the UI: (For v7 but it hasn't changed). Since this is just a record, you can export it like any other to move it from one database to another.
https://www.odoo.com/forum/help-1/question/solved-default-country-name-how-to-99440
CC-MAIN-2017-39
refinedweb
501
65.42