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
Asyncio doesn't work in pythonista 3 - jeremyherbert Hi, I've just purchased pythonista 3 and I'm trying to run the following code straight from the docs: import asyncio async def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() # Blocking call which returns when the hello_world() coroutine is done loop.run_until_complete(hello_world()) loop.close() I get the error: RuntimeError: There is no current event loop in thread 'Dummy-1'. Am I doing something wrong? Thanks, Jeremy Asyncio does work in Pythonista. If you double click the home button and throw Pythonista 3 out of memory and then relaunch Pythonista 3 and rerun your script, it will work. My advise is that you comment out the line loop.close()and then you will be able to run your asyncio script multiple times in a single Pythonista session. Added: - jeremyherbert Great, that workaround does sort it out in the meantime. Thank you for reporting the bug for me :) loop = asyncio.get_event_loop_policy().new_event_loop() I am confused. The issue was closed as ”fixed”, while all examples everywhere use get_event_loopand fail with the error stating There is no current event loop in thread 'Dummy-1'. Why is this not an issue with Pythonista? As I understand things, the code above does work, the first time it is run. But, because the pythonista environment is not fully reset when running a new script, the default event loop is now closed. This would be same as if you ran this code multiple times in IDLE for example, without python exiting. So bot so much a bug, as a subtlety with operating in a interactive environment. Other examples of things like this, include loggingloggers dont get cleared out, which is a good thing sometimes but also mean your code needs to check for existing handlers before adding new ones. What users can do is use asyncio.set_event_loop(asyncio.new_event_loop()) after loop.close, to reset the default event loop. Then get_event_loop works again. In theory, this could go into pythonista_preflight.py, however it is not obvious to me this wouldnt cause other issues, or would really be the intended behavior. @JonB, maybe some of these errors come from Pythonista running UI in separate thread, which does not know about the loop unless I provide it specifically. Need to experiment.
https://forum.omz-software.com/topic/3240/asyncio-doesn-t-work-in-pythonista-3/3
CC-MAIN-2022-05
refinedweb
380
65.83
10 September 2010 16:05 [Source: ICIS news] TORONTO (ICIS)--?xml:namespace> Gerd Romanowski, general manager of the science and technology portfolio at German chemical industry trade group VCI, said it was regrettable that the government would sacrifice tax measures to promote R&D because of the need for budget savings. The value of fiscal incentive to promote R&D was beyond doubt, he said. He went on to say that Chancellor Angela Merkel’s Christian Democrat-Liberal government, which took office last September, had noted the importance of R&D in its official coalition agreement. “We do hope that this [freeze] is not the final word on this file,” Romanowski said. The plan to freeze R&D tax incentives became clear on Friday when the government responded to an opposition party’s parliamentary request for an answer - a process known as “Grosse Anfrage” in Germany's lower house, the Bundestag, VCI said. Romanowski said almost all OECD countries used fiscal tax measures to promote R&D. Such measures were an important competitive advantage for producers in those countries. Last year, Germany-based chemical firms spent over €8bn ($10bn) on the development of new products and processes. About 10% of the industry’s jobs were in R&D laboratories, he said. Earlier this month, VCI also criticised a government move to cut breaks on eco-energy taxes, warning of a mistake in industrial policy that would threaten the country's future chemical investments. Frankfurt-based VCI represent some 1,650 Germany-based chemical firms. (
http://www.icis.com/Articles/2010/09/10/9392626/german-chems-disappointed-as-govt-freezes-r.html
CC-MAIN-2014-49
refinedweb
254
51.68
Mesh Scripting Contents Introduction First of all you have to import the Mesh module: import Mesh After that you have access to the Mesh module and the Mesh class which facilitate the functions of the FreeCAD C++ Mesh-Kernel. Creation and Loading To create an empty mesh object just use the standard constructor: mesh = Mesh.Mesh() You can also create an object from a file mesh = Mesh.Mesh('D:/temp/Something.stl') (A list of compatible filetypes can be found under 'Meshes' here.) Or create it out of a set of triangles described by their corner points: planarMesh = [ # triangle 1 [-0.5000,-0.5000,0.0000],[0.5000,0.5000,0.0000],[-0.5000,0.5000,0.0000], #triangle 2 [-0.5000,-0.5000,0.0000],[0.5000,-0.5000,0.0000],[0.5000,0.5000,0.0000], ] planarMeshObject = Mesh.Mesh(planarMesh) Mesh.show(planarMeshObject) The Mesh-Kernel takes care about creating a topological correct data structure by sorting coincident points and edges together. Later on you will see how you can test and examine mesh data. Modeling To create regular geometries you can use the Python script BuildRegularGeoms.py. import BuildRegularGeoms This script provides methods to define simple rotation bodies like spheres, ellipsoids, cylinders, toroids and cones. And it also has a method to create a simple cube. To create a toroid, for instance, can be done as follows: t = BuildRegularGeoms.Toroid(8.0, 2.0, 50) # list with several thousands triangles m = Mesh.Mesh(t) The first two parameters define the radiuses of the toroid and the third parameter is a sub-sampling factor for how many triangles are created. The higher this value the smoother and the lower the coarser the body is. The Mesh class provides a set of boolean functions that can be used for modeling purposes. It provides union, intersection and difference of two mesh objects. m1, m2 # are the input mesh objects m3 = Mesh.Mesh(m1) # create a copy of m1 m3.unite(m2) # union of m1 and m2, the result is stored in m3 m4 = Mesh.Mesh(m1) m4.intersect(m2) # intersection of m1 and m2 m5 = Mesh.Mesh(m1) m5.difference(m2) # the difference of m1 and m2 m6 = Mesh.Mesh(m2) m6.difference(m1) # the difference of m2 and m1, usually the result is different to m5 Finally, a full example that computes the intersection between a sphere and a cylinder that intersects the sphere. import Mesh, BuildRegularGeoms sphere = Mesh.Mesh( BuildRegularGeoms.Sphere(5.0, 50) ) cylinder = Mesh.Mesh( BuildRegularGeoms.Cylinder(2.0, 10.0, True, 1.0, 50) ) diff = sphere diff = diff.difference(cylinder) d = FreeCAD.newDocument() d.addObject("Mesh::Feature","Diff_Sphere_Cylinder").Mesh=diff d.recompute() Examining and Testing Write your own Algorithms Exporting You can even write the mesh to a python module: m.write("D:/Develop/Projekte/FreeCAD/FreeCAD_0.7/Mod/Mesh/SavedMesh.py") import SavedMesh m2 = Mesh.Mesh(SavedMesh.faces) Odds and Ends An extensive (though hard to use) source of Mesh related scripting are the unit test scripts of the Mesh-Module. In this unit tests literally all methods are called and all properties/attributes are tweaked. So if you are bold enough, take a look at the Unit Test module. -
https://www.freecadweb.org/wiki/Mesh_Scripting
CC-MAIN-2020-05
refinedweb
536
58.69
client XXX.X.XX.XXX] File does not exist: /var/www/static File does not exist: /var/www/xhr import sys sys.path.insert(0, "/location/of/the/files") from htpcfrontend import app as application WSGIScriptAlias / /linktowhereyouinstalledtheprogram snoopy1492 Wrote:Thanks for those info! It helped a lot! EDIT : Unfortunately I can't get the Trakt or XBMC widget to work... Wonder if it's because I'm using a XBMC build from two days ago, the JSON-RPC API could have been changed... But regarding trakt, I don't know snoopy1492 Wrote:Ok thanks, I'll wait for the updates sno.
http://forum.xbmc.org/showthread.php?tid=113136&page=2
CC-MAIN-2013-48
refinedweb
101
57.98
Hi, I am new to C# and Forms/GUIs. Basically I am trying to pass a value in a textBox to my programs program.cs file where I can apply my programs logic, but I'm stuck with how to do this. To get started all I am making is a form which takes two variables, and I want to add those variables together and display the sum in a third text box. I am stuck though with getting the value entered by the user into my program.cs file where I can use it/add the two values together. My skeleton app is as follows: The GUI: SCREEN SHOT using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MyApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //get the value from the textBox1 and put it into the variable a in the class/object Program.a Application.Form1.a = this.textBox1.Text;//??????? } } } using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace MyApp { public class Program { public string a = ""; public string b = ""; static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } On line 22 of Form1.cs I am trying to pass the value in the textbox to the variable 'a', which is part of the class Program. This is not working though, the compiler reports: error CS0117: 'MyApp.Program' does not contain a definition for 'Form1' Been stuck for ages trying to figure this out now. I'm using Visual Studio 2008 on Windows & 64 bit. Could anyone tell me what I am doing wrong? I just want to pass the values entered by the user over to the file Program.cs where I can apply my programs logic, but despite trying to figure it out, I'm stuck.
https://www.daniweb.com/programming/software-development/threads/357121/c-forms-newbie-passing-values-from-form-cs-to-program-cs
CC-MAIN-2018-17
refinedweb
322
60.31
Just to conclude this posting: first many thanks to Alan! Alan's little nutshell example about how to use MethodHandles.Lookup and employ MethodHandle s to invoke helped me a lot to get afloat with rewriting the reflection part for the bindings also using MH. The new reflection mechanism has been implemented such that on Java 1.6/6 and 1.7/7 it uses core reflection (on Java 1.7/7 MethodHandle only reflection runs in some errors that cannot be circumvented, hence using core reflection) reflection with the need to do setAccessible(true) in quite a few places. The support for Java 1.8/8 and 9 can use both, core reflection (without a need for setAccessible() at all!) and MethodHandle reflection (with one case found so far, that does not work on MH, but with core reflection). The type of reflection that is being carried out is in all my use cases (my bridge intentionally has been only supporting public classes and public members) not really specific/relevant to jigsaw. Just wanted to point that out explicitly. --- The only grief I have at the moment is with the meaning of "public": "public" has become a homonym in jigsaw, introducing a *lot* of confusion into Java (one time "public" is public, another time "public" is not public). This could be probably eased considerably IMHO, if there was a class Modifier introduced named "module" that would be set for reflective access to classes from non exported modules. This would have at least the following benefits: - communicating (and teaching!) about the publicness of a class can immediately be clarified ("is the class truly public or does it reside in a non-exported module?"), - also, programmatically it would be simple to learn whether a class object fetched reflectively is truly public or not by testing against the presence of such a "Module" modifier bit at runtime in Java 9 or higher. ---rony On 24.01.2018 20:48, Alan Bateman wrote: > On 24/01/2018 15:42, Rony G. Flatscher wrote: >> >> OK, now add to this the following class that uses p.C2 objects to access >> e.g. m() via it: >> >> G:\xfer\java9modules\03-20180124-AlanBatmanP\p>type UseC2.java >> >> public class UseC2 >> { >> public static void main (String args[]) { >> p.C2 o=new p.C2(); >> System.out.println("o="+o); >> System.out.println("o.m()="+o.m()); >> } >> } >> >> Compiling all three classes works. >> >> Running "UseC2" works and outputs: >> >> G:\xfer\java9modules\03-20180124-AlanBatmanP\p>java -cp ".;.." UseC2 >> o=p.C2@66048bfd >> o.m()=-1 >> >> So it is possible to access m() via the p.C2 object from UseC2. > That's right and this is the reason for moving to the simpler example. > > To be absolutely sure then you should decompile C2.class to make sure that > there isn't a bridge > method calling C1's m2(). If you change m() to be final then that will keep > the bridge method from > complicating the picture. > > If you change UseC2 to use core reflection and you hit the issue because the > Method object you get > is p.C1.m(). Attempting to invoke this will fail with IllegalAccessException. > In your other mail > you show a code fragment where it catches exceptions and calls setAccessible > - I'll guess that > this may have been masking the issue in the Rexx bridge. > > For completeness then you may want to try out the new reflection API. I > realize you have to > compile to JDK 6 but I think you'll find it will work the same way as the > invokevirtual that o.m() > compiles to. > > MethodHandles.Lookup lookup = MethodHandles.lookup(); > MethodType mt = MethodType.methodType(int.class); > MethodHandle mh = lookup.findVirtual(p.C2.class, "m", mt); > Object res = mh.invoke(o); > > -Alan
https://www.mail-archive.com/jigsaw-dev@openjdk.java.net/msg10306.html
CC-MAIN-2018-13
refinedweb
624
66.64
13 May 2011 16:38 [Source: ICIS news] ?xml:namespace> US-owned ExxonMobil will hold a 51% stake in the agreement with Total taking the remaining 49%. The deal is subject to approval from the Polish authorities. The concessions will allow the companies to explore the areas for a period of five years, from March 2009 for Chelm and five years from December 2008 to access Werbkowice. The work programme for each region means the companies can acquire seismic data, drill exploratory wells and undertake production tests. ExxonMobil has already performed seismic acquisition works as well as drilling an exploratory well in the Chelm region. Financial details of the agreement were not immediately available. For more on Total,
http://www.icis.com/Articles/2011/05/13/9459871/total-exxonmobil-sign-agreement-to-search-for-shale-gas-in-poland.html
CC-MAIN-2014-52
refinedweb
118
65.32
0 Hello, I would like to know what am I missing in this program to be getting that error. Thanks in advance! Error is error C3861: 'setprecision': identifier not found #include <iostream> using namespace std; int main () { int numFloors=0, numRooms=0, numOccupied=0, totRooms = 0, totOccupied = 0, totUnoccupied=0; double occupRate=0.0; cout << "How many floors are in the hotel?\n"; cin >> numFloors; for (int floor = 1; floor <= numFloors; floor++) { cout << "How many rooms are in the #" << floor << " floor?\n"; cin >> numRooms; totRooms += numRooms; cout << "How many rooms are occupied?\n"; cin >> numOccupied; totOccupied += numOccupied; totUnoccupied = totRooms - totOccupied; occupRate= static_cast<double>(totOccupied) / totRooms; } cout << "\n\nThe hotel has " << totRooms << " rooms.\n"; cout << totOccupied << " rooms are occupied.\n"; cout << totUnoccupied << " rooms are unoccupied.\n"; cout << fixed << showpoint << setprecision(1); cout << occupRate*100 << "% of the rooms are occupied.\n\n"; return 0; }
https://www.daniweb.com/programming/software-development/threads/347559/setprecision-identifier-not-found-error
CC-MAIN-2017-22
refinedweb
142
51.65
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives In trying to bring my YinYang work to a textual programming language, I'm beginning to design a new type system based on mixin-like traits (as in YinYang, no classes) but with global type inference (also, to support the inference described in the before-mentioned paper). As we know, global type inference through Hindley Milner in OO languages is problematic given support for subtyping. So a language like Scala is limited to local type inference. I'm developing my system based adding the concept of an "at most" constraint as the opposite of the typical "at least" constraint. Rather than have type variables that are bound, their "at most" constraint starts as an open type that is gradually narrowed via unification. Consider some Scala/C# like code: trait Dictionary[K,E] { def set(key : K, elem : E) = {...} def get(key : K) : E = {...} } def foo(s : string) = {...} def bar(dict) = { dict.set(key = 42, elem = "hello"); foo(s = dict.get(0)); } The bar method lists dict as an argument without specifying a type, so a type parameter is implicitly created for it (we could have written def bar[T](dict : T)). The second-last statement (calling "set") propagates a constraint on dict that (a) dict is at least a Dictionary (as in YinYang, methods are selected directly rather than by name), K is at most int while E is at most string. The last statement (calling "foo") propagates a constraint on dict that E is at least string (so E is string since its at least and at most a string). So for any def "p" with argument "a" that is called on expression "e" (so "p(a = e)") we have: typeof(e) <: typeof(a) typeof(a) :> typeof(e) Where <: is "at least," which are combined by union, and :> is "at most," which are combined by intersection. A type error occurs on a type parameter if "at least" is not a subset of "at most." An actual type is just a set of traits where extension means subset (so if C : B and B : A, then typeof(C) is (A, B, C)). Type variables are never closed until they go out of scope (in which case, we can just take "at least" to be its type), and so we have to limit the type system in some way so we can type check in a modular way, which I haven't really explored yet. YinYang-style inference comes into play when we start treating traits like type variables that can be constrained. Also, exclusive extension relationships (which prevents an int from being mixed in with a Button, for example) continue to temper the flexibility of compositions so the system isn't completely open-ended. So I'm trying to figure out why I think this is workable to support global type inference when Scala cannot support it with similar mechanisms. Any ideas? Perhaps its because I'm not relying on name binding (names are resolved to symbols by the IDE)? What do you mean by "(no classes)"? It seems this is made a little easier for yourself by defining foo(s: string) rather than just foo(s). Do you propose a truly global inferencing algorithm, in the sense that you are going to review all of f()'s callers to see what f()'s argument types are? How will you handle recursion? Library boundaries? foo(s: string) foo(s) f() BTW, I think this is incredibly interesting. I'm working on a language that would use this (over my current local-only type inference) in a heartbeat if you/we figure out if any remaining limitations are acceptable. Scala-style traits are simply classes that support mixin-style inheritance sans constructors. In the language I'm designing, there are only traits that have constructors and a few other features (exclusive inheritance) that allow them to supersede the need for classes in a language. Inference will be restricted to the module level, so you can't change the type of a library method simply by implementing it. However, any constraints computed in compiling a module remain visible to clients of that module (for visible symbols of course!). Recursion is easy enough to detect in a set-based way (hey, the set I got for this type includes myself...to top or bottom!). I hacked this scheme up in Scala (because I was bothered with lazy type completion) at one point a long time ago, and it seemed to work. I'm just wondering if I'm reinventing the wheel (or worse yet, an unworkable square wheel, even dependent types...scary), it seems like an obvious solution. Trying to clarify. When Scala unifies types, its trying to compute an equivalence, "T = A" whereas I think only a range is necessary in my case, "A <= T <= B," which I think should be much easier to compute. The lack of name binding means we don't depend on type information to resolve names to symbols, so equivalence isn't really necessary (on the flip side, we can definitely use what type information we have to guide name resolution in the IDE). And since I have no qualms about upgrading types as needed (refining the at-least type on demand), I think I'm dealing with a different set of language design constraints. So performance would be limited by the size of sets being unioned and intersected, which in term depends on (a) the number of letters (e.g., type parameters, traits) in our type systems, and (b) the "depth" of the type (since type parameters are members and can have members...). As for (a), this can get tricky since type parameters are duplicated on instantiation (make an object, call a method), and we can't just blow them away very easily. As for (b), in a functional language you can have very deep typeful structures, but in an imperative language less so. Limiting accuracy of deeper structures could some how help. What you describe seems no different from the usual approach to subtyping inference (see e.g. the works of Palsberg and others). The reason that, in practice, it doesn't work well as a global mechanism is that (1) constraints quickly explode combinatorially, and (2) there is no succinct way to present inferred "types" to the user. In Scala, you also have very expressive forms of (first-class) polymorphism, which make everything undecidable immediately, even without subtyping. Ah, I've been looking at some of Jens' papers but didn't see an immediate similarity. I should probably look for some sort of trade off, as in arguments have to be typed so that all type variables are explicit and the constraints converge more quickly while still conveying benefits to library users (the dictionary example would still work, but the dict argument would need some sort of type). The problem with Scala, as I understand it, is that they are tracking exact type parameter bindings and therefore unification is very hard. I think that by tracking upper and lower bounds separately, there is a lot more leeway (unification is just intersection most-bounds and union for least-bounds, no magic number limits needed to compute LUBs and MLBs!), or maybe I'm deluding myself. dict.set(key = 42, elem = "hello"); K is at most int while E is at most string dict.set(key = 42, elem = "hello"); K is at most int while E is at most string It does not seem clear to me why these should be an upper bound. We know that dict.K is at most int and dict.E is at most string (actually referred to as a lower type bound???). When I grab some key or element from dict later, that upper bound is very useful in further type checking as well as code completion (i.e. we can show completions between the at-least and at-most type bounds). What I intuitively understand from `key = 42, elem = "hello"` is that a key can be constructed from an integer, and an elem can be constructed from text. This is compatible, for example, with `key` type being a rational or float, of which 42 is one example. It does not make sense to me that you treat these as upper bounds. Rather, "can be constructed from" is a lower bound - a trait or typeclass. key = 42, elem = "hello" What am I missing? Are there no overloaded operators, literals, or expressions in your language? We're talking about constraints on type signatures, not constraints on values. To say E is "at most" string does not mean that a variable of type E cannot hold subclasses of string. It means that the type declaration for E must be at most string. It cannot be more than string otherwise a string could not be assigned. e.g. in C++: class base class string : public base class myString : public string template<class E> struct foo { E * member; } var; var.member = new string("hello") implies that var.E is at most string, because if var.E were myString the assignment would be invalid. However, E could be less than string (it could be base). Right! Actually, my example is bad because I'm using types that aren't typically refined, a better example would be: dict[1] = aDog; dict[2.3] = aCat; K is at most a number (the intersection of int and float) while E is at most a mammal (the intersection of dog and cat). These types are useful for guiding code completion, where we don't see the program as a close entity. At-least type constraints are driven by need; e.g., foreach (var e in dict.Elements) e.doAnimalStuff(); In this code, e has doAnimalStuff in its code completion menu, and after the code is written, E would be at least an animal, which is completely compatible with it at least being a mammal. It get's a bit more interesting if we do: object a : Thing; dict[1] = a; foreach (var e in dict.Elements) e.doAnimalStuff(); So typically there would be an error on "a" if its type was closed, but with the "maze of twisty classes" work, "a" is automatically upgraded to an animal because it needs to be. We could do this implicitly or through a fix mechanisms, but the point is that it is driven by inference. Ah, so when the programmer specifies a type, he's in fact specifying a minimum type, but the rest of the program text can constrain that further. Yes, that makes sense, since in a statically untyped language every variable tacitly has a specified type of <root type> and type inference in those languages per se is attempting to tighten that up. Applying this to a whole program sound scary, but within the context of a well-defined module with an interface that is firmly typed (i.e. those are the actual types, not minimum types), and which only calls out to other well-defined modules, it seems like this should let you abandon specifying type information everywhere within the module (since any time an object "arrives", it's either been created explicitly and has a known type, or it's been passed in and has a known type). So you could create a library with a well-defined C++ interface, but internally it's all just typeless variable declarations. Then, as meta-level 1, the users of a module in a specific program could expose their inference information for that interface, and that inference information could be combined to tighten up the interface according to actual usage. So, say a library is flexible with regards to some input objects (they have virtual functions defined) but in fact only one type of object is used. The interface can now be tightened up - just for this program - to make those functions non-virtual. And now they can be inlined, even, during link-time code generation. Huge performance win, but still based on nice flexible library code. And the flexible library code has a static signature so can also be linked with code which doesn't do the type inference. I like the idea, definitely, although I doubt I have anything to contribute regarding its feasibility in the general case :) the type declaration for E must be at most string. It cannot be more than string otherwise a string could not be assigned But: The latter point may be language-dependent - e.g. Haskell can do it for numbers (via typeclass), while C++ can do it for strings. In your example, if E was of type `base`, it could be assigned `new string("hello")`. And it could also be assigned any subclass of string. Yes, any value with a type that is a superclass of E can be assigned to E (and doing so changes the at-most type of E), in fact, anything can still be assigned to E because its at-least type is empty. I'm not considering conversions. Right, so your bullet points explain what "not more than string" means, and your last line reiterates my last sentence. So why the "but"? The second bullet point does not describe "not more than string". Superclasses are usually conceived as supertypes of their subclasses. So must be at least string. Consider the following code: def foo[T](t : T) = t; val aCat : Cat = ...; val aDog : Dog = ...; var x = foo(aCat) // typeof(x) :> Cat x = aDog; // typeof(x) :> Mammal So the typeof(x) isn't exactly Cat after the foo call, it is just at-most Cat. The second assignment to aDog then causes x's type to be at most Mammal (the intersection of cat and dog). We didn't really need the dummy foo call to achieve this: val aCat : Cat = ...; val aDog : Dog = ...; var x = aCat; // typeof(x) :> Cat x = aDog; // typeof(x) :> Mammal Basically assignment, binding, and return create at-most type constraints. My idea for global inference doesn't work so great for functional structures, consider: abstract trait List { abstract def ForEach(a); } trait Empty :: List { override def ForEach(a) = {}; } trait Prepend(val At, val Rest) :: List { override def ForEach(a) = { a(At); // so a <: Action[ON], a.ON :> typeof(at) Rest.ForEach(a); // Rest <: List... } } The inference algorithm could infer that the typeof(At) is actually a type parameter of List so it can be used to type the declaration of ForEach in List: abstract trait List[T] { abstract def ForEach(a : Action[ON :> T]); } trait Empty :: List { override def ForEach(a) = {}; } trait Prepend(val At : T, val Rest : List) :: List { override def ForEach(a) = { a(At); Rest.ForEach(a); } } But if we follow through and do that on Rest, we'll add type parameters to List forever. So we either have to cut off or disallow recursive type inference, or not bother at all with creating new type parameters, rejecting the above code as incorrectly typed. Since we can't create type parameters, the type system is quite limited, but still very useful in expressing typical OO imperative constructions. So let's look at a sane explicitly annotated definition of List: abstract trait List[T] { abstract def ForEach(a : Action[/* ON :> T - inferred */]); } trait Empty :: List { override def ForEach(a) = {}; } trait Prepend(val At : T, val Rest : List[T : T]) :: List { override def ForEach(a) = { a(At); /* infers a.ON :> T */ Rest.ForEach(a); } } List[T : T] is an explicit type constraint on Rest.T to be at least this.T. Now let's call ForEach on a list: val list : List = ...; val a : Action = x => x.doAnimalStuff(); /* infer a.ON <: Animal */ list.ForEach(a); By our constraints we have list.T <: a.ON <: Animal so...we can infer by transitivity that: list.T <: Animal Or do we? Actually, expressions should have their own names, so the action is actually an anonymous something: val list : List = ...; var a : Action = ($a) x => x.doAnimalStuff(); /* infer $a.ON <: Animal, a :> $a */ list.ForEach(a); /* infer a.ON :> list.T So we really have a.ON :> $a.ON (given a :> $a) and $a.ON <: Animal and list.T <: a.ON Ugh, so what can we say about that? The problem is the assignment to val a, since we don't have equivalence, we just say that "a" could be at most $a, and when we call ForEach, the constraint is not really propagated as we really want (a could have been reassigned to another type somewhere else). So that is still something to figure out. (Co/contra) variance always gets us in the end! So my parent post got sort of whack at the end: it turns out I have a big problem with co and contravariance, which shouldn’t be so surprising but here I am. Here are some observations: an “at-least†type constraint of some type parameter T is not just some bound, it constrains what values can be assigned to T: if T trait Cell[V] { var Value : V; } var c = Cell[V : Dog]; // typeof(c) :> Cell[V <: Dog] if (b) c = Cell[V : Cat]; // typeof(c) :> Cell[V <: Cat] // typeof(c) :> Cell, (Dog + Cat) :> c.V :> (Dog * Cat) object foo; c.Value = foo; // foo <: c.V <: (Dog + Cat), c.V :> (Dog * Cat * foo) var k = c.Value; // typeof(k) :> c.V :> foo, foo <: typeof(k) Ok, so that’s weird, after the third statement, c.V’s at least type is the union of Dog and Cat (a mythical dog cat), while its at most type is Mammal (Dog intersected with Cat). Variance works out because “at-least†types are used to constrain assignments (so “foo†must be a cat and dog) while “at-most†types are used to constraint evals (so “k†is only guaranteed to be a mammal). Yikes! What does colon “:†mean then? In Scala, I think “:†means “<:†(we write V <: Dog, not V : Dog) but that doesn’t make sense in my type system, “V : Dog†is really invariant and means something like “Dog :> V <: Dog†if we want the above results. We also need the following rule to capture the invariance of type member parameters in : if A :> B and B.T :> C then A.T :> C if A :> B and B.T <: C then A.T <: C I’m not sure yet if the dual rule also applies to A <: B.
http://lambda-the-ultimate.org/node/4660
CC-MAIN-2014-52
refinedweb
3,104
70.43
squibnMembers Posts12 Joined Last visited Content Type Profiles Forums Store Showcase Product ScrollTrigger Demos Downloads Everything posted by squibn Liquid Stage with parallax asset squibn replied to squibn's topic in TransformManager (Flash)Hi Greensock, Apologies, I didn't mean to sound like I wanted you to work it all out for me ...just frustrated that I couldn't work it out myself...I'll get to the bottom of it tho that's for sure:)....just might take me a while!... I'll look into your suggestion tho that's for sure! Kudos for such an amazing set of Classes by the way...love em! Squibn Liquid Stage with parallax asset squibn posted a topic in TransformManager (Flash)Hi there, I sure hope someone can help with my liquid stage issue, as its essential I get it working as my whole site hinges on it!! Basically, I've incorporated Liquid Stage into my Gaia built site and itreally works a treat! ...But (there's always a but!!) ....the home page has a placed asset in it which is a swf that makes use of a parallax effect, where the placement of the mouse controls the scrolling to the left and right of a MovieClip. This works fine by itself, but when placed within my Gaia framework the "wheels fall off!!" I'm pretty sure this is because the parallax placed swf references the stage, and wondered if there was a work round, or alternative solution? It doesn't have to be a placed swf, it could be actually within the framework, but this is just how I like to build my sites. My code is this....within my Gaia project... package pages{ import com.gaiaframework.templates.AbstractPage; import com.gaiaframework.events.*; import com.gaiaframework.debug.*; import com.gaiaframework.api.*; import flash.display.*; import flash.events.*; import gs.*; import com.greensock.layout.*; public class HomePage extends AbstractPage { public function HomePage() { super(); alpha=0; } override public function transitionIn():void { super.transitionIn(); TweenLite.to(this, 0.3, {alpha:1, onComplete:transitionInComplete}); } override public function transitionOut():void { super.transitionOut(); TweenLite.to(this, 0.3, {alpha:0, onComplete:transitionOutComplete}); } override public function transitionInComplete():void { super.transitionInComplete(); init(); } public function init():void { var myContainer:MovieClip = new MovieClip(); this.addChild(myContainer); myContainer.addChild(assets.homePage.loader); myContainer.alpha=1; myContainer.visible=true; myContainer.x=0; myContainer.y=0; assets.homePage.alpha=1; assets.homePage.visible=true; var ls:LiquidStage=new LiquidStage(this.stage,1624,668,1024,668); var area:LiquidArea=new LiquidArea(this,0,0,1624,668); area.attach(myContainer, ScaleMode.PROPORTIONAL_OUTSIDE); ls.update(); } } } code within my swf asset... import com.greensock.*; import com.greensock.easing.*; var easeType = Expo.easeOut; var xmouse:Number = 0; var xPct:Number = 0; var speed:Number = 2; stage.addEventListener(MouseEvent.MOUSE_MOVE, render); function render(e:MouseEvent):void { if( e.stageX > stage.stageWidth/2) { xmouse= -(e.stageX -stage.stageWidth) - stage.stageWidth/2; //-512 } else { xmouse = ((stage.stageWidth/2) - e.stageX); //512 } xPct = Math.round ((xmouse/stage.stageWidth) * 200); var skyXto:Number = ((xPct/100) * (sky_mc.width - stage.stageWidth)/2) + stage.stageWidth/2; TweenMax.to(sky_mc,speed, {x:skyXto, ease:easeType}); var fieldXto:Number = ((xPct/100) * (scrollPanel.width - stage.stageWidth)/2) + stage.stageWidth/2; TweenMax.to(scrollPanel,speed, {x:fieldXto, ease:easeType}); } I appriciate that this may be one for the Gaia forum, but thought I'd try here first as my project uses Liquid Stage? Any help would be fantastic, and alleviate a huge amount of head scratching!! Here's hoping! Squibn Controlling a movieclips timeline using timelinemax squibn replied to squibn's topic in GSAP (Flash)Thats exactly what I was after!!!...I'd never have worked that out! Thank you Greensock... you've thought of everything! Cheers, Squibn Controlling a movieclips timeline using timelinemax squibn posted a topic in GSAP (Flash)Hi there, I can't seem to work out how to control a movieclips timeline whilst working with timelinemax? What I've got is a series of animations which are scripted but one of those animations is keyframed on one of the movieclips timeline. So what I'm trying to do is let the scripted animations run through, but the movieclip animation hold until its turn to play through, then once its played carry on with the scripted animations, so my code so far looks like this, and I'll show the point that I want the keyframed animation to play through... var myTimeline:TimelineMax = new TimelineMax(); myTimeline.append(TweenMax.from(logo, 0.5, {autoAlpha:0, ease:Back.easeOut})); myTimeline.append(TweenMax.from(baseTint, 0.5, {_yscale:0, ease:Back.easeOut})); //////////////////////// Movieclips keyframed animation here... //////////////////////// myTimeline.append(TweenMax.from(mainHeadline, 0.5, {autoAlpha:0, ease:Back.easeOut})); myTimeline.play(); I tried using "frameLabel" but lost my way! If I'm not explaining my self very well I'll try make things more clear, but basically its scriped animation, then a movieclips timeline animation, then back to scripted animation. Any help would be superb! Cheers, Squibn looped clips all at once rather than one after the other squibn posted a topic in GSAP (Flash)Hi there, I'm not entirely sure if this is a TimeLineMax question or a general actionscript question but here goes anyway... What I'm wanting to do is animate a set of MovieClips all at once rather than one after the other, what I've go so far is this... var button:Array = [button1, button2, button3, button4, button5, button6, button7, button8]; var myTimeline:TimelineLite = new TimelineMax({repeat:-1, yoyo:true}); for( var i:int = 0; i < button.length; i++ ){ myTimeline.append(TweenMax.to(button[i], 1, {scaleX:1.2, scaleY:1.2, ease:Sine.easeIn})); myTimeline.append(TweenMax.to(button[i], 1, {scaleX:1, scaleY:1, ease:Sine.easeIn})); } myTimeline.play(); Which almost works, in that it animates each clip one after the other, but what I actually want it to do is animate all the clips at the same time, would someone be able to explain where I'm going wrong in my code setup? Thanks, Squibn Simple remove child after tween squibn replied to lostatoll's topic in GSAP (Flash)Apologies if this is seen to be jumping on the end of someone else's post but my question is very similar to the original poster so though it'd be OK to do so, all I 'm trying to work out is how do I now fire a second function? What I'm trying to do is tween a MovieClip back to zero, then remove the Clip (exactly what has been done in the original post... but now I want to fire another function that does something else.) I'm a little stumped simulate mouseover using frames squibn replied to squibn's topic in GSAP (Flash)That is EXACTLY what I'm after...I can not fault the capabilities of this superb engine...thanks greensock! simulate mouseover using frames squibn posted a topic in GSAP (Flash)Hi there, Is this something that can be achieved using TweenMax, and if so whats would be my best route to go... What I'm wanting to do is simulate a mouse cursor moving over a button so that it changes from an arrow to the pointer when it travels over a particular movieclip as if to simulate someone moving their cursor over a button. There would be no actual user interaction as its all automated to simulate a "How to use" animation. I was planning on using TweenMax's bezierThrough to achieve the movement of a MovieClip (the cursor) with two frames inside, one of the arrow, and the other of the pointer, this would then travel across the screen and when it entered a particular MovieClip would go to frame two (which would make the arrow change to the pointer) and then when it went back out of the MovieClip go back to frame one (thus change back to the arrow.)..so it would look like an animation of a mouse cursor going over a button. I hope I'm being clear in what I'm trying to achieve, if I'm not then I'll try explain further!! I'm just not sure what would be the best tool to use in this amzing tweening engine! Cheers, Squibn - Got it... var frameTween:TweenMax = new TweenMax(mc, mc.totalFrames - 1, {frame:"4", ease:Linear.easeNone, useFrames:true, paused:true}); Should have tried before posting - Ahhh, I see, now that you've explained it like that I understand when to use timelineLite...thank you So using TweenMax's "frame" feature is it possible to control the amount of frames that the playhead travels to per click? As in every time a button is pressed the playhead travels say 4 frames? Playing a nested movieClips frames in timelineLite squibn posted a topic in GSAP (Flash)Hi There, I'm having a bit of trouble animating a nested movieClips frames. What I've got in my fla are two movieClip buttons on the stage, and a third movieClip (myTimeline) that has a series of animations along its timeline, and what I'm wanting to do is have the two buttons control the third movieClips timeline, so when one button is pressed the third movieClips timeline animates along and when its gets to the end of the keyframes goes back to the first keyframe and loops through continuously, and then when the other button is pressed it reverses the third moveiClips timeline and then loops through in the opposite direction (so basically the two buttons control the third movieClips timeline forward and backwards). From reading the documentation timelineLite would be the way to go (correct me if I'm wrong!). But I just can't get it working the code I've got looks as follows... package { import flash.display.MovieClip; import flash.display.SimpleButton; import flash.events.MouseEvent; import com.greensock.*; public class Navigation02 extends MovieClip { public function Navigation02() { myTimeline.stop(); rotateOneWay.addEventListener(MouseEvent.MOUSE_DOWN, OneWayPress); rotateOneWay.addEventListener(MouseEvent.MOUSE_UP, OneWayRelease); rotateOtherWay.addEventListener(MouseEvent.MOUSE_DOWN, OtherWayPress); rotateOtherWay.addEventListener(MouseEvent.MOUSE_UP, OtherWayRelease); } private function OneWayPress(evt:MouseEvent){ var myTimeline:TimelineLite = new TimelineLite({useFrames:true}); myTimeline.gotoAndPlay(this.currentFrame); } private function OneWayRelease(evt:MouseEvent){ var myTimeline:TimelineLite = new TimelineLite({useFrames:true}); myTimeline.stop(this.currentFrame); } private function OtherWayPress(evt:MouseEvent){ var myTimeline:TimelineLite = new TimelineLite({useFrames:true}); myTimeline.reverse(); } private function OtherWayRelease(evt:MouseEvent){ var myTimeline:TimelineLite = new TimelineLite({useFrames:true}); myTimeline.stop(this.currentFrame); } } } I hope I'm explaining myself clearly?? Here's hoping... Squibn conveyor belt effect woes squibn posted a topic in GSAP (Flash)Hi all, Having trouble executing what I thought was a fairly simple animation, wondered if anyone could tell me if this is the best way of doing this kind of animation... What I've got is a simple conveyor belt with several boxes on it, what I'm trying to do is make the boxes look like they fall off the belt when they get to the end, the animation that I've put together does this but there are two problems with it, firstly the items only animate one at a time, when I actually need them to travel along the conveyor belt at the same time, secondly there is a slight pause between them getting to the end of the belt and them falling off. This is my code so far... import com.greensock.*; var myTimeline:TimelineLite = new TimelineLite(); myTimeline.append(new TweenLite(box1, 5, {x:600})); myTimeline.append(new TweenLite(box1, 0.5, {rotation:90, x:990, y:300, alpha:0})); myTimeline.append(new TweenLite(box2, 5, {x:600})); myTimeline.append(new TweenLite(box2, 0.5, {rotation:90, x:990, y:300, alpha:0})); myTimeline.append(new TweenLite(box3, 5, {x:600})); myTimeline.append(new TweenLite(box3, 0.5, {rotation:90, x:990, y:300, alpha:0})); Anyone point me in the right direction? Here's hoping! Cheers, Squibn
https://greensock.com/profile/140-squibn/content/?change_section=1
CC-MAIN-2022-33
refinedweb
1,979
55.54
Introduction to JSON JSON is a simple idea that can be quite confusing at times. It can be difficult trying to figure out when you need to convert JSON to an object and when you need to convert an object to JSON. In this article you'll see both directions, but first what is JSON? JSON stands for JavaScript Object Notation. It is a data exchange format that has the same notation as a JavaScript object. I'll take a look at that in a moment, but the most important thing to remember about JSON is it's just a string (with a standard format). First, let's look at some JavaScript, specifically a JS object: let o = { name: "Fred", age: 59, hobbies: ['diving', 'stamps', 'coins', 'boardgames'] }; You have three data types there: string, number (in this case integer), and an array (of strings). As a JSON string this would be: { "name": "Fred", "age": 59, "hobbies": ['diving', 'stamps', 'coins', 'boardgames'] } JSON format also supports other JSON objects within the structure. So you could have: { "users": [ {"name": "Fred", "id": 1234, "loggedin": true}, {"name": "Jim", "id": 4567, "loggedin": false} ] } So this is a JSON object that contains a named value ( users) that is an array of JSON objects. NOTE: JSON data is always in name/value pairs. JSON data types JSON supports the following data types: - String - Number - Array - JSON object - Boolean null Note that there is no Date data type. If you ever want to check the validity of your JSON, you can use the excellent JSON lint. Just paste in your JSON string and click Validate JSON. Where is JSON used? The reason JSON is important these days is because a lot of code is written in JavaScript, and people are familiar with the syntax of JavaScript objects. Further, many REST APIs offer JSON as the response format. Sometimes REST APIs will offer you the option of responses in JSON or XML (or some other format), but most people opt for the JSON format response as it's quite easy to work with. You make an HTTP request (API call), and what actually returns to the client-side is a string, in the JSON format. You can also POST data to a server in JSON format, and I'll be looking at that in more detail in another article. Often your client is written in JavaScript, and so converting that JSON string into something compatible with your code is trivial. There are also libraries for most of the other languages. Essentially these libraries provide two main functions: - Convert a JavaScript object, or other language-specific object (e.g. Python dictionary) into a JSON format string. - Convert a JSON string (typically from a HTTP response) into a language-specific object (e.g. Python dictionary). Let's look at examples in both JavaScript and Python. JavaScript First, let's look at going from an object to JSON: var o = { name: "Fred", age: 59 }; console.log(o); var s = JSON.stringify(o); console.log(s); This code uses stringify to convert a JavaScript object to a JSON-format string. You can then go the other way: var j = JSON.parse(s); console.log(`${j.name} - ${j.age}`); This code uses the parse method to turn the JSON-format string back into a JavaScript object. Python Now let's look at Python. First, you'll see how to convert a Python dictionary into a JSON-format string: import json o = {"name": "Fred", "age": 59} print(o) s = json.dumps(o) print(s) You need to import the json module. You can then use json.dumps to dump a Python dictionary to a JSON-format string. If you want to convert a JSON-format string into a Python dictionary: p = json.loads(s) print(p) print(p['name']) print(p['age']) Here you use json.loads to load a JSON string into a Python dictionary. This is useful where, for example, you receive a JSON response from a REST API and you want to process that response as a Python dictionary, rather than trying to parse a potentially complex string. Other Modules and frameworks may provide convenience methods for dealing with JSON. For example, if you are using the Flask web framework then dictionaries returned from a response method are automatically converted to JSON for you using jsonify(). You can also convert non-dictionary items to JSON if you want to by calling any appropriate JSON method. You can then explicitly jsonify any response object you are returning. For example: @app.route("/users") def users_api(): users = get_all_users() return jsonify([user.to_json() for user in users]) In this example, taken from the Flask documentation, the user object is converted to JSON with its to_json method. This would leave you with a Python list of user objects (in JSON format). You then turn the Python list to JSON format array using jsonify. Summary JSON is an important data interchange format. You have seen how to convert a language-specific object into a JSON string, and also how to convert a JSON string back into a language-specific object.
https://tonys-notebook.com/articles/intro-to-json.html
CC-MAIN-2022-05
refinedweb
851
72.16
Subject: [Boost-bugs] [Boost C++ Libraries] #10524: Why does boost\log\sinks\text_file_backend.cpp prevents users from reusing its classes? From: Boost C++ Libraries (noreply_at_[hidden]) Date: 2014-09-22 15:45:40 #10524: Why does boost\log\sinks\text_file_backend.cpp prevents users from reusing its classes? ---------------------------------------------+--------------------- Reporter: blacksmith33@⦠| Owner: andysem Type: Feature Requests | Status: new Milestone: To Be Determined | Component: log Version: Boost 1.57.0 | Severity: Problem Keywords: logger; inheritance; code reuse | ---------------------------------------------+--------------------- Hello, guys! Today my colleague have encountered a problem. We're using boost logger in our application and it's really great boost library part. But, we need to change some of it's functionality. Actually, we need to add some lines of code in a method of collector class (for example, file_collector) I guess the right way of doing it is inheritance from file_collector and redefining those functions. But, since it's all declaration and definition is in text_file_backend.cpp file in an anonymous namespace, it's impossible. The only solution I see is to copy-and-paste entire file_collector class and rewrite some of it's methods content. Is there any reason that the entire class is in text_file_backend.cpp file or maybe I am missing something? Thank you for attention! -- Ticket URL: <> Boost C++ Libraries <> Boost provides free peer-reviewed portable C++ source libraries. This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:17 UTC
https://lists.boost.org/boost-bugs/2014/09/38009.php
CC-MAIN-2020-24
refinedweb
238
60.61
How to flip an image in Java ME This articles shows how to to flip a given Image in Java ME. Solution - Create a new Image using createImage - Or use drawRegion to fllp the image when drawn. - Apply Mirror transformation using Sprite.TRANS_MIRROR On some devices, pre-transformed images may render more quickly than images that are transformed on the fly using drawRegion. However, creating such images does consume additional heap space, so this technique should be applied only to images whose rendering speed is critical. Sample Code Imports import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.*; Flip Image Create a new flipped image with createImage. For immutable source images, transparency information, if any, is copied to the new image unchanged. Or use drawRegion to fllp the image when drawn. Note For MIDP 1.0 devices we can use com.nokia.mid.ui.DirectGraphics.drawImage(javax.microedition.lcdui.Image img, int x, int y, int anchor, int manipulation) with manipulation = DirectGraphics.FLIP_HORIZONTAL --Submitted by Amitabh Srivastava at 16:55(IST), 5 July 2010. Series 40 Series 40 DP 1.1 Symbian MIDP 2.0
http://developer.nokia.com/community/wiki/How_to_flip_an_image_in_Java_ME
CC-MAIN-2014-41
refinedweb
185
51.95
cleansing multiple build directories In my adventures of building GNOME with JHBuild, it often happens that when I tweak something that affects the build environment (e.g. use system Python instead of JHBuild-built one), I get a heck of a lot of build failures. This will happen even after I run jhbuild clean (which runs make clean on the modules), testimony to the weakness ofthe GNOME build infrastructure (autotools, ...). This means that I need to run make distclean or better still (where applicable) git clean -dfx. Note that I sometimes even have to uninstall one or two modules (on JHBuild path) to get a build failure fixe ( jhbuild uninstall modulename). This is laborious work, so I sometimes just wipe out the entire installation. Note that there's dozens of modules to build, so I wrote this little script to take care of it: import os import subprocess top_level = os.path.expanduser("~/src/gnome") for filename in os.listdir(top_level): full_path = "{}/{}".format(top_level, filename) if os.path.isdir(full_path): cmd = "cd ~/src/gnome/{} && git clean -dfx".format(filename) if subprocess.call(cmd, shell=True) != 0: cmd = "cd ~/src/gnome/{} && make distclean".format(filename) if subprocess.call(cmd, shell=True) != 0: cmd = "cd ~/src/gnome/{} && make clean".format(filename) subprocess.call(cmd, shell=True) update Someone very kind guy made a bunch of suggestions, making my code much better: import os import subprocess top_level = os.path.expanduser("~/src/gnome") for filename in os.listdir(top_level): full_path = os.path.join(top_level, filename) if os.path.isdir(full_path): os.chdir(full_path) if subprocess.call("git clean -dfx".split()) != 0: if subprocess.call("make distclean".split()) != 0: subprocess.call("make clean".split()) further reading modules: os, os.path, subprocess
http://tshepang.net/cleansing-multiple-build-directories/
CC-MAIN-2018-43
refinedweb
285
52.36
). By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults. However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files. The second half of this document describes how these storage systems work. When you use a FileField or ImageField, Django provides a set of APIs you can use to deal with that file. Consider the following model, using an ImageField to store a photo: from django.db import models class Car(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='cars') Any Car instance will have a photo attribute that you can use to get at the details of the attached photo: >>> car = Car.objects.get(name="57 Chevy") >>> car.photo <ImageFieldFile:> Fileobject¶ Internally, Django uses a django.core.files.File instance any time it needs to represent a file. Most of the time you’ll use a File that Django’s given you (i.e. a file attached to a model as above, or perhaps an uploaded file). If you need to construct a File yourself, the easiest way is to create one using a Python built-in file object: >>> from django.core.files import File # Create a Python file object using open() >>> f = open(' Behind the scenes, Django delegates decisions about how and where to store files to a file storage system. This is the object that actually understands things like file systems, opening and reading files, etc. Django’s default file storage is given by the DEFAULT_FILE_STORAGE setting; if you don’t explicitly provide a storage system, this is the one that will be used. See below for details of the built-in default file storage system, and see Writing a custom storage system for information on writing your own file storage system. Though most of the time you’ll want to use a File object (which delegates to the proper storage for that file), you can use file storage systems directly. You can create an instance of some custom file storage class, or – often more useful – you can use the global default storage system: >>> from django.core)
https://django.readthedocs.io/en/3.2.x/topics/files.html
CC-MAIN-2022-40
refinedweb
374
56.45
Hey Folks. I am working on a project in which i have to use Classes and do multiple things with different sorts of data. The basic question i have though is this: what am i doing wrong here in terms of this class declaration etc... i have looked around on here, other websites about classes, used my text book and my lecture notes - but none really correlate with how i need to set up this class/constructor etc. Please let me know how i could fix this to work it - and then i should be on a roll. Please include a brief description of where i could start if you dont wish to help me 100%! Thanks - your help is always appreicated! #include <iostream> #include <fstream> #include <ostream> #include <string> using namespace std; class Employee { private: //class variables char last_name[39]; char first_name[39]; char ss_num[9]; double salary; int years_employed; public: //class constructor Employee() { last_name = ""; first_name = ""; ss_num = ""; salary = 0; years_employed = 0; } //class methods void print(); void setName(char [], char []); void setSSN(char []); void setSalary(double); void setYearsEmployed(int); int getLeaveTime(); } ; int main() { Employee myName; myName("Hogan", "Tony", "12300123", 55000, 10); system("PAUSE"); return 0; } As you can see im trying to make a constructor with a last name, first name, SSN, salary and then years employed. I cant seem to get it working - im sure there is something obvious going on tho! CHeers
https://www.daniweb.com/programming/software-development/threads/99100/classes-basics-starting-implementation
CC-MAIN-2017-26
refinedweb
234
59.98
WARNING: Please do not use this code in your apps. It was just a quick experiment and is neither well tested nor secure. Updates: - February 23, 2012: I put the code for the category on GitHub and added a corresponding link to the article. I also added a custom prefix to the category methods to avoid possible namespace problems. - July 4, 2014: Added warning not to use the code. The codesign Utility On the command line, you can use the codesign utility to check whether a Mac app is signed. For example, codesign --display --verbose=4 /Applications/Preview.app will display a whole lot of info about Preview’s code signature: You can also use codesign to determine whether an app is sandboxed and, if so, list its sandboxing entitlements. The command codesign --display --entitlements - /Applications/Preview.app will display the contents of the entitlements property list that is embedded in the application binary: Doing it in Code Can we do the same in code? Yes we can. With a lot of help from my coworkers Jörg Jacobsen (see his work on XPC and Sandboxing for the iMedia framework) and Christian Beer (who pointed me to the source code for the codesign utility), I wrote a category on NSBundle that can tell you for any application bundle: - whether it has a valid code signature, - whether it is sandboxed and - whether it was downloaded from the Mac App Store. The public interface for the category looks like this and should be self-explanatory: Code Signing Services For the implementation, we need to look at the Code Signing Services in the Security framework. The SecStaticCodeCreateWithPath() takes the URL of an app bundle and returns a reference to a so-called static code object that represents the bundle’s code. We can then call the function SecStaticCodeCheckValidityWithErrors() on the static code object to obtain information about its code signature. Additional Requirements for the Signature (Sandboxing) To determine whether an app is sandboxed, we can call SecStaticCodeCheckValidityWithErrors() again, this time with the additional code requirement (passed as the third argument to the function) that the code object contains a certain entitlement (which is com.apple.security.app-sandbox in our case). The call to create this requirement looks like this: Have a look at the documentation for the Code Signing Requirement Language to learn how to formulate other requirements you might have. Mac App Store Receipt Check The implementation of the last method, -ob_comesFromAppStore, is rather unrelated. It simply checks whether the bundle contains a Mac App Store receipt. OS X 10.7 has a special method to find the App Store receipt in the bundle: appStoreReceiptURL. If 10.6 compatibility is important for you, you have to hard-code the path to the receipt at Contents/_MASReceipt/receipt. The Source Code Check out the full source code of the category below. I use associative references to cache the values of some variables that I use in multiple places, such as the code signature state. Update February 23, 2012: The code is now also available on GitHub.
http://oleb.net/blog/2012/02/checking-code-signing-and-sandboxing-status-in-code/
CC-MAIN-2016-07
refinedweb
513
52.19
May 102011 I don’t even know… Okay, I guess I do know, I made it. Why? I don’t even know. How? bge and a simple gravity script of course. wanna hear it? here is go! import bge from mathutils import Vector co = bge.logic.getCurrentController() scene = bge.logic.getCurrentScene() obList = [] for o in scene.objects: if o.__class__ == bge.types.KX_GameObject: obList.append(o) def calcGrav(obA, obB, G): m1 = obA.mass; m2 = obB.mass m = m1*m2 loc1 = obA.worldPosition loc2 = obB.worldPosition v = loc1 - loc2 r = v.length F = G * ( (m) / (r*r) ) return -v * F def loopGrav(obs, G): for obA in obs: fV = Vector((0,0,0)) for obB in obs: if obA != obB: fV += calcGrav(obA, obB, G) obA.applyForce(fV, False) loopGrav(obList, 1) keyb = bge.logic.keyboard if keyb.events[bge.events.ZKEY]>0: for ob in obList: ob.applyTorque(Vector((0,0,50)), False) if keyb.events[bge.events.XKEY]>0: loopGrav(obList, -2.5) if keyb.events[bge.events.CKEY]>0: loopGrav(obList, 15) HOW TO: – copy/paste script into blender text editor. – setup an EMPTY object with logic nodes as shown. – change ‘Engine’ from ‘Blender Render’ to ‘Blender Game’ – set World>Physics>Gravity to 0.0 (under Bullet) – create some objects. – hit ‘p’ This script will (should/might) make all meshes in the scene obey Newton. Up until the first rag doll shows sup, it looks like a bunch of rectanguloid piranhas having dinner. After skipping breakfast and lunch.
http://funkboxing.com/wordpress/?p=423
CC-MAIN-2017-43
refinedweb
251
73.13
Dash TableDash Table An interactive DataTable for Dash. QuickstartQuickstart pip install dash-table import dash import dash_table import pandas as pd df = pd.read_csv('') app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) if __name__ == '__main__': app.run_server(debug=True) BackgroundBackground Dash DataTable is an interactive table component designed for viewing, editing, and exploring large datasets. DataTable is rendered with standard, semantic HTML <table/> markup, which makes it accessible, responsive, and easy to style. This component was written from scratch in React.js and Typescript specifically for the Dash community. Its API was designed to be ergonomic and its behavior is completely customizable through its properties. DataTable was designed with a featureset that allows that Dash users to create complex, spreadsheet driven applications with no compromises. We're excited to continue to work with users and companies that invest in DataTable's future. Please subscribe to dash-table#207 and the CHANGELOG.md to stay up-to-date with any breaking changes. Note: DataTable is currently supported in Chrome, Firefox, Safari, Edge (version 15+), and Internet Explorer 11. Share your DataTable Dash apps on the community forum! ContributingContributing See CONTRIBUTING.md
https://juliapackages.com/p/dash-table
CC-MAIN-2021-25
refinedweb
206
52.15
WSGIScriptAlias / /some/path/project-1/wsgi.py If wanting to host a second Django instance under the same host name but at a sub URL, you would use: WSGIScriptAlias /suburl /some/path/project-2/wsgi.py WSGIScriptAlias / /some/path/project-1/wsgi.py If the Django instances are not under the same host, then it would instead simply be a matter of adding them to the respective VirtualHost. <VirtualHost *:80> ServerName site-1.example.com WSGIScriptAlias /some/path/project-1/wsgi.py ... </VirtualHost> <VirtualHost *:80> ServerName site-2.example.com WSGIScriptAlias /some/path/project-2/wsgi.py ... </VirtualHost> In both cases, whether under the same host name or different ones, both Django instances would run in the same process. Separation would be maintained however by virtue of mod_wsgi running each WSGI application mounted using WSGIScriptAlias in a distinct Python sub interpreter within the processes they are running in. The directive which controls which named Python sub interpreter within the process is used is WSGIApplicationGroup. The default for this directive is %{RESOURCE}. For this default value of %{RESOURCE}the sub interpreter name will be constructed from the host name (as specified by the ServerName directive), the port (if not port 80/443) and the value of the WSGI environment variable SCRIPT_NAME as deduced from the URL mount point set by the WSGIScriptAlias directive. So in the first instance above where both Django instances run under the same host name, the distinct named sub interpreters within the process would be called: site-1.example.com:/ site-1.example.com:/suburl In the second instance where they run under separate host names they would be: site-1.example.com:/ site-2.example.com:/ So as long as you don't fiddle with which sub interpreter is used by specifying the WSGIApplicationGroup directive, mod_wsgi should maintain separation between the multiple Django instances. What therefore can go wrong and why would requests get routed to the wrong Django instance? Ordering of WSGIScriptAlias directives. The first scenario where one may see requests being handled by the wrong Django instance is where the multiple Django instances are running under the same host name and the ordering of the WSGIScriptAlias directives is wrong. When using the WSGIScriptAlias multiple times under the same host name, it is important that the WSGIScriptAlias for sub URLs comes first. In other words, the ordering is such that the most deeply nested URLs must come first. If you don't do that, then the shorter URL will match first and take precedence, thereby swallowing up all requests for both Django instances. For example, if the directives above were instead written as: WSGIScriptAlias / /some/path/project-1/wsgi.py WSGIScriptAlias /suburl /some/path/project-2/wsgi.py The solution if this is the cause is obviously to reorder the WSGIScriptAlias directives as appropriate to ensure the longest URLs come first. Leaking of process environment variables. In order to specify the module that the Django applications settings are contained in, it is necessary to set the process environment variable DJANGO_SETTINGS_MODULE. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() When using Apache/mod_wsgi, this is done in the WSGI script file and the environment variable would be set in os.environ when the WSGI script file is loaded. As much as process environment variables and global variables have their limitations and are arguably a bad idea for specifying configuration, this has still worked okay until recently. Problems started when Django 1.4 was released however. In Django 1.4 the content of the WSGI script file was changed from what was described previously for Django 1.3 and older versions to: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Although the differences on first glance appear to be fine, they aren't and the WSGI script file in Django 1.4 will break Apache/mod_wsgi for hosting multiple Django instances in the same process. The key problem is what the setdefault() method does when setting the environment variable DJANGO_SETTINGS_MODULE compared to using assignment as previously. In the case of assignment the environment variable is always updated. For setdefault(), it is only updated if it is not already set. You might ask why would this be a problem. It is a problem because although os.environ looks like a normal dictionary, it isn't. Instead it is actually a custom class which only looks like a dictionary. When a key/value is set in os.environ, it is also setting it at the C level by calling putenv(). What now happens with our multiple Django instances running in the same process is that for the first one to be loaded, DJANGO_SETTINGS_MODULE will not be set and so setdefault() will actually set it, including it being set globally to the process. When the second Django instance is loaded, at the point the sub interpreter is created, os.environ is populated from the C level environ, thereby picking up the value of DJANGO_SETTINGS_MODULE set when the first Django instance was loaded. In this case setdefault() will not override the value as it already sees it as being set. Technically this leakage of environment variables between Python sub interpreters within the one process would always happen, but use of setdefault() instead of assignment means DJANGO_SETTINGS_MODULE will not get overridden to be the correct value for the second Django instance to be loaded. The end result of the leakage can be one of two things. If the name of the Django settings module used for the first Django instance doesn't exist in the context of the second Django instance, then an import failure will occur and the Django instance will fail to be initialised. In this first case an actual failure will occur with nothing working and so it will be fairly obvious. A more problematic case though is where you are using one code base and multiple Django settings modules for each of the distinct Django instances being run. In this case the Django settings module may well be found, with the result being that when attempting to load up the second Django instance, a duplicate of the first instance would be loaded instead. Where URLs are now meant to be routed to the second instance, they would instead be handled as if being sent to the first instance as the configuration for the first is still being used. There are two solutions if this is the cause. The quickest is to replace the use of setdefault() to set the environment variable in the WSGI script file with more usual assignment. os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' An alternative which involves a bit more work, but can have other benefits, is to switch to using daemon mode of mod_wsgi to run the Django instances and delegate each to a separate set of processes. By running the Django instances in separate processes there can be no possibility of environment variables leaking from one to the other. WSGIDaemonProcess project-2 WSGIScriptAlias /suburl /some/path/project-2/wsgi.py process-group=project-2 WSGIDaemonProcess project-1 WSGIScriptAlias / /some/path/project-1/wsgi.py process-group=project-1 Fallback to default VirtualHost definition. Apache supports hosting of sites under multiple host names by way of name based virtual hosts. These are setup with the VirtualHost directive as previously shown. <VirtualHost *:80> ServerName site-1.example.com ServerAlias WSGIScriptAlias /some/path/project-1/wsgi.py ... </VirtualHost> <VirtualHost *:80> ServerName site-2.example.com WSGIScriptAlias /some/path/project-2/wsgi.py ... </VirtualHost> The ServerName directive specified within the VirtualHost gives the primary host name by which the site is identified. If the same site can be accessed by other names, the ServerAlias directive can be used to list them explicitly, or by using a wildcard pattern. What is not obvious however is if there are any host names by which the server IP is addressable and they are not covered by a ServerName or ServerAlias directive, rather than Apache giving an error, it will route the request to the first VirtualHost definition it found when it read its configuration. In the above example, if the host name '' also existed and mapped to the server IP, because that host name wasn't covered by a ServerAlias directive for the second VirtualHost, the request would actually end up being handled by the Django instance running 'site-1.example.com'. To address this problem you simply need to be diligent in ensuring that you have correctly mapped all host names you wish to have directed at a site. Using mod_wsgi daemon mode will make absolutely no difference in this situation as it is Apache that is routing the request to the wrong VirtualHost before the request even gets passed off to mod_wsgi. As a failsafe to pick up such issues and ensure that requests don't unintentionally go to the wrong site, a good practice may be to ensure that the first VirtualHost that Apache encounters when reading its configuration is actually a dummy definition which doesn't equate to an actual site. <VirtualHost _default_:*> Deny from all </VirtualHost> This could then be setup to fail all requests by way of forbidding access. A custom error document could also be used to customise the error response if necessary. 16 comments: In 2012, with modern Python/Apache/mod_wsgi/etc. why would someone choose not to use WSGIDaemonProcess by default? I strongly prefer it for reliability and security (when using a separate user, of course) and have thought that some of the deployment questions I've seen in the Django world could be avoided if the default recommendation was to use a daemon rather than in-process instance. P.S. Is out of date? It doesn't mention the "WSGIScriptAlias … process-group=" syntax but does mention the presumably equivalent WSGIProcessGroup directive. Yes, the mod_wsgi documentation has lots of stuff missing. And yes daemon mode is the better option for most. I'll hopefully be saying more about this in future blog post and if not at PyCon if talk gets accepted. Wish I had more time. :-) Great work Graham, thank you for all your effort. It looks like you are the only one working on this project, is it really so? Fed. Yep, only one mad enough to do it. Unfortunately don't get as much time to devote to it now as I once did. how come nobody else in the python community wants to help? I think it is not your fault if you can't dedicate time to it, it's open source, those who use it should contribute. Have you ever tried mentoring a student for the Google Summer of Code? More a case of when I was working on this I was moving so quick was hard for anyone to catch up with what was going on so as to be able to contribute. Now it is very stable and so the need to do anything else has dropped dramatically. Delving into the C APIs of both Apache and Python also isn't going to be of interest to most people, so was always going to be a very small pool of people one could draw from. If you specify "WSGIScriptAlias … process-group=" syntax or the WSGIProcessGroup doesn't that only work if you are running Apache as root? WSGIScriptAlias and WSGIDaemonProcess group directives can only be added into the main Apache configuration file and not in a .htaccess file. Typically the main Apache configuration will require root access to modify the configuration files. That is the only way root comes into it. The feature implemented by those directives works fine if Apache was started as a user other than root. This is really helpful. I had problem with environment variables leakage between processes and I realized, that I hadn't been using attribute "process-group" in WSGIAlias command. @Tomas The leakage of environment variables is between Python sub interpreters within the one process, not between separate processes. Thanks Graham, Your article clearly explained my problem and enabled me to efficiently fix it and to understand apache a little better as a bonus. Thank you for posting this Graham. I seem to have been running into your answers on a lot of Django deployment questions I've been searching lately. I appreciate the sharing! I could not confirm that using assignment on environ solves the problem when using multiple threads with apache. Two threads may call os.environ[...] = settings1, then settings2 in sequence and the end result will be that both will run with settings2. Can you confirm this ? I'm currently experiencing lots of invalid ALLOWED_HOSTS errors in my dual virtual host setup and the only explanation I have right now is that the settings are being overridden by the wsgi handler. I can't confirm that the assignment is the sole problem because things are slightly more complicated since I'm using django-configurations and the racy variable is actually DJANGO_CONFIGURATION. I also noticed that I'm creating one WGSIApplication per request, which may be also worsening the situation: @hdante If you are specific help in working out an issue, please use the mod_wsgi mailing list as mentioned at: In short though, setting os.environ to different values on a per request basis is dangerous in any multithreaded application and not just mod_wsgi and will cause lots of issues. You should never do that. You should find a different way of achieving whatever it is you want to do. Use the mailing list to provide better information on the actual problem you are trying to solve rather than trying to debug your solution. @Graham The point is that the text suggests, as solution for multiple django settings "to replace the use of setdefault() to set the environment variable in the WSGI script file with more usual assignment". This is not supposed to work if apache is using worker or event MPM, because starting 2 threads would cause a race when setting the environment variable on each thread. @hdante The use of assignment is not a race condition for the documented example given in the blog post because it is done at global scope within the WSGI script file. The WSGI script file would be loaded once and the loading is under the context of an import lock and so only one request thread can trigger the loading. There is thus no possibility for the assignment in that specific WSGI script to be done concurrently from multiple threads. If however you do the assignment within the application() function as you do on a per request basis, and which I already said you shouldn't do because that whole concept is fundamentally broken if the value can change per request, then you will have problems. As I already said, use the mod_wsgi mailing list if you want to have a discussion about this. Using the comment section of a blog post is not the proper forum for a discussion.
http://blog.dscpl.com.au/2012/10/requests-running-in-wrong-django.html
CC-MAIN-2014-52
refinedweb
2,511
53.41
Hi all, I've been doing some reading about calling a non static variable or method from a static context, and almost but not quite have my head around what exactly is going on. I've read the text but can't seem to put that into context, so please bare with me. I'm doing a program to simulate a student enrolment system (Unique huh!) I have most of the functionality that I need, with exception to searching the array to match based on an attribute but that I will work on later. The project has a hard coded array of students which is then used to search through for a matching year started at the place of study. I'm having problem with my printEnrolment() method from my Enrolment class, I used the addStudent() method in Enrolment to add the students to the array using the Student constructor, and that works without drama. I then put all of the information into a readable format using printDetails() which returns a String which I then want to use in the printEnrolment() method under the Enrolment class, which is where I get the dreaded non static error. Now from what I can tell, I somehow need to create an instance of the printDetails() method so that I can call it from the static printEnrolment() method, but i'm not quite sure as to how I should approach that. Will my printEnrollment() method not work until I implement the search function? Like, create a temp Student in the array to compare values against the array? Is creating a temp student even the best way to achieve this? Any advice to point me in the right direction would be very much appreciated! Code below - Error line 23 of Enrolment public class enrolment { public static void addStudent() { //Create objects of Student class Student[] unistudent = new Student[6]; unistudent[0] = new Student("Al", "Capone", "Male", 12345671, "0419817271", 2006); unistudent[1] = new Student("Bob", "Builder", "Male", 12345672, "0419817271", 2007); unistudent[2] = new Student("Carol", "Candlelight", "Female", 12345673, "0419817271", 2007); unistudent[3] = new Student("Dirk", "Diggler", "Male", 12345674, "0419817271", 2007); unistudent[4] = new Student("Ebony", "Star", "Female", 12345675, "0419817271", 2008); } public void getStudent() { // Used for searchStudent() in main } public static void printEnrolment() { String details = Student.printDetails(); // <----- ERROR IS HERE System.out.println(details); } } class Student { private String firstName, lastName, gender, phoneNumber, details; private int studentID,yearStarted; public Student(String firstName, String lastName, String gender, int studentID, String phoneNumber, int yearStarted) { this.firstName = firstName; this.lastName = lastName; this.gender = gender; this.studentID = studentID; this.yearStarted = yearStarted; this.phoneNumber = phoneNumber; } private String getFirstName() { return this.firstName; } private String getLastName() { return this.lastName; } private String getGender() { return this.gender; } private String getPhoneNumber() { return this.phoneNumber; } private int getStudentID() { return this.studentID; } private int getYearStarted() { return this.yearStarted; } public String printDetails() { String details = ("First Name: " + getFirstName() + "\nLast Name: " +getLastName() + "\nStudent ID: " + getStudentID() + "\nGender: " + getGender() + "\nPhone No: " + getPhoneNumber() + "\nYear Started: " + getYearStarted() +"\n\n"); return this.details; } } public class admin { public static void main(String args[]) { fillData(); } public static void fillData() { enrolment.addStudent(); enrolment.printEnrolment(); } public void searchStudent() { // Not yet started } }
https://www.daniweb.com/programming/software-development/threads/371955/static-non-static-methods-searching-array-question
CC-MAIN-2021-43
refinedweb
518
54.73
Supporting Information - StackExchange thread on how to successfully use the UART on the Raspberry Pi 3 (it’s not as simple as you might think) Out with the Wand, In with the Pi Electronics projects, like so many other things in life, don’t always work out the way we expect. This has definitely been the case with the C-BISCUIT demo bot, which has taken a few twists and turns on its way to becoming a functional system. And the biggest twist/turn of all happened at the end, when we decided to eliminate the Wandboard and replace it with a Raspberry Pi 3. The dominant reason for this change was quite simple—the Wandboard had become an obstacle to our primary design goal, namely, transmitting live video from the robot to a computer via Wi-Fi. No one on the C-BISCUIT team knew exactly how to accomplish this after our initial attempt failed. It was one of those situations where we expected the third-party software environment to handle the details of the video transmission and, when it became clear that this was not exactly the case—well, let’s just say that the Wandboard quickly fell out of favor. Fortunately, Patrick came up with the excellent idea of shelving the Wandboard and using a Raspberry Pi instead. This also meant using the Raspberry Pi Camera instead of the WandCam, because of course we cannot expect a Wandboard camera to seamlessly interface to a Raspberry Pi (and seamless is what we want here—maybe there’s some way to make a WandCam talk to a Pi, but we’d much rather pay another $30 for a camera that just works). Why the Pi? The Raspberry Pi has more fully-developed software support than the Wandboard, and it gives us access to a larger pool of experience (from both AAC contributors and the wider RPi community). It is also smaller and less expensive than the Wandboard. It’s possible that the Pi is not powerful enough for some of the image processing tasks that we want C-BISCUIT to support, but we can worry about that later. For now, we just need the wireless video feed and some basic serial communication, and the RPi 3 can certainly provide that functionality. And we certainly have no regrets about using the Pi Camera (version 2). This module does indeed interface effortlessly to the RPi, and it provides high resolution (8 megapixels) along with a variety of useful features (customizable output resolution and frame rate, image rotation, brightness and contrast adjustment, etc.). So now you know why C-BISCUIT ended up with a Pi instead of a Wand; here is the updated block diagram: Fortunately, the RPi can use the same 5 V supply and UART connections that were originally intended for the Wandboard, so we didn’t need to make any modifications to the Robot Control Board (RCB). Hooray! The Hardware Let’s take a look at how the robot is assembled, and then we’ll cover some details regarding the video and communication interfaces. So the battery and RCB are on the upper level, and the RPi is down below. The camera is simply inserted into the dual-row header near the front edge of the RCB; I wrapped some electrical tape around the back row of pins so that they don’t short out anything on the back side of the camera PCB (the tape also ensures a snugger fit). This arrangement wouldn’t be adequate for rough terrain, but it should be fine for initial testing and demonstration. Here are a few more assembly details: - The bot is enabled whenever 12 V is delivered to the RCB, and 12 V is delivered to the RCB whenever the two power connectors are mated and the power switch is closed. - The RPi is powered via its USB connector. I simply chopped off one end of a standard Micro USB cable and then connected the power and ground wires to the 5 V and GND screw terminals on the RCB. It turns out that the red wire is power and the black wire is ground, and I might dare to assume that all cable manufacturers follow this rather well-established color-code custom; nevertheless, always break out your multimeter and find a way to double-check the pinout before you plug everything in and flip the switch. - Serial communication is enabled via two wires from the RPi’s UART Tx and Rx pins to the RCB’s UART Rx and Tx signals. A ground wire is not necessary because the power-supply connection ensures that the RCB and RPi are at the same ground potential. It would be good to include a ground specifically for the UART interface if we were worried about signal integrity, but in this case we’re not pushing any limits—we’re using 3.3 V logic at the astonishing rate of 9600 baud, and the UART lines have decent physical separation from the noisy motors. - Notice how I have the robot resting on a book such that the tank treads are not in contact with the surface. This is a simple and very effective way to prevent the nightmare scenario in which your robot goes careening off your workbench after you experience a firmware malfunction or accidentally knock the power switch or what not. Best RPi Video Software in the World Well, OK, I only tried two techniques; the first one didn’t work and the second one did. But after the difficulties with the Wandboard and the convoluted failure produced by the first RPi attempt, it was extremely impressive to see how well the second solution performed. The software package is called the RPi Cam Web Interface, and you can read all about it here. I’m going to skip the details because the extensive wiki has everything you need to know to get started. The overall process is as follows: Connect the RPi to your network, either through a cable or Wi-Fi. Install the software on the RPi and run it. Then you simply open up your favorite browser and connect to the video stream by typing "" into the address bar (see the wiki for details). What you see is this: The low-latency video appears in the browser window, and you can also capture images or video and modify camera settings: This Is Not an Autonomous Robot The robot won’t be very useful if all it can do is move around in circles or drive forward until it hits a wall. Thus, we need a convenient way to control its movement, and that is exactly what the following Python script provides: import serial ser = serial.Serial( port='/dev/ttyS0', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) while True: response = raw_input("Enter command: ") if response == "forward": ser.write("forward\r".encode()) elif response =="reverse": ser.write("reverse\r".encode()) elif response == "go": ser.write("go\r".encode()) elif response == "stop": ser.write("stop\r".encode()) elif response == "s": ser.write("stop\r".encode()) elif not response: ser.write("stop\r".encode()) elif response == "rotate r": ser.write("rotate r\r".encode()) elif response == "rotate l": ser.write("rotate l\r".encode()) elif response == "low speed": ser.write("low speed\r".encode()) elif response == "high speed": ser.write("high speed\r".encode()) elif response == "very high speed": ser.write("very high speed\r".encode()) elif response == "battery voltage?": ser.write("battery voltage?\r".encode()) print(ser.read(23)) elif response == "disable battery protection": ser.write("disable battery protection\r".encode()) elif response == "enable battery protection": ser.write("enable battery protection\r".encode()) elif response == "exit": break The script itself is self-explanatory. It asks for input and then looks at the string entered by the user in order to determine which (if any) ASCII message should be transmitted over the UART. The EFM8 microcontroller on the RCB then receives the message and controls the motors accordingly. But how do we use the script if we have no direct access to the RPi? That’s where SSH comes in. (Click here for more information on controlling a Raspberry Pi via SSH.) We already have the Wi-Fi network connection, so we simply SSH into the RPi and then run the script via the console. One thing you might notice in the Python script is that there are three commands for stop. In addition to “stop,” we also have “s” and an empty string. This is an important feature because it ensures that you will be able to stop the robot quickly, even under pressure. Let’s say that you get distracted for a minute and the next thing you know, your bot is about to tumble down a staircase, or run into a door at high speed, or knock over your favorite houseplant. You might not have time to type “stop,” and that’s why the script is designed to interpret “s” as “stop”—surely you have time to hit one letter and then the enter key. But then there is the worst-case scenario: your robot is in serious danger and you panic. Maybe you can’t remember the stop command, or maybe you’re in such a rush that you hit the wrong key when you’re trying to send an “s” command. Well, you’re covered here too, because all you have to do to stop the robot is press the enter key! If you press nothing more than enter, the return string from the raw_input() function will be empty, and the script interprets an empty string as a stop command. This screenshot gives you the sequence of commands for the robot movements shown in the video that follows: The Firmware The firmware is pretty straightforward. There is a simple UART interface for communication with the RPi, and the programmable counter array (PCA) is used to generate the PWM motor-drive signals. You can use the following link to download all the source and project files. The code uses descriptive identifiers and is thoroughly commented, so you shouldn’t have much trouble understanding the details. One thing you will notice is additional files and code for USB communication. You can ignore this for now because USB functionality is not implemented in the demo-bot firmware. Conclusion We now have a fully functional C-BISCUIT demonstration robot, which means that this series of articles is complete. However, remember that C-BISCUIT is not a single robot but rather a platform for robotics projects. In other words, this demo bot is only the beginning!
http://www.allaboutcircuits.com/projects/c-biscuit-system-integration-and-testing/
CC-MAIN-2017-04
refinedweb
1,779
59.43
Hello, J.. You write 16 мая 2008 г., 4:27:07: JS> On Thu, May 15, 2008 at 11:50 PM, Dmitriy S. Sinyavskiy <[EMAIL PROTECTED]> wrote: >> So what about my patch and test? >> Is it right or someone can correct it? >> The silence is here for a week or more ( >> JS> Jonathan Rockway asked you to regenerate without whitespace changes. JS> Just waiting on that from you to properly review it. JS> -J It strange I haven't got received letter with this...may be deleted by antispam ( Nevertheless I've done it now: Index: Catalyst.pm =================================================================== --- Catalyst.pm (revision 7759) +++ Catalyst.pm (working copy) @@ -948,10 +948,12 @@ my $params = ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} ); + $path =~ s!/+!/!g; # strip extra slashes '///' + unshift(@args, split('/', $path)); carp "uri_for called with undef argument" if grep { ! defined $_ } @args; s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args; - unshift(@args, $path); + unless (defined $path && $path =~ s!^/!!) { # in-place strip my $namespace = $c->namespace; --:
https://www.mail-archive.com/catalyst@lists.scsys.co.uk/msg03184.html
CC-MAIN-2022-27
refinedweb
167
78.04
Radix Primitives can be rendered on the server. However a little setup is required to make sure they work properly. Server side rendering or SSR, is a technique used to render components to HTML on the server, as opposed to rendering them only on the client. Static rendering is another similar approach. Instead it pre-renders pages to HTML at build time rather than on each request. You should be able to use all of our primitives with both approaches, for example with Next.js or Gatsby, with very little setup required. The way SSR works with React is by rendering components to HTML on the server and then hydrating the HTML, thus enhancing it with interactivity. For all of this to function properly, React has to match the DOM structure between client and server. This is potentially an issue for Radix Primitives because we rely on generating random ids internally so that accessibility works out of the box. To enable more deterministic ids between server and client and ensure that no mismatch occurs, wrap your app with our IdProvider like so: import { IdProvider } from '@radix-ui/react-id';export default () => (<IdProvider><App /></IdProvider>);
https://www.radix-ui.com/docs/primitives/overview/server-side-rendering
CC-MAIN-2021-43
refinedweb
194
54.22
Converting the minimal Hello World and the simple example from C to C++ (actually g++ 4.4.5 on Linux Debian for Apache 2.2) took a minimal effort. What I had to do was adding an explicit include directive for http_protocol.h, to let the less forgiving C++ compiler to properly check against a few functions. Not doing it was leading to these errors: error: ‘ap_set_content_type’ was not declared in this scope error: ‘ap_rputs’ was not declared in this scope error: ‘ap_rprintf’ was not declared in this scopeBesides, I also removed the static specification for all the local function, and put them instead in an unnamed namespace. Finally I wrote this Makefile: all: mod_hello.so mod_hello.o : mod_hello.cpp g++ -c -I/path/to/apache22/include -fPIC mod_hello.cpp mod_hello.so : mod_hello.o g++ -shared -o mod_hello.so mod_hello.o clean: rm -rf mod_hello.o mod_hello.soTo build the object I called g++ with a few options: -c because I don't want it to run the linker, its output should be the object file. -I to specify the apache include directory (put there your actual one). -fPIC is due to the fact that we are about to create a shared object, so we need g++ to generate position-independent code. The actual generation of the shared object is accomplished by second call to g++, this time specifying as options: -shared to let it know that a shared object is what we want. -o to specify the output file name. Remember that in a Makefile you should put TAB and only TAB (no white spaces at all!), if you don't want to get a puzzling error like this: Makefile:6: *** missing separator. Stop.
https://thisthread.blogspot.com/2012/11/makefile-for-c-apache-module.html
CC-MAIN-2017-51
refinedweb
285
64.2
[Date Index] [Thread Index] [Author Index] Re: How smooth graphs?. Another option is to export each of the frames from Mathematica as they are created at about 4 times their desired final size. Then, you can import the frames into an application such as Adobe Photoshop and resize them down to the size you want. Photoshop, and perhaps some other applications, will automatically anti-alias raster graphics during this process. Anti-aliasing vector graphics (such as those in Mathematica) is trickier than for raster images. Photoshop only deals with raster images. Of course this requires that you have such an application available to you. If not, the code linked from the example above should work, but it will probably be slower. The bigger the image the longer it will take, and both options require you to rasterize the graphic (e.g. save/store the graphics object as a bitmap image). At 1024x768, this method will take a long time. There's no way I know of to do this in real-time. You might be able to make the effect less noticeable by choosing different colors, but this just masks the effect, it doesn't get rid of it. ? >
http://forums.wolfram.com/mathgroup/archive/2005/Oct/msg00549.html
CC-MAIN-2015-40
refinedweb
199
64.91
This is the second part of the two part series of "Say Hello to Behavior Driven Development". The first part of this series is Say Hello To Behavior Driven Development (BDD)- Part 1. In this article, I shall try to show you how to follow BDD in real life while starting development of any module or project. Please note that this article will only concentrate on showing the path of using BDD methodology in real life project rather than 100% full fledged project developed using BDD. I have attached a skeleton of .NET project (as UI component here, I have used WPF) that has been developed with steps as described below. At the end of the day, by implementing BDD you need to write some Unit test code and you need some tool that supports Unit Testing like NUnit, MSTest (integrated with Visual studio) or any other flavor you like. For this example, I shall use MBUnit. But you are free to use any such tool you like.For converting Gherkin to Unit Test code, I shall use SpecFlow. I like Specflow because it the Coolest BDD tool I have ever seen for .NET. For IDE, I shall use Visual Studio 2010. I am lucky to have license of ReSharper and in this example I shall take some help from ReSharper as it gives some integrated test output result. If you don’t have ReSharper, don’t worry as I only used that tool to ease some step. You can, of course, proceed without Resharper. Let the show begin! Since we shall develop something following Behavior Driven Development, at first, we should have some requirement in Gherkin. So here is one simple requirement. Given that we have a search form that searches over Name, Address and Profession table When The user enters non empty text And the length of the text is more than 3 alphanumeric character long Then The user will get the search result And if the search result is empty he will get an message box asking him to do the search again. So let's open Visual Studio 2010 and create two class library projects like below: Since we are creating everything from scratch, we have created two projects. SearchSpec will basically contain Gherkin to CS specification code. Carefully note that the project name is SearchSpec not SearchTest, since we shall write down the behavior or specification not test. SearchSpec SearchTest We have another class library project called SearchModule that will hold all the necessary code that would meet our specification. SearchModule We would add one configuration file in SearchModule project like below: After that, we will paste the following configuration in the App.Config file: <?xml version="1.0"?> <configuration> <configSections> <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/> </configSections> <specFlow> <unitTestProvider name="MbUnit"/> </specFlow> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> After pasting this, the App.config file will look like this. The first config section is related with the Specflow and the second one is related with the Unit Test tool that we will be using. As the picture says, you can use any Unit Testing tool you like. The reason we are using this configuration file is because when the Gherkin is trans coded to CS code, it is written as per the Unit Test Tool mentioned in the configuration file. Now we shall add one Feature file. Since it is assumed that SpecFlow has already been installed so in Visual Studio we will get 3 extra templates installed for SpecFlow. Among the 3, we shall choose Feature file like below. We will name it Search.feature and will press OK. Search.feature Visual Studio will create two files for us. One feature file containing the feature of specification in Gherkin and one code behind associated with feature file which contains generated C# code related with feature, that is C# representation of Gherkin as shown below. Please note that whenever Visual Studio creates any feature file, it gives a dummy feature related with some mathematics. Needless to say here, you need to add necessary reference of Spec Flow, Gallio and MBUnit in your project like below that can be found in their respective installation folder. Now we would change the content of feature file with our simple specification. We will just paste our specification there and will save the feature file. After saving the feature file corresponding CS code will be generated in code behind. Pretty cool, isn't it? The feature file and code behind will be looking like below: We have got our feature coded in CS. Now we need another level abstraction so that for each of the steps as described in our feature (and off-course in feature.cs) file can be defined. (Look I haven't used the word “test”. I could have written “so that each of the step can be tested.” Since we are using BDD, we will develop our feature by defining steps not by defining TEST! ) test Fortunately Specflow gave us a template for creating step definition. So we shall add one step definition file named SearchStepDefination.cs like below: But once the step definition file is generated, you will again see some preloaded code related with mathematics which is not at all related with our feature. Like below, it is trivial that we need to remove these dummy code. But the question is how can I write step definition since I don't know how to write step definition. (A blocking state!!!) Don't worry!!! We have an easy solution and again this code will be written by SpecFlow engine, but not in a very usual way! Let me show you how we can generate Step Definition based on our feature in step by step (yes! these are some sub steps). SearchStepDefinition [Binding] public class SearchStepDefinition { } SearchingInDataBaseTables I know right at this moment you are smiling. As you have rightly noticed, the output window is telling what functions are needed to be implemented in Step Definition file with proper signature! Our foundation has been created and now we can start development by following pure BDD. We will now write the body of the each step definition method and while writing this, we will actually write code related with the original development. Let's concentrate on the first method. [Given(@"that we have a search form that searches over Name, Address and Profession table")] public void GivenThatWeHaveASearchFormThatSearchesOverNameAddressAndProfessionTable() { ScenarioContext.Current.Pending(); } In order to write the body of this method, we need to create a form that will take input from user. So we need to have some place holder that will contain the input text. So we will create a class for this under SearchModule project. The class will be looking like below: namespace SearchModule { public class UserInput { public string Input { get; set; } } } We also need to create a form. For this, we can create another project under the same solution. I am going to choose a WPF project like this, so that we will have a WPF window having a text box and a search button and it will look something like below: Now we will need to have a class that will be able to search over Name, Address and Profession table. So our next steps will be: Name Address Profession I am not going to show you how to do the above 3 steps as these are the most trivial things you do in your day to day life. As you can see, we are now trying to create classes and variables just to meet step definition functions and step by step we are actually creating our module in such a way that meets the behavior aka specification of the project and thereby we have started developing a module following Behavior Driven Development methodology. I could have written a few hundred lines more to make a complete module using BDD but my target is to show you the path that will ultimately lead you to implement BDD in your own project. I hope you got the basic idea and tips/tricks to start Behavior Driven Development right from your next project. I wish you all the.
http://www.codeproject.com/Articles/150740/Say-Hello-To-Behavior-Driven-Development-BDD-Part?fid=1607032&df=90&mpp=10&sort=Position&select=3783539&tid=3783539
CC-MAIN-2015-18
refinedweb
1,373
62.07
Exploring Spark DataSource V2 - Part 2 : Anatomy of V2 Read second blog in the series where we discuss about different interfaces to read data in V2 API.Understanding these interfaces helps us to understand the design and motivation of v2 API.You can read all the post in the series here. Java Interfaces One of the characteristics of V2 API’s is it’s exposed in terms of Java interfaces rather than scala traits. The primary reason for this is better interop with java. The below are the basic interfaces to read the data in V2 API. DataSourceV2 DataSourceV2 is a marker interface. It doesn’t have any methods to override. Extending this interface we indicate that we are implementing support for V2 datasource. ReaderSupport ReaderSupport is interface which indicates that datasource supports reading that. There is similar interface for write also. In this post we only focus on the reading. It has single method with below signature def createReader(options: DataSourceOptions):DataSourceReader From the above signature it’s clear that,it’s an entry point method for data source. DataSourceOptions is a map which contains all the options specified by the user to this data source. This method creates DataSourceReader. DataSourceReader DataSourceReader is the primary interface for actually responsible for two things of reading. They are Schema Inference def readSchema():StructType The above method is responsible for schema inference. DataReader Factory def createDataReaderFactories:List[DataReaderFactory] DataReaderFactory is a factory class to create actual data readers. Number of data factories determines the number of partitions in the resulting DataFrame. DataReaderFactory It’s a factory class to create actual data readers. The data reader creation happens on the individual machines. It exposes single method. def createDataReader:DataReader As the name suggest, it creates data reader. DataReader Finally we have the interface which actually reads the data. The below are methods def next : Boolean def get : T As you can see from interface, it looks as simple iterator based reader. Currently T can be only Row. No Depednecies on High Level API One of the observation from above the API’s, there is no more dependency on RDD, DataFrame etc. This means these API’s can be easily evolved independent of change in user facing abstractions.This is one of the design goals of the API to overcome limitation of earlier API. References Spark Jira For Data Source V2. Conclusion In this post we discussed some of the important interfaces from datasource V2 API for reading data. You can see how this API is much different than earlier API.
http://blog.madhukaraphatak.com/spark-datasource-v2-part-2/
CC-MAIN-2018-34
refinedweb
427
50.02
Imagine, we are writing text processor. Now we have two requirements for our text processor: - have three fonts - add ability to color a text So, text would look like this: Ok. We have understood a task. So let’s try to implement this task. … Imagine, we are writing text processor. One of requirements to text processors is to have three fonts: - font 1: A - font 2: A - font 3: A Ok. We have understood a task. So let’s try to implement this task. One of the implementation would be: public class…) //… State pattern As wikipedia says: The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. Simple example of finite-state machine is vending machine which state depends whether you…
https://nicestepup.medium.com/?source=post_internal_links---------1----------------------------
CC-MAIN-2021-43
refinedweb
144
75.5
By Sean T. Allen The best place to see whether any of Storm's internal buffers are overflowing is the debug log output in Storm's logs. Assuming you're using a shuffle grouping to distribute tuples evenly among bolts and tasks, checking the value for any task of a given bolt should be enough to determine how close you are to capacity. If you're using a grouping that doesn't evenly distribute tuples among bolts and tasks, you may have a harder time quickly spotting the problem. A little automated log analysis should get you where you need to be, though. The pattern of the log entries is well established, and pulling out each entry and looking for population values that are at or near capacity would be a matter of constructing and using an appropriate tool. Once you find some internal Storm buffers overflowing, you can address them in one of four primary ways. These aren't all-or-nothing options—you can mix and match as needed in order to address the problem: - Adjust the production-to-consumption ratio - Increase the size of the buffer for all topologies - Increase the size of the buffer for a given topology - Set max spout pending Let's cover them one at a time, starting with adjusting the production-to-consumption ratio. Adjust the production-to-consumption ratio Producing tuples slower or consuming them faster is your best option to handle buffer overflows. You can decrease the parallelism of the producer or increase the parallelism of the consumer until the problem goes away (or becomes a different problem!). Another option beyond tweaking parallelism is to examine your user code in the consuming bolt (inside the execute method) and find a way to make it go faster. For executor buffer-related problems, there are many reasons why tweaking parallelism isn't going to solve the problem. Stream groupings other than shuffle grouping are liable to result in some tasks handling far more data than others, resulting in their buffers seeing more activity than others. If the distribution is especially off, you could end up with memory issues from adding tons of consumers to handle what is in the end a data distribution problem. When dealing with an overflowing worker transfer queue, "increasing parallelism" means adding more worker processes, thereby (hopefully) lowering the executor-to-worker ratio and relieving pressure on the worker transfer queue. Again, however, data distribution can rear its head. If most of the tuples are bound for tasks on the same worker process after you add another worker process, you haven't gained anything. Adjusting the production-to-consumption ratio can be difficult when you aren't evenly distributing tuples, and any gains you get could be lost by a change in the shape of the incoming data. Although you might get some mileage out of adjusting the ratio, if you aren't relying heavily on shuffle groupings, one of our other three options is more likely to help. Increase the size of the buffer for all topologies We'll be honest with you: this is the cannon-to-kill-a-fly approach. The odds of every topology needing an increased buffer size are low, and you probably don't want to change buffer sizes across your entire cluster. That said, maybe you have a really good reason. You can change the default buffer size for topologies by adjusting the following values in your storm.yaml: - The default size of all executors' incoming queue can be changed using the value topology.executor.receive.buffer.size - The default size of all executors' outgoing queue can be changed using the value topology.executor.send.buffer.size - The default size of a worker process's outgoing transfer queue can be changed using the value topology.transfer.buffer.size It's important to note that any value you set the size of a disruptor queue buffer to has to be set to a power of 2—for example, 2, 4, 8, 16, 32, and so on. This is a requirement imposed by the LMAX disruptor. If changing the buffer size for all topologies isn't the route you want to go, and you need finer-grained control, increasing the buffer sizes for an individual topology may be the option you want. Increase the size of the buffer for a given topology Individual topologies can override the default values of the cluster and set their own size for any of the disruptor queues. This is done via the Config class that gets passed into the StormSubmitter when you submit a topology. We place this code in a RemoteTopologyRunner class, which can be seen in the following listing. Listing 1: RemoteTopologyRunner.java with configuration for increased buffer sizes public class RemoteTopologyRunner { public static void main(String[] args) { Config config = new Config(); ... config.put(Config.TOPOLOGY_EXECUTOR_RECEIVE_BUFFER_SIZE, new Integer(16384)); config.put(Config.TOPOLOGY_EXECUTOR_SEND_BUFFER_SIZE, new Integer(16384)); config.put(Config.TOPOLOGY_TRANSFER_BUFFER_SIZE, new Integer(32)); StormSubmitter.submitTopology("topology-name", config, topology); } } This brings us to our final option (one that should also be familiar): setting max spout pending. Max spout pending As you may know, max spout pending caps the number of tuples that any given spout will allow to be live in the topology at one time. How can this help prevent buffer overflows? Let's try some math: - A single spout has a max spout pending of 512. - The smallest disruptor has a buffer size of 1024. 512 < 1024 Assuming all your bolts don't create more tuples than they ingest, it's impossible to have enough tuples in play within the topology to overflow any given buffer. The math for this can get complicated if you have bolts that ingest a single tuple but emit a variable number of tuples. Here's a more complicated example: - A single spout has a max spout pending of 512. - The smallest disruptor has a buffer size of 1024. One of our bolts takes in a single tuple and emits 1 to 4 tuples. That means the 512 tuples that our spout will emit at a given point in time could result in anywhere from 512 to 2048 tuples in play within our topology. Or put another way, we could have a buffer overflow issue. Buffer overflows aside, setting a spout's max spout pending value is a good idea and should always be done. We've addressed four solutions for handling buffers overflowing. In my book, Storm Applied, I also discuss tweaking the sizes of these buffers in order to get the best performance possible in your Storm topologies.
http://mobile.developer.com/open/addressing-internal-apache-storm-buffers-overflowing.html
CC-MAIN-2017-30
refinedweb
1,102
51.38
Agenda See also: IRC log Date: 6 Aug 2009 <scribe> Meeting: 151 <scribe> Scribe: Norm <scribe> ScribeNick: Norm <ht> oops, how time do fly <ht> running to grab T, brb ok -> Accepted. -> Accepted. Cancelling 13 Aug for Balisage Henry gives regrets for 20 Aug, 27 Aug Basically, what we've got doesn't work. Henry has made an alternate proposal. -> Vojtech: I think there's still an issue with nested pipelines. Henry: I think there is a problem...but not with nested pipelines. ... I don't think nested pipelines are a problem because the algorithm stops when it hits a p:pipeline child. ... Consider a pipeline that has an import and a nested pipeline (as a sibling of import) ... And that nested pipeline defines symbols (nested pipelines or an import of its own). <ht> [pipe <import a> [pipe <import b>][pipe <import c>]] Scribe struggles Henry: The problem is that the algorithm as I specified it doesn't check the nested pipelines. ... I think I know how to fix that without changing the algorithm, but we need a different set of initial conditions. ... To check a pipeline, you need to know the exports of its parent and the URIs that were involved in checking that and you start with those. ... I'll send another message in a little while with an update. Vojtech: I'm happier with the new proposal, including Henry's addendum. I think it's easier to understand. Norm: Yes, I think so to. ... Ok, we'll continue the review in email and touch base again at the next telcon. Vojtech: For options and variables, the spec says they can't be in the XProc namespace. It says the same thing about paramters. ... But I don't think it can be a *static* error for parameters. Norm: Right. It's clearly not a static error. Vojtech: Is it really necessary to say this about parameters? Norm: We own it, that's why we say it, but I don't feel strongly about it. ... Would anyone ever need to write a stylesheet that used parameters in the XProc namespace? ... I can't think of a reason. I'm inclined to leave the prohibition but make the parameter case dynamic. Vojtech: But leave options and variables static? Norm: Yes. Propsal: Keep the prohibition, create a new dynamic error for the parameters case. Accepted. Norm: I think this is editorial. Alex: I can dig up a normative reference and send it to you. Norm: Thanks! <scribe> ACTION: Alex to find a normative reference for UUID algorithms. [recorded in] Norm: Yes, it seems odd to have all three. We could lose 2 or 11 and 29 I think. ... I guess losing 2 is the way to go, it's in a part of the spec distant from the other constraints on p:document and p:data. Vojtech: I would remove 2. Proposal: Remove err:XD0002 in favor of the two more specific errors, 11 and 29. Accepted. <alexmilowski> Odd: Here's the official spec for UUIDs: Vojtech explains why they should both be dynamic errors. Norm: I think you're right. Proposal: Rename err:XC0001 to some appropriate dynamic error number Norm: Actually, I think err:XC0001 is simply subsumed by err:XD0020. There's no need to call out method if we aren't going to call out all of them. Vojtech: Do we need two: one for invalid values and one for unsupported values? Norm: I don't know, I'm not sure users will get value out of that distinction. Vojtech: When I was writing the serialization tests, I had problems telling them apart. Norm: Sold! Proposal: Remove err:XC0001 using err:XD0020 there instead. Accepted. Alex: In both cases, it's about making sure the values are consistent. Norm: Does anyone diagree that those are two cases of the same error, that is that one error code is sufficient. Vojtech: The first definition talks specifically about the header value. Alex: The spirit of this error is that to make a request, you have to get all the packaging right: headers, options, etc. have to match. ... The first mention talks about headers, but the boundry and a few other things also come into play. Norm: I'm happy to reword err:XC0020 so that it's clear that what we're testing is general consistency in a request. Proposal: Generalize err:XC0020 so that it's more appropriate for both cases. Accepted. <scribe> ACTION: Norm to generalize err:XC0020 appropriately. [recorded in] Vojtech: The replace step talks about the "elements" that it matches, but later on it talks about comments, PIs, text, etc. ... I think it should talk about nodes instead of elements. Norm: Sounds right to me. Proposal: Replace elements with nodes where appropropriate to make the description accurately reflect what the step does. Accepted. Norm: We're getting very close to being done. Maybe September? I'll have a more coherent report of coverage by the next meeting. No other business heard. Alex: Who's going to Balisage? Norm: I think it's you and I and Mohamed. Adjourned. This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/Keept he/Keep the/ Found Scribe: Norm Inferring ScribeNick: Norm Found ScribeNick: Norm Default Present: Norm, Vojtech, PGrosso, Alex_Milows, Ht Present: Norm Paul Vojtech Henry Alex Agenda: Found Date: 06 Aug 2009 Guessing minutes URL: People with action items: alex norm[End of scribe.perl diagnostic output]
http://www.w3.org/2009/08/06-xproc-minutes.html
CC-MAIN-2016-50
refinedweb
929
66.74
. Extends "DESCRIPTION" in OODoc::Object. Extends "OVERLOADED" in OODoc::Object. Extends "METHODS" in OODoc::Object. Extends "Constructors" in OODoc::Object. -Option --Default skip_links undef The parser should not attempt to load modules which match the REGEXP or are equal or sub-namespace of STRING. More than one of these can be passed in an ARRAY. Extends "Inheritance knowledge" in OODoc::Object. Inherited,). Extends "Commonly used functions" in OODoc::Object. Inherited, see "Commonly used functions" in OODoc::Object Inherited, see "Commonly used functions" in OODoc::Object Extends Text blocks have to get the finishing touch in the final formatting phase. The parser has to fix the text block segments to create a formatter dependent output. Only a few formatters are predefined. A call to addManual() expects a new manual object (a OODoc::Manual), however an incompatible thing was passed. Usually, intended was a call to manualsForPackage() or mainManual(). This module is part of OODoc distribution version 2.01, built on November 11, 2015. Website: This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See
http://search.cpan.org/~markov/OODoc-2.01/lib/OODoc/Parser.pod
CC-MAIN-2017-17
refinedweb
184
52.05
I think \n moves the needle down, and \r moves the needle to the beginning of a line (left align)? I'm not sure, though. So, if I'm wrong please correct me.... \n \r Anyway, I was told that Windows and Linux handle newlines and carriage returns differently. I would like to know how they handle them differently and some places where it's important to remember. Thanks for answering. newlines carriage returns \r\n \n\r CR LF I think \n moves the needle down, and \r moves the needle to the beginning of a line (left align)? I'm not sure, though I think \n moves the needle down, and \r moves the needle to the beginning of a line (left align)? I'm not sure, though This is true, more or less, but mostly a historical curiosity. Originally, linefeed (LF) was used to advance the paper by one line on printers and hardcopy terminals (teleprinters); carriage return (CR) returned the print head to the start of the line. This probably still works on modern printers when used in "text mode", but is otherwise of little relevance today. Anyway, I was told that Windows and Linux handle newlines and carriage returns differently. Anyway, I was told that Windows and Linux handle newlines and carriage returns differently. The difference is simply: OS designers had to choose how to represent the start of a new line in text in computer files. For various historical reasons, in the Unix/Linux world a single LF character was chosen as the newline marker; MS-DOS chose CR+LF, and Windows inherited this. Thus different platforms use different conventions. In practice, this is becoming less and less of a problem. The newline marker is really only relevant for pograms that process "plain text", and there are not that many - it mostly only affects program source code, configuration files, and some simple text files with documentation. Nowadays most programs handling these kinds of files (editors, compilers etc.) can handle both newline conventions, so it does not matter which one you choose. There are some cases where tools insist on "their" newline convention (e.g. Unix shell scripts must not use CR+LF), in which case you must use the right one. preg_match The American Standard Code for Information Interchange (ASCII) defined control-characters including CARRIAGE-RETURN (CR) and LINE-FEED (LF) that were (and still are) used to control the print-position on printers in a way analogous to the mechanical typewriters that preceded early computer printers. In Windows the traditional line-separator in text files is CR followed by LF In old (pre OSX) Apple Macintosh systems the traditional line separator in text files was CR In Unix and Linux, the traditional line-separator in text files is LF. In many programming and scripting languages \n means "new line". Sometimes (but not always) this means the ASCII LINE-FEED character (LF), which, as you say, moves the cursor (or print position) down one line. In a printer or typewriter, this would actually move the paper up one line. Invariably \r means the ASCII CARRIAGE-RETURN character (CR) whose name actually comes from mechanical typewriters where there was a carriage-return key that caused the roller ("carriage") that carried the paper to move to the right, powered by a spring, as far as it would go. Thus setting the current typing position to the left margin. In some programming languages \n can mean a platform-dependent sequence of characters that end or separate lines in a text file. For example in Perl, print "\n" produces a different sequence of characters on Linux than on Windows. print "\n" In Java, best practise, if you want to use the native line endings for the runtime platform, is not to use \n or \r at all. You should use System.getProperty("line.separator"). You should use \n and \r where you want LF and CR regardless of platform (e.g. as used in HTTP, FTP and other Internet communications protocols). System.getProperty("line.separator") In a Unix shell, the stty command can be used to cause the shell to translate between these various conventions. For example stty -onlcr will cause the shell to subsequently translate all outgoing LFs to CR LF. stty stty -onlcr Linux and OSX follow Unix conventions Text files are still enormously important and widely used. For example, HTML and XML are examples of text file. Most of the important Internet protocols, such as HTTP, follow text-file conventions and include specifications for line-endings. Most printers other than the very cheapest, still respect CR and LF. In fact they are fundamental to the most widely used page description languages - PCL and Postscript. line.separator println() In short, was needed for printers, but now the OSes do it slightly differently. In most cases, it is fine to just do both CR and LF by doing \r\n and in most cases, this will work fine. By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 29771 times active
http://superuser.com/questions/374028/how-are-n-and-r-handled-differently-on-linux-and-windows?answertab=votes
CC-MAIN-2016-07
refinedweb
853
61.87
Using Dependent Code: Adding the Twitter Handle Name to Your Referring Traffic A common request I hear from customers is the desire to integrate 3rd party data inside the digital marketing suite. There are a few approaches to do this. SAINT classifications allow you to add metadata to a particular data point. Generally, we see this tool used to give campaigns friendly names or make an unfriendly product SKU readable. Another option to bring in data as a data source. Data sources come in many forms but are most commonly implemented to import aggregated pre-click data (such as email or display advertising data) with the online marketing suite. Both of these methods are batch processes that are implemented either through an API call or and FTP upload. API and FTP are straightforward methods for importing data, however it is at times necessary to include the integrated data in an image request in real-time. By doing this, the integrated data becomes part of the visitor’s profile and can be used to create segments and correlated with other real time metrics. During the Tag Manager lab at Summit, we presented a similar use case to look up a Twitter author’s handle and include this data within the image request in real time. The process flow looks something like this: A similar process flow can be used to integrate any kind of data that may not be necessarily available on the page or in a query string. In my experience, the most common approach is to capture a view through metric on the first page of a visit in a display advertising integration. We can easily implement this using Adobe Tag Manager and a dependent code block as I will illustrate below. First, I’ll assume that you are up and running with Tag Manager. If you are not, Brent’s post is a good place to start. Adding Dependent code is possible in the product section of Tag Manager. For this example, we’ll name the dependent code block “Twitter”. The default code that is populated when you add the dependent code isn’t germane to this project except the first line. s.Integrate.add("Twitter") What this line does is create a specific “Twitter” namespace within the integrate module. The name “Twitter” is the name I gave the integration when adding the code block. By making this name unique, it allows for multiple integrations with individual namespaces that won’t collide with one another. The most important element of the this block of code is the get request. s.Integrate.Twitter.get("" + g); s.Integrate.Twitter.delay(); The way the Twitter API works is that you make a call out to the service and include a callback function on the page along with the hashed handle name in the referrer. What is returned is then passed to the callback function and includes the Twitter user’s handle. The delay method is called to tell the remote code file to wait on sending the image request until the data is returned from the API or we hit the maxDelay time. This will ensure that the data is received by the online marketing suite even if Twitter never responds to the the api request. In this sample I made the maxDelay 2000 ms. This can be adjusted based on your preference. I normally start with 5000ms and work my way down. We will want to ultimatly delay it long enough for the twitter api to respond but not too long that we lose page data. I’ve included the full code below. It’s important to note that this is not production code. The Twitter API returns the most recent Tweeter. If you open the data structure that is returned you will notice that there is more data returned than just the handle. Within the “text” data point you can discover if this is a re-Tweet. Parsing this you could ultimately populate 2 variables – the Tweeter and the re-Tweeter. s.Integrate.add(“Twitter”); s.maxDelay = “2000”; var g = s.referrer ? s.referrer : document.referrer; if(g.indexOf(‘t.co’) > –1) { s.Integrate.Twitter.get(“” + g); s.Integrate.Twitter.delay(); s.Integrate.Twitter.setVars = function(s,p) { if ℗ { s[tTwitterVar] = this.twitterResponse.from_user; } } s.Integrate.Twitter.tweeter = function(obj) { if(typeof obj==‘undefined’||obj.results.length==0){ return; } this.twitterResponse = obj.results[0]; this.ready(); } } Ultimately, there are many uses for dependent code. This is can ultimately provide the functionality to send a single beacon request based on the a certain event being set or as I demonstrated a request to a web service for additional information. Hopefully, this is functionality that you can build into your next TagManager project. Pingback: Trafic code | Letsbuymiami
http://blogs.adobe.com/digitalmarketing/digital-marketing/social-media/using-dependent-code-adding-the-twitter-handle-name-to-your-referring-traffic/
CC-MAIN-2013-20
refinedweb
796
55.64
On Tue, 2007-03-20 at 10:29 +0800, Zhang, Yanmin wrote:> On Wed, 2007-03-14 at 16:33 -0700, Siddha, Suresh B wrote:> > On Tue, Mar 13, 2007 at 05:08:59AM -0700, Nick Piggin wrote:> > > I would agree that it points to MySQL scalability issues, however the> > > fact that such large gains come from tcmalloc is still interesting.> > > > What glibc version are you, Anton and others are using?> > > > Does that version has this fix included?> > > > Dynamically size mmap treshold if the program frees mmaped blocks.> > > >> The *ROOT CAUSE* is dynamic thresholds don’t apply to non-main arena.> > To verify my idea, I created a small patch. When freeing a block, always> check mp_.trim_threshold even though it might not be in main arena. The> patch is just to verify my idea instead of the final solution.> > --- glibc-2.5-20061008T1257_bak/malloc/malloc.c 2006-09-08 00:06:02.000000000 +0800> +++ glibc-2.5-20061008T1257/malloc/malloc.c 2007-03-20 07:41:03.000000000 +0800> @@ -4607,10 +4607,13 @@ _int_free(mstate av, Void_t* mem)> } else {> /* Always try heap_trim(), even if the top chunk is not> large, because the corresponding heap might go away. */> + if ((unsigned long)(chunksize(av->top)) >=> + (unsigned long)(mp_.trim_threshold)) {> heap_info *heap = heap_for_ptr(top(av));> > assert(heap->ar_ptr == av);> heap_trim(heap, mp_.top_pad);> + }> }> }> > I sent a new patch to glibc maintainer, but didn't get response. So resend it here.Glibc arena is to decrease the malloc/free contention among threads. But arenachooses to shrink agressively, so also grow agressively. When heaps grow, mprotectis called. When heaps shrink, mmap is called. In kernel, both mmap and mprotectneed hold the write lock of mm->mmap_sem which introduce new contention. The newcontention actually causes the arena effort to become 0.Here is a new patch to address this issue.Signed-off-by: Zhang Yanmin <yanmin.zhang@intel.com>------ glibc-2.5-20061008T1257_bak/malloc/malloc.c 2006-09-08 00:06:02.000000000 +0800+++ glibc-2.5-20061008T1257/malloc/malloc.c 2007-03-30 09:01:18.000000000 +0800@@ -4605,12 +4605,13 @@ _int_free(mstate av, Void_t* mem) sYSTRIm(mp_.top_pad, av); #endif } else {- /* Always try heap_trim(), even if the top chunk is not- large, because the corresponding heap might go away. */- heap_info *heap = heap_for_ptr(top(av));-- assert(heap->ar_ptr == av);- heap_trim(heap, mp_.top_pad);+ if ((unsigned long)(chunksize(av->top)) >=+ (unsigned long)(mp_.trim_threshold)) {+ heap_info *heap = heap_for_ptr(top(av));++ assert(heap->ar_ptr == av);+ heap_trim(heap, mp_.top_pad);+ } } } -To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2007/4/1/268
CC-MAIN-2017-34
refinedweb
441
70.19
_lwp_cond_reltimedwait(2) - wait for child process to change state #include <wait.h> int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options); The waitid() function suspends the calling process until one of its child processes changes state. It records the current state of a child in the structure pointed to by infop. It returns immediately if a child process changed state prior to the call. The idtype and id arguments specify which children waitid() is to wait for, as follows:. Wait for traced process(es) to become trapped or reach a breakpoint (see ptrace(3C)). The infop argument must point to a siginfo_t structure, as defined in siginfo.h(3HEAD). If waitid() returns because a child process was found that satisfies the conditions indicated by the arguments idtype and options, then the structure pointed to by infop will be filled by the system with the status of the process. The si_signo member will always be equal to SIGCHLD. One instance of a SIGCHLD signal is queued for each child process whose status has changed. If waitid() returns because the status of a child process is available and WNOWAIT was not specified in options, any pending SIGCHLD signal associated with the process ID of that child process is discarded. Any other pending SIGCHLD signals remain pending.)
http://docs.oracle.com/cd/E18752_01/html/816-5167/waitid-2.html
CC-MAIN-2014-52
refinedweb
215
62.38
QML C++ application runs much slower than pure QML Hi everyone. I'm writing small game in qml. When i run it in qmlviewer everything works fine, application uses 10-15% CPU. When i create QtQuick project and run application with QmlApplicationViewer C++ class it runs much slower, there is about 70-80 % CPU usage. Is it normal? Can i deploy pure QML application? Can I make package or bin file from my app without writing C++ code? Thanks everyone. It's weird. Since everything is works properly for me, can you paste your env? Desktop ? Mobile ? Very strange, because the QML viewer app does not much more than use the same class. Did you try setting a QGLWidget as your viewport widget? You may try to use QML Profiler in Qt Creator. It should give you some clue. Thank's everyone for replies! "Here's the link to my project. Main file is _arca.qml.": - I ran it with qmlviewer ("qmlviewer _arca.qml" in terminal) - I made QtQuick project. My main.cpp: @ #include <QtGui/QApplication> #include "qmlapplicationviewer.h" Q_DECL_EXPORT int main(int argc, char *argv[]) { QScopedPointer<QApplication> app(createApplication(argc, argv)); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); viewer.setMainQmlFile(QLatin1String("_arca.qml")); viewer.showExpanded(); return app->exec(); } @ Now i understood, that it's bad idea to use javascript in C++ application so i'm rewriting all logic in C++. But the problem wasn't solved. And i forgot to say that its desktop configuration. I'll try to use QGLWidget and write about results - outdoor_guy last edited by Have you tried @ QApplication::setGraphicsSystem("raster");@ at the beginning of the main (I would say in Line 7 or so) For me, this makes the application much faster Yes, i already tried it before, but application is still very slow. Can somebody give advice how to make an explosion animation? I tried two variant but both are too slow. - Dynamically create some objects and make them move to different corners of screen - Use Particles qml object (burst method) [quote author="outdoor_guy" date="1331547299"]Have you tried @ QApplication::setGraphicsSystem("raster");@ at the beginning of the main (I would say in Line 7 or so) For me, this makes the application much faster[/quote]
https://forum.qt.io/topic/14434/qml-c-application-runs-much-slower-than-pure-qml
CC-MAIN-2022-40
refinedweb
371
58.38
Always Test Everything – Twitter App Update I image was, I decided this would be an ideal opportunity to check that the script is still current and working as it should. You’ll be glad to hear that the instructions still work fine and the original script still works. But – yes there’s always a but – I have a lot more twitter followers than I did two years ago and I stumbled across an issue that only kicks in once you have >5000 followers. I ran the original script and it told me I had exactly 5000 followers. I knew this to be wrong because yesterday I hit 9000 (you tend to notice the even milestones). Why could this be happening? Is it a limitation of tweepy? Some googling revealed that the twitter API is rate-limited. In terms of querying followers it will only allow you to query 5000 followers once per minute, so you have to split your query into sections <=5000. How To Search More Than 5000 Followers In Tweepy? It’s easy and obvious when you know, but actually finding out how to do this was quite tricky. It took several rounds of looking at the tweepy documention, the twitter API documentation and stack exchange to work out the code that would do the job for me. In truth, I would never have worked it out from the documentation because it is too hard to understand and there are too few useful examples. This code snippet on stack exchange saved the day for me, but it took a long time to find it. Lines 9 onwards are the interesting bits… import time import tweepy auth = tweepy.OAuthHandler(..., ...) auth.set_access_token(..., ...) api = tweepy.API(auth) # this is the part I actually used, changing McDonalds to raspitv... ids = [] for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pages(): ids.extend(page) time.sleep(60) print len(ids) Documentation Without Examples Is Almost Useless (to me) This code allows you to Cursor() through multiple pages() of results. I’d seen reference to Cursor() and pages() in both tweepy and Twitter API documention, but it was incomprehensible to me. All I needed was 4 lines of code in an example. A well explained example is worth far more than generalised documentation. So how does it work? It loops through the pages() of follower_ids, waiting 60 seconds in between each page. Each page is added to the ids list. Once finished, it tells you how many entries there are in the ids list. 1 Minute Delay Per 5000 Followers This was exactly what I needed! So I tweaked my script to incorporate this code, and it now works as it should. If used on an account with a very large number of followers it will take a long time to run, as it waits 65 seconds between each page of 5000 followers. To run this script for the official @Raspberry_Pi twitter account (with 257k followers) would take >55 minutes (and it might well break something else – WJDK). Here’s The Code This script now works and is fit for purpose… #!/usr/bin/env python2.7 # twitdraw.py based on twitterwin.py by Alex Eames import tweepy import random from time import sleep # Consumer keys and access tokens, used for OAuth consumer_key = 'insert_your_consumer_key' consumer_secret = 'insert_your_consumer_secret' access_token = 'insert_your_access_token' access_token_secret = 'insert_your_access_token_secret' # OAuth process, using the keys and tokens auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # Creation of the actual interface, using authentication api = tweepy.API(auth) user = api.get_user('raspitv') print user.screen_name print user.followers_count ids = [] for page in tweepy.Cursor(api.followers_ids, screen_name="raspitv").pages(): ids.extend(page) if len(page) == 5000: print "waiting 65 seconds before requesting next page of results..." sleep(65) print "you have %d followers" % len(ids) show_list = raw_input("Do you want to list the followers array?") if show_list in ('y', 'yes', 'Y', 'Yes', 'YES'): print ids def pick_winner(): random_number = random.randint(0, len(ids)-1) winner = api.get_user(ids[random_number]) print winner.screen_name, random_number while True: pick = raw_input("Press Enter to pick a winner, Q to quit.") if pick in ('q', 'Q', 'quit', 'QUIT', 'Quit'): break pick_winner() (Edit to add: Thanks to Andrew Scheller for comment 1 below. Most of those tips have been incorporated to improve the code.) Odd SSL Error The only other thing that isn’t quite as it ought to be is that there is an odd SSL error message appearing in the output for each tweepy query. There doesn’t appear to be much I can do about this – apart from switching to twython – which I probably will do at some point anyway. But for now, it works, so I don’t much care about that. And Tomorrow We Use It For Real! Tomorrow I will use this script to pick a winner at random from my twitter followers. The winner will receive a Joey board from Gooligum Electronics I new found a moment to spark up the Joey from @gooligumelec Instructions worked fine. Nice little board :) pic.twitter.com/JcJQWGWfKr — RasPi.TV (@RasPiTV) January 6, 2016 If you fancy having a go at this yourself, start with the original page here which has all the installation instructions on. I don’t use Twitter myself, but here’s a few little Python tips… ;-) raw_input always returns a string, so no need to explicitly do str(raw_input()) if show_list == (‘y’ or ‘yes’ or ‘Y’ or ‘Yes’ or ‘YES’): doesn’t actually do what you think it does! (‘y’ or ‘yes’ or ‘Y’ or ‘Yes’ or ‘YES’) will always return ‘y’ (as it’s the first non-False value), so your if-statement is actually just doing if show_list == ‘y’: You can verify this by typing ‘yes’ == (‘y’ or ‘yes’ or ‘Y’ or ‘Yes’ or ‘YES’) into an interactive python prompt (and the same obviously applies to the ‘pick’ line too). To get it to do what you *expect* it to do, you could rewrite it as if show_list in (‘y’, ‘yes’, ‘Y’, ‘Yes’, ‘YES’): or just simplify it to if show_list[0].lower() == ‘y’: For choosing a single random item out of an array, it’s probably easier to use i.e. you could do random_id = random.choice(ids) winner = api.get_user(random_id) print “Happy New Year %d!” % (2**5*3**2*7) Thanks Andrew. I’ll do some tweaks. Some basic stuff there that has gone unnoticed for >2 years as it’s mostly copied from the original script. :) Great :) It currently works as-is, but I think line 34 would look better with a space after the ‘in’. Bugs that are copy’n’pasted from existing code are always very easy to overlook, and tend to be the kind of things that only a fresh pair of eyes can spot ;-) **Swears** **adds space** Thanks Andrew. I agree with you. It was unintentional. I’ve gone back and “reto-fitted” the amendments to the original script as well :) Alex, your SSL errors are pretty easy to fix. I followed your guide to install tweepy, then wrote a follow-up post on a blog detailing how to correct the errors. That post is here: Nice one. Thanks Bryan :) Thanks for the great tutorial Alex. Agreed the Tweepy docs are very slim. I would just add the “name” when you print out the winner. Its easier to find on your feed than the “screen_name”. i.e. print winner.screen_name, random_number, ” – Name: “, winner.name
https://raspi.tv/2016/always-test-everything-twitter-app-update?replytocom=60401
CC-MAIN-2019-35
refinedweb
1,239
73.07
Features/GPUPassthrough - Revision history 2014-04-16T19:31:45Z Revision history for this page on the wiki MediaWiki 1.19.13 Ajax: Created page with "<!-- All fields on this form are required to be accepted by FESCo. We also request that you maintain the same order of sections so that all of the feature pages are uniform. --..." 2011-09-30T19:28:15Z <p>Created page with "<!-- All fields on this form are required to be accepted by FESCo. We also request that you maintain the same order of sections so that all of the feature pages are uniform. --..."</p> <p><b>New page</b></p><div><!-- All fields on this form are required to be accepted by FESCo.<br /> We also request that you maintain the same order of sections so that all of the feature pages are uniform. --><br /> <br /> <!-- The actual name of your feature page should look something like: Features/YourFeatureName. This keeps all features in the same namespace --><br /> <br /> = GPU Passthrough in KVM =<br /> <br /> == Summary ==<br /> <br /> Adds the ability to pass a whole PCI GPU device to a KVM guest, and to use it from Linux guests (and possibly others).<br /> <br /> == Owner ==<br /> <br /> * Name: [[User:Ajax|Adam Jackson]]<br /> * Email: ajax@redhat.com<br /> <br /> == Current status ==<br /> <br /> * Targeted release: [[Releases/17 | Fedora 17 ]] <br /> * Last updated: 30 September 2011<br /> * Percentage of completion: 0%<br /> <br /> == Detailed Description ==<br /> <br /> Like other forms of PCI passthrough, this exposes a PCI or PCIE device directly to a virtualized guest OS. GPUs have some additional restrictions for IBM VGA compatibility, so this feature will describe those limitations and attempt to solve as many as are practicable.<br /> <br /> == Benefit to Fedora ==<br /> <br /> KVM guests under Fedora can now host complete desktop environments, allowing testing of graphical applications on a variety of operating systems. Guests may also be able to use the GPU for strictly computational tasks while remaining tightly isolated from the host.<br /> <br /> == Scope ==<br /> <br /> Changes will likely be required in qemu/kvm. The host OS will want some form of user interface for detaching from a GPU before assigning it to a guest. The guest may require modification to break assumptions about legacy VGA services. If running an unmodified guest is desired, additional work to kvm and the host kernel may be required.<br /> <br /> == How To Test ==<br /> <br /> On a machine with VT-d or equivalent IOMMU functionality, run through the following setup instructions (TBD) to bring up a guest OS with GPU passthrough.<br /> <br /> == User Experience ==<br /> <br /> TBD.<br /> <br /> == Dependencies ==<br /> <br /> Requires integration with at least KVM and possibly more.<br /> <br /> Requires sufficiently capable host hardware for IOMMU isolation.<br /> <br /> VGA routing passthrough will require work beyond pure PCI, and may have restrictions based on host bus topology.<br /> <br /> Passing through the boot VGA device requires the above VGA routing passthrough work and may also require kernel changes to allow detaching the boot console.<br /> <br /> == Contingency Plan ==<br /> <br /> None needed, purely an additional feature.<br /> <br /> == Documentation ==<br /> <br /> TBD.<br /> <br /> == Release Notes ==<br /> <!-- The Fedora Release Notes inform end-users about what is new in the release. Examples of past release notes are here: -->. --><br /> * None yet.<br /> <br /> == Comments and Discussion ==<br /> * See [[Talk:Features/GPUPassthrough]]> Ajax
https://fedoraproject.org/w/index.php?title=Features/GPUPassthrough&feed=atom&action=history
CC-MAIN-2014-15
refinedweb
566
55.95
Due by 11:59pm on Friday, 5/2 Homework 10 is in two parts, of which this is the first. The solutions to this part are in Python. Those for 10b are in logic notation. Submission. See the online submission instructions. Submit the files for hw10a and hw10b together as hw10. We have provided a hw10a starter file for the questions below. Readings. Sections `4.2 4.3, and 4.4 of Composing Programs. Q1. (Objects and recursion review): - The left and right attributes of a Mobile should both be Branch instances. Check that the types of constructor arguments for Mobile are Branch instances, and raise an appropriate TypeError for incorrect argument types. See the doctest for Mobile for exception details. - The length of a Branch and the weight of a Weight should be positive numbers. Implement check_positive to check if an object x is a positive number. - Add a property weight that gives the total weight of the mobile. -. Implement the method is_balanced that returns True if and only if the Mobile Q2. (Python evaluation and recursion review) Q3.. The zip function in the doctest for __iter__ combines the corresponding elements of two iterables into pairs until one iterator raises StopIteration: class Stream: """A lazily computed recursive. >>> list(zip(range(6), ints)) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] """ "*** YOUR CODE HERE ***" def __getitem__(self, k): """Return the k-th element of the stream. >>> ints[5] 6 >>> increment_stream(ints)[7] 9 """ "*** YOUR CODE HERE ***" def increment_stream(s): """Increment all elements of a stream.""" return Stream(s.first+1, lambda: increment_stream(s.rest)) # The stream of consecutive integers starting at 1. ints = Stream(1, lambda: increment_stream(ints)) Q ***" Q5. definition of merge, then fill in the definition of make_s below: def merge(s0, s1): """Return a stream over the elements of increasing s0 and s1, removing
https://inst.eecs.berkeley.edu/~cs61a/sp14/hw/hw10a.html
CC-MAIN-2020-10
refinedweb
311
67.15
MOUNT(2) BSD Programmer's Manual MOUNT(2) mount, unmount - mount or dismount a filesystem #include <sys/param.h> #include <sys/mount.h> int mount(const char *type, const char *dir, int flags, void *data); int unmount(const char *dir, int flags);user_SYNCHRONOUS All I/O to the filesystem should be done synchronously. MNT_ASYNC All I/O to the filesystem should be done asynchronously. MNT_SOFTDEP Use soft dependencies. Applies to FFS filesystems only (see 'softdep' in mount(8)).. . statfs(2), mfs(8), mount(8), umount(8) mount() and unmount() function calls appeared in Version 6 AT&T UNIX. Some of the error codes need translation to more obvious messages. MirOS BSD #10-current December 11, 1993.
http://www.mirbsd.org/htman/sparc/man2/unmount.htm
CC-MAIN-2017-09
refinedweb
116
60.51
Early in 2012, a developer, named Egor Homakov, took advantage of a security hole at Github (a Rails app) to gain commit access to the Rails project. His intent was mostly to point out a common security issue with many Rails apps that results from a feature, known as mass assignment (and did so rather loudly). In this article, we'll review what mass assignment is, how it can be a problem, and what you can do about it in your own applications. What is Mass Assignment? To begin, let's first take a look at what mass assignment means, and why it exists. By way of an example, imagine that we have the following User class in our application: # Assume the following fields: [:id, :first, :last, :email] class User < ActiveRecord::Base end Mass assignment allows us to set a bunch of attributes at once: attrs = {:first => "John", :last => "Doe", :email => "john.doe@example.com"} user = User.new(attrs) user.first #=> "John" user.last #=> "Doe" user.email #=> "john.doe@example.com" Without the convenience of mass assignment, we'd have to write an assignment statement for each attribute to achieve the same result. Here's an example: attrs = {:first => "John", :last => "Doe", :email => "john.doe@example.com"} user = User.new user.first = attrs[:first] user.last = attrs[:last] user.email = attrs[:email] user.first #=> "John" user.last #=> "Doe" user.email #=> "john.doe@example.com" Obviously, this can get tedious and painful; so we bow at the feet of laziness and say, yes yes, mass assignment is a good thing. The (Potential) Problem With Mass Assignment One problem with sharp tools is that you can cut yourself with them. But wait! One problem with sharp tools is that you can cut yourself with them. Mass assignment is no exception to this rule. Suppose now that our little imaginary application has acquired the ability to fire missiles. As we don't want the world to turn to ash, we add a boolean permission field to the User model to decide who can fire missiles. class AddCanFireMissilesFlagToUsers < ActiveRecord::Migration def change add_column :users, :can_fire_missiles, :boolean, :default => false end end Let's also assume that we have a way for users to edit their contact information: this might be a form somewhere that is accessible to the user with text fields for the user's first name, last name, and email address. Our friend John Doe decides to change his name and update his email account. When he submits the form, the browser will issue a request similar to the following: PUT[first]=NewJohn&user[email]=john.doe@newemail.com The update action within the UsersController might look something like: def update user = User.find(params[:id]) if user.update_attributes(params[:user]) # Mass assignment! redirect_to home_path else render :edit end end Given our example request, the params hash will look similar to: {:id => 42, :user => {:first => "NewJohn", :email => "john.doe@newemail.com"} # :id - parsed by the router # :user - parsed from the incoming querystring Now let's say that NewJohn gets a little sneaky. You don't necessarily need a browser to issue an HTTP request, so he writes a script that issues the following request: PUT[can_fire_missiles]=true Fields, like :admin, :owner, and :public_key, are quite easily guessable. When this request hits our update action, the update_attributes call will see {:can_fire_missiles => true}, and give NewJohn the ability to fire missiles! Woe has become us. This is exactly how Egor Homakov gave himself commit access to the Rails project. Because Rails is so convention-heavy, fields like :admin, :owner, and :public_key are quite easily guessable. Further, if there aren't protections in place, you can gain access to things that you're not supposed to be able to touch. How to Deal With Mass Assignment So how do we protect ourselves from wanton mass assignment? How do we prevent the NewJohns of the world from firing our missiles with reckless abandon? Luckily, Rails provides a couple tools to manage the issue: attr_protected and attr_accessible. attr_protected: The BlackList Using attr_protected, you can specify which fields may never be mass-ly assignable: class User < ActiveRecord::Base attr_protected :can_fire_missiles end Now, any attempt to mass-assign the can_fire_missiles attribute will fail. attr_accessible: The WhiteList The problem with attr_protected is that it's too easy to forget to add a newly implemented field to the list. This is where attr_accessible comes in. As you might have guessed, it's the opposite of attr_protected: only list the attributes that you want to be mass-assignable. As such, we can switch our User class to this approach: class User < ActiveRecord::Base attr_accessible :first, :last, :email end Here, we're explicitly listing out what can be mass-assigned. Everything else will be disallowed. The advantage here is that if we, say, add an admin flag to the User model, it will automatically be safe from mass-assignment. As a general rule, you should prefer attr_accessible to attr_protected, as it helps you err on the side of caution. Mass Assignment Roles Rails 3.1 introduced the concept of mass-assignment "roles". The idea is that you can specify different attr_protected and attr_accessible lists for different situations. class User < ActiveRecord::Base attr_accessible :first, :last, :email # :default role attr_accessible :can_fire_missiles, :as => :admin # :admin role end user = User.new({:can_fire_missiles => true}) # uses the :default role user.can_fire_missiles #=> false user2 = User.new({:can_fire_missiles => true}, :as => :admin) user.can_fire_missiles #=> true Application-wide Configuration You can control mass assignment behavior in your application by editing the config.active_record.whitelist_attributes setting within the config/application.rb file. If set to false, mass assignment protection will only be activated for the models where you specify an attr_protected or attr_accessible list. If set to true, mass assignment will be impossible for all models unless they specify an attr_protected or attr_accessible list. Please note that this option is enabled by default from Rails 3.2.3 forward. Strictness Beginning with Rails 3.2, there is additionally a configuration option to control the strictness of mass assignment protection: config.active_record.mass_assignment_sanitizer. If set to :strict, it will raise an ActiveModel::MassAssignmentSecurity::Error any time that your application attempts to mass-assign something it shouldn't. You'll need to handle these errors explicitly. As of v3.2, this option is set for you in the development and test environments (but not production), presumably to help you track down where mass-assignment issues might be. If not set, it will handle mass-assignment protection silently - meaning that it will only set the attributes it's supposed to, but won't raise an error. Rails 4 Strong Parameters: A Different Approach Mass assignment security is really about handling untrusted input. The Homakov Incident initiated a conversation around mass assignment protection in the Rails community (and onward to other languages, as well); an interesting question was raised: does mass assignment security belong in the model layer? Some applications have complex authorization requirements. Trying to handle all special cases in the model layer can begin to feel clunky and over-complicated, especially if you find yourself plastering roles all over the place. A key insight here is that mass assignment security is really about handling untrusted input. As a Rails application receives user input in the controller layer, developers began wondering whether it might be better to deal with the issue there instead of ActiveRecord models. The result of this discussion is the Strong Parameters gem, available for use with Rails 3, and a default in the upcoming Rails 4 release. Assuming that our missile application is bult on Rails 3, here's how we might update it for use with the stong parameters gem: Add the gem Add the following line to the Gemfile: gem strong_parameters Turn off model-based mass assignment protection Within config/application.rb: config.active_record.whitelist_attributes = false Tell the models about it class User < ActiveRecord::Base include ActiveModel::ForbiddenAttributesProtection end Update the controllers class UsersController < ApplicationController def update user = User.find(params[:id]) if user.update_attributes(user_params) # see below redirect_to home_path else render :edit end end private # Require that :user be a key in the params Hash, # and only accept :first, :last, and :email attributes def user_params params.require(:user).permit(:first, :last, :email) end end Now, if you attempt something like user.update_attributes(params), you'll get an error in your application. You must first call permit on the params hash with the keys that are allowed for a specific action. The advantage to this approach is that you must be explicit about which input you accept at the point that you're dealing with the input. Note: If this was a Rails 4 app, the controller code is all we'd need; the strong parameters functionality will be baked in by default. As a result, you won't need the include in the model or the separate gem in the Gemfile. Wrapping Up Mass assignment can be an incredibly useful feature when writing Rails code. In fact, it's nearly impossible to write reasonable Rails code without it. Unfortunately, mindless mass assignment is also fraught with peril. Hopefully, you're now equipped with the necessary tools to navigate safely in the mass assignment waters. Here's to fewer missiles! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/mass-assignment-rails-and-you--net-31695
CC-MAIN-2018-17
refinedweb
1,558
55.54
Mastering the Visual Basic Language: Procedures, Error Handling, Classes, and Objects - Sub Procedures - Creating Functions - Using Optional Arguments - Passing a Variable Number of Arguments - Preserving Data Between Procedure Calls - Understanding Scope - Handling Runtime Errors - Unstructured Exception Handling - Structured Exception Handling - Introducing Classes and Objects - Summary - Q&A - Workshop Today, we're going to look at some crucial aspects of the Visual Basic language: procedures such as Sub procedures and functions, procedure scope, and exception (runtime error) handling. We'll also get an introduction to a topic that's become central to Visual Basic: classes and objects. Now that our code is growing larger, it's good to know about procedures, which allow us to break up our code into manageable chunks. In fact, in Visual Basic, all executable code must be in procedures. There are two types of procedures: Sub procedures and functions. In Visual Basic, Sub procedures do not return values when they terminate, but functions do. If you declare variables in your new procedures, those variables might not be accessible from outside the procedure, and that fact is new also. The area of your program in which a data item is visible and can be accessed in code is called scope, and we'll try to understand scopea crucial aspect of object-oriented programmingin this chapter. We'll also look at handling runtime errors today. In Visual Basic, a runtime error is the same as an exception (that's not true in all languages), so we're going to look at exception handling. We'll see that there are two ways of heading off errors that happen at runtime before they become problems. Finally, we'll get an introduction to classes and objects in this chapter. Visual Basic .NET programming is object-oriented programming (OOP), a fact you need to understand in depth to be a Visual Basic programmer. Today, we'll start by discussing classes and objects in preparation for our later work (such as Day 9, "Object-Oriented Programming," which is all about OOP). Here's an overview of today's topics: Creating Sub procedures and functions Passing arguments to procedures Returning data from functions Preserving data values between procedure calls Understanding scope Using unstructured exception handling Using structured exception handling with Try/Catch Using exception filtering in Catch blocks Using multiple Catch statements Throwing an exception Throwing a custom exception Understanding classes and objects Supporting properties and methods in objects All these topics are powerful ones, and they're all related. And today, the best place to start is with Sub procedures. Sub Procedures Procedures give you a way to break up your Visual Basic code, which is invaluable as that code grows longer and longer. Ideally, each procedure should handle one discrete task. That way, you break up your code by task; having one task per procedure makes it easier to keep in mind what each procedure does. You can place a set of Visual Basic statements in a procedure, and when that procedure is called, those statements will be run. You can pass data to procedures for that code to work on and read that data in your code. The two types of procedures in Visual Basic are Sub procedures and functions, and both can read the data you pass them (the name Sub procedure comes from the programming term subroutine). However, only one type, functions, can also return data. In fact, we've been creating Sub procedures in our code already (not surprisingly, because all Visual Basic code has to be in a procedure). All the code we developed yesterday went into the Sub procedure named Main, created with the keyword Sub: Module Module1 Sub Main() Console.WriteLine("Hello there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub End Module This Main Sub procedure is special because when a console application starts, Visual Basic calls Main automatically to start the program. When Main is called, the code is run as we wanted. You can also create your own Sub procedures, giving them your own names. Those names should give an indication of the procedure's task. For example, to show the "Hi there!" message, you might create a new Sub procedure named ShowMessage by simply typing this text into the code designer: Module Module1 Sub Main() End Sub Sub ShowMessage() End Sub End Module In the ShowMessage Sub procedure, you place the code you want to execute, like this code to display the message: Module Module1 Sub Main() End Sub Sub ShowMessage() Console.WriteLine("Hi there!") End Sub End Module How do you make the code in the ShowMessage Sub procedure run? You can do that by calling it; to do so, just insert its name, followed by parentheses, into your code: Module Module1 Sub Main() ShowMessage() Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage() Console.WriteLine("Hi there!") End Sub End Module And that's it! Now when you run this code, Visual Basic will call the Main Sub procedure, which in turn will call the ShowMessage Sub procedure, giving you the same result as before: Hi there! Press Enter to continue... TIP If you want to, you can use a Visual Basic Call statement to call a Sub procedure like this: Call ShowMessage(). This usage is still supported, although it goes back to the earliest days of Visual Basic, and there's no real reason to use it here. Note the parentheses at the end of the call to ShowMessage like this: ShowMessage(). You use those parentheses to pass data to a procedure, and we'll take a look at that task next. Passing Data to Procedures Say you want to pass the message text you want to display to the ShowMessage Sub procedure, allowing you to display whatever message you want. You can do that by passing a text string to ShowMessage, like this: Module Module1 Sub Main() ShowMessage("Hi there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage() End Sub End Module A data item you pass to a procedure in parentheses this way is called an argument. Now in ShowMessage, you must declare the type of the argument passed to this procedure in the procedure's argument list: Module Module1 Sub Main() ShowMessage("Hi there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal Text As String) End Sub End Module This creates a new string variable, Text, which you'll be able to access in the procedure's code. The ByVal keyword here indicates that the data is being passed by value, which is the default in Visual Basic (you don't even have to type ByVal, just Text As String here, and Visual Basic will add ByVal automatically). Passing data by value means a copy of the data will be passed to the procedure. The other way of passing data is by reference, where you use the ByRef keyword. Passing by reference (which was the default in VB6) meant that the location of the data in memory will be passed to the procedure. Here's an important point to know: Because objects can become very large in Visual Basic, making a copy of an object and passing that copy can be very wasteful of memory, so objects are automatically passed by reference. We'll discuss passing by value and passing by reference in more detail in a page or two. Visual Basic automatically fills the Text variable you declared in the argument list in this example with the string data passed to the procedure. This means you can access that data as you would the data in any other variable, as you see in the SubProcedures project in the code for this book, as shown in Listing 3.1. Listing 3.1 Passing Data to a Sub Procedure (SubProcedures project, Module1.vb) Module Module1 Sub Main() ShowMessage("Hi there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal Text As String) Console.WriteLine(Text) End Sub End Module And that's all you need! Now you're passing data to Sub procedures and retrieving that data in the procedure's code. You can pass more than one argument to procedures as long as you declare each argument in the procedure's argument list. For example, say you want to pass the string to show and the number of times to show it to ShowMessage; that code might look like this: Module Module1 Sub Main() ShowMessage("Hi there!", 3) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal Text As String, ByVal Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex End Sub End Module Here's the result of this code: Hi there! Hi there! Hi there! Press Enter to continue... If you pass arguments by reference, using the ByRef keyword, Visual Basic passes the memory location of the passed data to the procedure (which gives the code in that procedure access to that data). You can read that data just as you do when you pass arguments by value: Sub ShowMessage(ByRef Text As String, ByRef Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex End Sub The code in the procedure has access to the data's location in memory, however, and that's something to keep in mind. So far, we've passed two literals ("Hello there!" and 3) to ShowMessage, and literals don't correspond to memory locations. But see what happens if you pass a variable by reference, like this: Dim NumberOfTimes As Integer = 3 ShowMessage("Hi there!", NumberOfTimes) . . . Sub ShowMessage(ByRef Text As String, ByRef Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex End Sub The code in the procedure has access to that variable, and if you change the value of the passed argument, you'll also change the value in the original variable: Dim NumberOfTimes As Integer = 3 ShowMessage("Hi there!", NumberOfTimes) . . . Sub ShowMessage(ByRef Text As String, ByRef Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex Times = 24 End Sub After this code is finished executing, for example, the variable NumberOfTimes will be left holding 24. This side effect is not unintentional; it's intentional. Being able to change the value of arguments is a primary reason to pass arguments by reference. Changing the value of arguments passed by reference is one way to pass data from a procedure back to the calling code, but it can be troublesome. You can easily change an argument's value unintentionally, for example. A more structured way of passing data back from procedures is to use functions, which is the next topic. You should also know that an Exit Sub statement, if you use one, causes an immediate exit from a Sub procedure in case you want to leave before executing all code. For example, say you have a Sub procedure that displays reciprocals of numbers you pass to it, but you want to avoid trying to find the reciprocal of 0. You could display an error message and exit the procedure like this if 0 is passed to the procedure: Sub Reciprocal(ByVal dblNumber As Double) If dblNumber = 0 Then Console.WriteLine("Cannot find the reciprocal of 0.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() Exit Sub End If Console.WriteLine("The reciprocal is " & 1 / dblNumber) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub Procedure Syntax Like other Visual Basic statements, Sub procedures require a formal declaration. You declare Sub procedures with the Sub statement: [ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride | Shadows | Shared }] [{ Public | Protected | Friend | Protected Friend | Private }] Sub name [(arglist)] [ Implements interface.definedname ] [ statements ] [ Exit Sub ] [ statements ] End Sub And like other Visual Basic statements, many of the keywords here won't make sense at this point, so you can treat this information as reference material to come back to later. (Many of the keywords here deal with OOP, but we can't cover OOP in the detail needed here before knowing how to work with procedures, so it's impossible to avoid slightly circular definitions.) The parts of this statement are as follows: attrlistThis is an advanced (and optional) topic; this is a list of attributes for use with this procedure. Attributes can add more information about the procedure, such as copyright data and so on. You separate multiple attributes with commas. OverloadsSpecifies that this Sub procedure overloads one (or more) procedures defined with the same name in a base class. An overloaded procedure has multiple versions, each with a different argument list, as we'll see in Day 9. The argument list must be different from the argument list of every procedure that is to be overloaded. You cannot specify both Overloads and Shadows in the same procedure declaration. OverridesSpecifies that this Sub procedure overrides (replaces) a procedure with the same name in a base class. The number and data types of the arguments must match those of the procedure in the base class. OverridableSpecifies that this Sub procedure can be overridden by a procedure with the same name in a derived class. NotOverridableSpecifies that this Sub procedure may not be overridden in a derived class. MustOverrideSpecifies that this Sub procedure is not implemented. This procedure must be implemented in a derived class. ShadowsMakes this Sub procedure a shadow of an identically named programming element in a base class. You can use Shadows only at module, namespace, or file level (but not inside a procedure). You cannot specify both Overloads and Shadows in the same procedure declaration. SharedSpecifies that this Sub procedure is a shared procedure. As a shared procedure, it is not associated with a specific object, and you can call it using the class or structure name. PublicProcedures declared Public have public access. There are no restrictions on the accessibility of public procedures. ProtectedProcedures declared Protected have protected access. They are accessible only from within their own class or from a derived class. You can specify Protected access only for members of classes. FriendProcedures declared Friend have friend access. They are accessible from within the program that contains their declaration and from anywhere else in the same assembly. Protected FriendProcedures declared Protected Friend have both protected and friend accessibility. They can be used by code in the same assembly, as well as by code in derived classes. PrivateProcedures declared Private have private access. They are accessible only within the element in which they're declared. nameSpecifies the name of the Sub procedure. arglistLists expressions representing arguments that are passed to the Sub procedure when it is called. You separate multiple arguments with commas. Implements interface.definednameIndicates that this Sub procedure implements an interface. We'll see interfaces, which allow you to derive one class from several others, in Day 9. statementsSpecifies the block of statements to be executed within the Sub procedure. In addition, each argument in the argument list, arglist, has this syntax: [ <attrlist> ] [ Optional ] [{ ByVal | ByRef }] [ ParamArray ] argname[( )] [ As argtype ] [ = defaultvalue ] Here are the parts of arglist: attrlistLists (optional) attributes that apply to this argument. Multiple attributes are separated by commas. OptionalSpecifies that this argument is not required when the procedure is called. If you use this keyword, all following arguments in arglist must also be optional and be declared using the Optional keyword. Every optional argument declaration must supply a defaultvalue. Optional cannot be used for any argument if you also use ParamArray. ByValSpecifies passing by value. ByVal is the default in Visual Basic. ByRefSpecifies passing by reference, which means the procedure code can modify the value of the original variable in the calling code. ParamArrayActs as the last argument in arglist to indicate that the final argument is an optional array of elements of the specified type. The ParamArray keyword allows you to pass an arbitrary number of arguments to the procedure. ParamArray arguments are always passed by value. argnameSpecifies the name of the variable representing the argument. argtypeSpecifies the data type of the argument passed to the procedure; this part is optional unless Option Strict is set to On. It can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, or String, or the name of an enumeration, structure, class, or interface. defaultvalueSpecifies the default value for an optional argument, required for all optional arguments. It can be any constant or constant expression that evaluates to the data type of the argument. Note that if the type is Object, or a class, interface, array, or structure, the default value must be Nothing. That gives us what we need to know about Sub procedures, we'll move on to functions next.
http://www.informit.com/articles/article.aspx?p=31488&amp;seqNum=2
CC-MAIN-2017-13
refinedweb
2,798
53.41
This is a known bug in Wine. You can read more here: Something like: foreach(var line in File.ReadLines(filename) .Where(l => l.Contains("ERROR MESSAGE"))) { // Log line } Additionally if you need specific information inside the line you can use a Regex to capture the information. I cannot provide a better example without more information. As KazJaw said above, as an intermediate VBA user you should be able to create the userform and related code that allows your users to select the Word document as you describe. Once you get to working with the Word document things get a bit different from coding for Excel. Let me share the little I know about this: First, make sure you've activated the Word Object Library: on the Tools menu, click References. In the list of available references, find and select the appropriate Microsoft Word Object Library As I understand it, late binding just means declaring the object type when you assign the value. I have no idea if this will solve your 'Error Accessing the System Registry' issue. I have used late binding when I call Word Documents by first defining a variable as a generic object: D There are many fundamental differences between PDF and Word making the approach you want highly undesirable as a general workflow. I'll give just one example: PDF typically does not store information about document structure - sentences, paragraphs, columns, tables... All it stores is the actual text at certain locations at a page. Word of course does have those concepts. Is it possible to do what you want? Yes, to some extent. In the general case with guesswork and approximation. If you know which information you want to convert it might be possible to search for it in the PDF file generated by SSRS and then generate a Word file out of it. However, if SSRS allows export to text, XML, RTF or any other structure based file format (however slightly structure based), you'd have a much easier Try this: protected void InsertTableAtBookMark(string[][] docEnds, string bookmarkName) { Object oBookMarkName = bookmarkName; Range wRng = WordDoc.Bookmarks.get_Item(ref oBookMarkName).Range; Table wTable = WordDoc.Tables.Add(wRng, docEnds.Length, docEnds[0].Length); wTable.set_Style("Table Grid"); for (int i = 0; i < docEnds.Length; i++) { for (int j = 0; j < docEnds[0].Length; j++) { wTable.Cell(i, j).Range.Text = docEnds[i][j]; wTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; wTable.Cell(1, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } } Borders wb = wT You will need to: Distinguish the file type $file_name = $_FILES['image']['name']; $file_extn = end(explode(".", strtolower($_FILES['image']['name']))); if($file_extn == "doc" || $file_extn == "docx"){ docx2text(); }elseif($file_extn == "rtf"){ rtf2text(); } Convert the document to text for doc or docx for rtf Count the words Yes, that's the correct way; the measurement is in half points. In a docx, you'd have something like: <w:rPr> <w:sz w: </w:rPr> ECMA 376 spec on @sz defines the unit as ST_HpsMeasure (Measurement in Half-Points) Its the same with the binary doc format, which HWPF supports. If you look at [MS-DOC], you'll see it also specifies the size of text in half-points. Doh.. changing var componentSchema = new Schema({ name: String , desc: String }, { discriminatorKey : '_type' }) to var componentSchema = new Schema({ name: String , desc: String }, { collection : 'components', discriminatorKey : '_type' }) Fixes the issue. Not sure why. Maybe the SendMessage could just pass a <type-of-list> to the View and the view could call a function in the document which returns the fields required by the view, like // define structure/class VIEWFIELDS which contain the items required by the View VIEWFIELDS ViewFields; nNextItem = 0; nNextItem = pDoc->GetNextItem(nListType, nNextItem, &ViewFields); until the function returns -1? } ] } Based on the comments you are using the 2003 "XML" output format, that schema is available from microsoft: Have a look at your event log, it should have more detailed information. Most likely your web server is not logged in as the "correct user": refer How to paginate a Word document from c# with Open XML in more if you can generate xml for it. Create a New Word Document, set Pagination into that. save the document as XML see tags for pagination. you might find something like footer1.xml First of all, please note that serverside office interop isn't officially supported by Microsoft: Nevertheless I got a similar scenario running with power point and had to do the following steps to get rid of the error you describe: Run Microsoft Management Console (mmc.exe) Add Snap-In for "Component Services" Slide (you may search for something that sounds correct for your word-scenario) Open Properties > Tab "Security" "Launch and Activation Permissions" > Edit ... Add your application pool user to this list and allow "Local Launch" and "Local Activation" Unless you are going to install Microsoft Office on your server, I would recommend using the Open XML SDK 2.5 from Microsoft. With the SDK you can manipulate Microsoft Office documents for Office 2007 and higher: Here's some code for getting text from a TextBox using both the OpenXML and Office Interop methods: using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using Word = Microsoft.Office.Interop.Word; namespace OpenXMLSDKTest { class Program { static void Main(string[] args) { // Open XML Method object fileName = @"OpenXmlTest.d You've misspelled Word.Application. Also, consider adding a reference to the Microsoft Word Object Library, and then you can use strong types and intellisense: Dim newApp As New Word.Application newApp.Visible=True Dim newDoc = newApp.Documents.Add See here and here for some good starting points. I also refer you to my answer here (It's for python, but the principles are the same). I think you'll find the search function is probably more efficient for you. The following code will search the document and put the values into an array and then put them at the end of the document. It'll also set the paragraph style to reflect the original. Be aware you'll get a nasty output if you keep running it with the styles applied to the output at the end of the document. I've commented it fairly well but let me know if it doesn't make sense. Sub SearchStyles() Dim iCount As Integer, iArrayCount As Integer, bFound As Boolean 'We'll store our result in an array so set this up (assume 50 entries) ReDim sArray(1 To iArrayCount) As String iArrayCount = 50 'State your Style type sMyStyle = "Heading 1" 'Always start at the top of the document Selec You can use 7-pdf library have a look at this it may help : PS: itext has some issues when given file is non RGB image, try this out!! No you can't display a Word document in a JPanel. But you can use the Desktop class. See How to Integrate With the Desktop Class. You need to use a .doc processor java library. Without the help of word processor library, you need to know the format of .doc documents, just you know the structure of .html documents. Apache poi is a good example of such a library. Another approach is to port the MS Office libraries to a java library using COM bridges. I have been using a commercial tool for that purpose. JACOB seems an open source example of a Java-COM bridge, though I have not tested this product. Use a library that can parse Word documents. Apache POI is good choice as long as the documents aren't too big. The library allows you to load the document. Afterwards, you can examine the various parts. Bug 52949 has an attachment with sample code how to extract Macro code. This should get you started. You you're using the new XML format .docx / OOXML, then the word file is in fact a ZIP archive that you can unpack using the standard Java library. Inside, you will find a lot of XML files. The macros should be there as well. You need to write a Microsoft Word addin to do this. For basic on this check microsoft site: Word solutions with Visual Studio And you can do something like below to solve your quesstion. The code will send the mail when you save the document. With a word addin you have alot of events you can cacth and do your own stuff. Or you can add your own button, if you want to send the mail by clicking a button. void ThisAddIn_Startup(object sender, System.EventArgs e) { this.Application.DocumentBeforeSave += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(DocumentSave); } void DocumentSave(Word.Document doc, ref bool test, ref bool test2) { if(doc is Word.Document) { SendMailWithAttachment(doc); } } public void SendMail The file may be in use by another application which is why you're being told it is read-only. This isn't a problem unless you want to write to the file. If you're only trying to read from it my suggestion is to add Application.DisplayAlerts = False to see if it gets rid of the prompt for you. Also note that it is generally good practice to do something more along the lines of Sub YourMethod Dim PrevDispAlerts as Boolean PrevDispAlerts = Application.DisplayAlerts Application.DisplayAlerts = False 'code that does something goes here Application.DisplayAlerts = PrevDispAlerts End Sub Assuming new lines as described, split at new lines and make choices depending on blank lines, e.g. function parse(str) { var a = str.split(' '), // split input and var everything flag = 0, question = -1, qLine = 0, i, questions = []; for (i = 0; i < a.length; ++i) { // loop over lines if (!a[i]) { // if blank line, flag = 1 - flag; // flip choice qLine = 0; // reset multi-line counter } else if (flag === 0) { // if question line if (qLine === 0) { // if new question questions.push({ // add to questions label: a[i], options: [], answer: [] }); ++question; // and increase que An HTTP response can't contain a reference to a file path on the client computer, if that's what you're after then the answer is no. If the file is on the server and you want it to open on the client, then you need to read the entire contents of the file and write those contents to the response. You can use word interop. If I understand well, you want to create a word document, adding texte, and register in your desk(or somewhere else)? Look at this msdn library : Word.Interop You will be able to create a word document, and append text you want. First, I would like to point out the example provided by apache poi - Link, i.e. the correct way to do it would be doc.createParagraph().createRun().addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); However, there is still an existing bug which renders the .docx file unreadable after executing the above statement. It might be resolved soon, in which case the above-mentioned statement will do the work. For the meantime, there is a work-around. First, generate the docx file without any pictures. Then add this class CustomXWPFDocument to your package.Visua Firstly convert doc or docx file into PDF using iOS-htmltopdf Now there many API available for PDF word searching functionality such as PDFKitten. Hope its helpful in right direction........ Found the answer. I had to get the ListString value: // Loop through each table in the document, // grab only text from cells in the first column // in each table. foreach (Table tb in docs.Tables) { for (int row = 1; row <= tb.Rows.Count; row++) { var cell = tb.Cell(row, 1); var listNumber = cell.Range.ListFormat.ListString; var text = listNumber + " " + cell.Range.Text; dt.Rows.Add(text); } } You might use a HTML file as the source: using System; using System.IO; using System.Reflection; using Microsoft.Office.Interop.Word; using System.Windows.Forms; class Program { [STAThread] public static void Main() { var file = new FileInfo("input.html"); Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); try { app.Visible = true; object missing = Missing.Value; object visible = true; _Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref visible); var bookMark = doc.Words.First.Bookmarks.Add("entry"); bookMark.Range.InsertFile(fil You could give a look at NPOI: This project is the .NET version of POI Java project at. POI is an open source project which can help you read/write xls, doc, ppt files. It has a wide application. Take a look at this previous SO thread for more information. It has been a while..maybe there is now a cleaner way without having to use Visual Basic from C Sharp; Using C Sharp with Office Interop has improved recently. I dug this up from very old code, but I use it a lot: using Microsoft.VisualBasic; Application wordApp = (Microsoft.Office.Interop.Word.Application)Interaction.GetObject(null, "Word.Application"); Note the use of null for first parameter PathName. Use of empty string would return a new object instance of Word Application. If you omit the PathName, GetObject will return currently active object. You may want to wrap in a try/catch, and if COM exception occurs, use CreateObject (unless these new-fangled programming practices call this bad practice) You can use XtraReport.ExportToRtf(). See here for the documentation Microsoft Word will open and save an .rtf document without any problems. If you really need the output in .doc or .docx format, have a look at this answer. ActiveDocument.FullName The above gives the full path to the document, including the file name. ActiveDocument.Path The above gives the directory where your document is saved. ActiveDocument.Name The above gives the name of the document, without path information. Try this.... byte[] bte = File.ReadAllBytes("E:\test.doc"); // Put the Reading file File.WriteAllBytes(@"E:\test1.doc", bte); // Same contents you will get in byte[] and that will be save here After you've made all your changes, you can use OnTime to force a slight delay before reading the page statistics. Application.OnTime When:=Now + TimeValue("00:00:02"), _ Name:="UpdateStats" I would also update all the fields before this OnTime statement: ActiveDocument.Range.Fields.Update I wouldn't call Excel a database. ;) Nevertheless this is very well possible. Word has a mail merge feature. It allows you to take one source document and fill in some fields. Then merge it with a data source, like an Excel sheet, to get a resulting document that repeats the source document for each row in the sheet. I'm pretty sure you must have used this feature, back then. I'm using Word 2010, which has a separate ribbon dedicated to Mail Merge, and the wizards is docked to the side. I don't recall exactly in which menu mail merge could be found in Word 2003, but it should be fairly easy to find it now you know the name of the feature. {edit} I see now that the tutorial I linked to, applies to Word 2003. :D Here is MSDN link which help you to resolve your issue. Building a Word Document Using SQL Server Data docx4j has dependencies. One of them is: <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>xmlgraphics-commons</artifactId> <version>1.5</version> </dependency> You need to add this to your class path.
http://www.w3hello.com/questions/-populate-word-document-via-asp-net-
CC-MAIN-2018-17
refinedweb
2,567
57.77
“Good morning. It’s 7:00 a.m. The weather in Malibu is 72 degrees with scattered clouds. The surf conditions are fair with waist-to-shoulder high lines. High tide will be at 10:52 a.m”. Every time I hear this voice of Jarvis in the movie Iron Man it sends me chills down my spine. I am sure just like me many would have dreamt of living a life as sophisticated as Tony Stark. But sadly we have not advanced with technology for a miniature Arc reactor or an AI as smart as JARVIS. But it is possible to replace our boring morning alarm clocks with the one that is similar to Jarvis using a Raspberry Pi. At the end of this project, we will create a very basic GUI using which we can set an alarm and when the alarm goes on we will have a voice which tells us the current time and day with some pre-defined text. Sounds cool right!! So let us build one. Materials Needed - Raspberry Pi - 3.5” TFT LCD Screen - Speaker - AUX cable - Internet Connection Pre-Requisites It is assumed that your Raspberry Pi is already flashed with an operating system and is able to connect to the internet. If not, follow the Getting started with Raspberry Pi tutorial before proceeding. Here we are using Rasbian Jessie installed Raspberry Pi 3. It is also assumed that you have access to your pi either through terminal windows or through other application using which you can write and execute python programs and use the terminal window. You might also want to check out how to interface 3.5” TFT LCD with Raspberry Pi since we will be using it in this project. Install TTS Engine (Espeak) for Raspberry Pi As the project title states we are going to build a speaking clock. In order to make your Pi speak we need a Text To speech (TTS) Engine. There are so many options to select from, but for the sake of simplicity I have select the Espeak Engine. To install Espeak on your Pi simply run the following command on your terminal sudo apt-get install espeak sudo apt-get install espeak python-espeak Creating GUI for Raspberry Pi Speaking Alarm Clock For this project we need to develop a GUI that represents an alarm clock so that the user can view the current time and also set the alarm. There are lots of options to develop a GUI using Python, but the most popular and versatile one is the PyQt4, so we will use that to develop our GUI. In the below few headings we discuss how to use PyQt4 to design your own GUI’s, but if you are not interested you can directly skip down to “Program for Speaking Alarm Clock” heading. Installing PyQt4 with Qt designer on your Windows Machine Since we are designing a GUI we will first start our programming on our laptop (windows/Linux) and then port this python script to work on our Pi. Since PyQt4 has a very good portability most developers do this since the development is easy and faster in a laptop then actually doing it on a Raspberry Pi. I have installed python and PQt packages on my windows machine; if you are not interested in this you can develop your GUI on your raspberry pi itself by simply skipping this step. To install PQt on windows download this exe file and during the installation procedure make sure you have checked the Qt designer software since we will be using it for our project. Installing PyQt on Pi/Linux/MAC machines To install PyQt on Linux machine simply run the following line on your command terminal sudo apt-get install python-qt4 Designing the GUI using Qt Designer One noticeable advantage of using PyQt4 for your GUI designs is that it has Qt designer software. This software can be used to create button, displays, texts and other graphics by simply dragging things into screen and placing them wherever required. This saves us a lot of time since we don’t have to manually feed in the size and position of the objects on our screen. I have installed Qt designer along with Python and PyQt4 on my windows laptop using the exe file as discussed in above paragraph. After installing open your Qt Designer and you will get this screen. On the left side you can find layout, spacers, buttons and other items which you can simply use by dragging it into your window. You can also customize the objects as required using the windows on the right. I have used a 7-segment LCD display, a button, a text line and set time object to create the UI for our alarm clock. After using layouts to place all the objects in the required place and size my window looked something like this below Once your GUI is ready you can save your design as a .ui file. Later, anytime when you wish to make changes to your GUI you can simply open this file and do the changes without having to scroll up and down in your program. The .ui file for speaking clock can be downloaded if you wish to make any changes to this design. Once you are satisfied with the GUI design you can export it as a python code from where you can begin your python programming. I know many things here would have bounced over your head, but it is not possible to explain how to use the Qt4 library in a single tutorial. You can refer to sentdex PyQt4 tutorial series to know more on how to use PyQt4 and Qt designer software. Python Program for Raspberry Pi Speaking Alarm Clock The complete python code for this project is given at the end of this page. You can directly run it on your Raspberry pi to get output, but further below I have explained the program into small snippets so that you can understand how the program works. Almost half of the code is already written for us by the Qt designer software, this code has then information about the type, style, size and position of the objects that are on top of our screen. Now all that we have to do is provide purpose and function for these objects. The 7-segment display is used to show the current time. The set-time object is used to select the alarm time and the button “set alarm” should be clicked to set the alarm on the selected time. The text line at the bottom shows when the alarm is set and other useful information. Apart from that we also have to play voice alarm when the alarm is set and triggered. For our program we need the PyQt4 for designing the GUI and espeak to play voice alarm and time package strftime to read the current time from Pi. So we import all the three packages using the below line of code. from PyQt4 import QtCore, QtGui #PyQt4 is used for designing the GUI from espeak import espeak #text to speech sonversion from time import strftime # To get time from Raspberry pi Next we have a chunk a codes which was obtained from the Qt designer, these codes will consist of the position and size of the widgets that we have placed on the screen. We have edited the code a little to assign purpose to the widget. First on the 7-segment LCD widget we have to display the current time, this can be done by using the strftime method which will give us the current time that’s running on Pi. We can then display this time on the LCD as shown below.) Next we have a button pressed button, when this button is pressed we have to set the alarm. So we use a method called button_pressed. Whenever this button is pressed the function button_pressed will be called. self.pushButton = QtGui.QPushButton(self.centralwidget) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.pushButton.clicked.connect(self.button_pressed) #when button pressed call the button pressed function self.gridLayout.addWidget(self.pushButton, 2, 1, 1, 1) MainWindow.setCentralWidget(self.centralwidget) The button_pressed function is shown below. Here we read the values of hour and minutes from the set time widget. This information will be in form of string, so it can be trimmed to get the value of hour and minutes and stored in the variable alarm_h and alarm_m. Once we have the value of minute and hour we can use this to compare it with current minutes and hour. Finally after the set time is read we also display a text using the string variable message. This message will be displayed as a label text. We also give a voice alert stating that the alarm was set for so and so time by using the espeak method. This method just speaks any text passed to it via the audio jack. Here the string in the variable message is read out espeak.synth (message) #speak the message through audio jack Finally we need one more method, that compares the current time with set time and when both match it has to notify the user through speech. For this purpose we have the time function in our code, it compares the current_h with alarm_h and current_m with alarm_m. When both match it triggers the alarm by speaking the text stored in the variable message1. You can customise the variable message1 if you wish to make the clock speak something else; right now it will wish you good morning along with the current time and day.) Hardware Set-up for Raspberry Pi Alarm Clock The Hardware set-up for this project is pretty simple. We are using just using a 3.5” TFT LCD screen with our PI. To set up the display you can follow the Interfacing Pi with 3.5” LCD tutorial. Once your interfacing is complete you should be able to use the stylus and navigate through the OS of raspberry pi. In order to play the sound you need to have a speaker, I have connected by portable speaker to pi through AUX cable. Once everything is set and the program is launched my set-up looked like this below. Working of Pi based Speaking Alarm Clock Prepare the hardware as shown above and then make sure you have installed PyQt4 and Espeak on your Pi. Then use then python code given below, just paste it in the python IDLE and run the program. It will launch the GUI window as shown below It shows the current time and also provides a text box to set the alarm. Use your stylus to set the alarm time and press on set alarm button. This will give you a voice message stating that the alarm is set. Now just wait till the current time shown on the 7-seg display is equal to the alarm time. When its equal the alarm is triggered, this will again give a voice message with current time and day. This alarm will repeat four times before the minute value changes. The complete working of the project can be found at the video link given below. This is just a base for the project and you can easily build on top of by adding snooze and stop button. Also, customize the voice message based on your preference or based on location and what not? Let me know what you have in mind. Hope you understood the tutorial and enjoyed building it. If you have any problem please feel free to drop them on the comment section or use the forums for other technical quires. # Speaking alarm clock using Raspberry Pi #Connect 3.5" LCD and speaker though AUX and run the program with PyQt4 and espeak packages # Program by: B.Aswinth Raj # Website: circuitdigest.com # # GUI code was created using Qt Designer import sys import time from PyQt4 import QtCore, QtGui #PyQt4 is used for designing the GUI from espeak import espeak #text to speech sonversion from time import strftime # To get time from Raspberry pi #Code from Qt Designer try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): self.alarm_h = 0 self.alarm_m = 0 MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(676, 439) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout = QtGui.QGridLayout(self.centralwidget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label = QtGui.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(14) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 3, 0, 1, 1)) self.timer = QtCore.QTimer(MainWindow) self.timer.timeout.connect(self.Time) self.timer.start(1000) current_time = QtCore.QTime() self.Set_Time = QtGui.QTimeEdit(self.centralwidget) self.Set_Time.setObjectName(_fromUtf8("Set_Time")) self.Set_Time.setTime(current_time.currentTime()) self.gridLayout.addWidget(self.Set_Time, 2, 0, 1, 1) self.pushButton = QtGui.QPushButton(self.centralwidget) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.pushButton.clicked.connect(self.button_pressed) self.gridLayout.addWidget(self.pushButton, 2, 1, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 676, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) #End of code from Qt Designer def retranslateUi(self, MainWindow): #update the GUI window print("Dispay Re-translated") MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.label.setText(_translate("MainWindow", "Alarm curretly Turned off", None)) self.pushButton.setText(_translate("MainWindow", "Set Alarm", None)) if __name__ == "__main__": #main function app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) Mar 24, 2019 First of all, I want to really thanks to you for your very detailed tutorial. I was following your tutorial, and I got a problem. In my pi, when I activate the alarm python code, the clock number left to the "Set Alarm" seems to be shown with AM/PM. When I choose PM, the alarm goes well. It has no problem at all. However when I choose AM, the alarm doesn't set. And I get a error message on terminal window which is : File "alarm.py", line 124, in button_pressed Mar 24, 2019 self.alarm_h = int(alarm_time[19:21]) #value of hour is sorted in index value of 19 and 20 ValueError: invalid literal for int() with base 10: '2,' Can you help me what part am I doinig wrong? I didn't changed your code. I only added some mp3 play line which I guess doesn't effect the code. Aug 04, 2019 Heyy, Im wokring on tihs clock and ran into the same problems too. Have you figured or worked it out? Jun 18, 2019 I have tried to do this a couple of times and keep getting stuck. There appear to be massive jumps in the tutorial that are assuming we already know how to do things. Examples: * how to use PyQt4 here - from the command line? What command? * The same for espeak, time, strftime - you introduce the time strftime package with no indication of how it is used here * Where do we put the "chunk a codes"? * How do we use the strftime method? Is there no way of just setting this up so it works with code that you have set up with a step by step explanation (including the actual commands) of how to implement this on the Raspberry Pi... ? Aug 14, 2019 Hi, I did do few jumps trying to keep the article as small as possible. Sorry if it stops you people from actually trying it. The probelm is with the lib. that you are importing inside you python script. Mostly likely you have not added these packages eariler whcih throws an error import sys import time from PyQt4 import QtCore, QtGui #PyQt4 is used for designing the GUI from espeak import espeak #text to speech sonversion from time import strftime # To get time from Raspberry pi Try to use these line in your shell window to check if they throw any error, if yes please install the respective packge. If you still face problems please post them here
https://circuitdigest.com/microcontroller-projects/raspberry-pi-based-jarvis-themed-speaking-alarm-clock
CC-MAIN-2020-50
refinedweb
2,762
62.07
How to display a splash screen for at specific minimum length of time in WPF WPF supports the ability to make an image load immediately as a splash screen to give your application the appearance of loading faster. It doesn’t actually load faster, but seeing the splash screen is a “feel good” experience for the user. Adding a basic splash screen Adding a Splash Screen to a WPF application is very easy, now. - Right-click any image in the start-up project and choose Properties. - Set the Build Action to SplashScreen. Yes it is that easy. You are done. The problem with the basic splash screen We found that on some machines the splash screen is a “must have” because the application load time was greater than two seconds. In fact, it was so long that without the splash screen, the user thought the program didn’t start and clicked it again. So a splash screen was added the default way. However, on newer and faster machines, the application load time was less than half a second. For these newer and faster devices, the splash screen loads and closes so quickly it is awkward. It would actually be better to always have the splash screen show for a minimum of two seconds whether the machine is fast or slow. Adding a splash screen that displays for a minimum amount of time Step 1 – Add an image to use as a splash screen to your project - Add an image to your Visual Studio project. Note 1: I put mine in an images folder and since I it is a “Hello World” example, I just grabbed the first picture from an internet search. Note 2: Use a .png file. - In Visual Studio, right-click on the image and choose Properties. - Make sure the image is set to Resource. Important! Do not set it to Splash Screen. Step 2 – Take control of the window startup - Open the App.xaml file. <Application x: <Application.Resources> </Application.Resources> </Application> - Remove the StartupUri tag seen below in line 4. <Application x: <Application.Resources> </Application.Resources> </Application> - Open the App.xaml.cs. using System.Windows; namespace SimpleSplashExample { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } } - Add a couple integers as member variables, one for the minimum time, 1.5 seconds, and one for the splash screen fade time, .5 seconds. - Override the OnStartup method. - Add a SplashScreen object using the image you added earlier and show it. - Add a StopWatch object to monitor the time and start timing. - Load the Window object that previously was being loaded by the StartupUri, but don’t show the window yet. - Stop the StopWatch and then see how much time has elapsed. - If the time is less than 1.5 seconds sleep the remaining time. - Stop the SplashScreen. - Now, show your window. Note: I added comments showing how to do this in five basic steps. using System; using System.Diagnostics; using System.Threading; using System.Windows; namespace SimpleSplashExample { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private const int MINIMUM_SPLASH_TIME = 1500; // Miliseconds private const int SPLASH_FADE_TIME = 500; // Miliseconds protected override void OnStartup(StartupEventArgs e) { // Step 1 - Load the splash screen SplashScreen splash = new SplashScreen("Images/Globe-256.png"); splash.Show(false, true); // Step 2 - Start a stop watch Stopwatch timer = new Stopwatch(); timer.Start(); // Step 3 - Load your windows but don't show it yet base.OnStartup(e); MainWindow main = new MainWindow(); // Step 4 - Make sure that the splash screen lasts at least two seconds timer.Stop(); int remainingTimeToShowSplash = MINIMUM_SPLASH_TIME - (int)timer.ElapsedMilliseconds; if (remainingTimeToShowSplash > 0) Thread.Sleep(remainingTimeToShowSplash); // Step 5 - show the page splash.Close(TimeSpan.FromMilliseconds(SPLASH_FADE_TIME)); main.Show(); } } } You now have a splash screen with a nice, consistent user experience whether you have fast or slow hardware. Thanks, I didn’t remember what it was like, but here’s a new solution: public partial class App : Application { private const int MINIMUM_SPLASH_TIME = 1500; // Miliseconds private const int SPLASH_FADE_TIME = 2500; // Miliseconds protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); SplashScreen splash = new SplashScreen(“img/1.png”); Stopwatch timer = new Stopwatch(); timer.Start(); Login_Window login = new Login_Window(); MainWindow main = new MainWindow(); this.MainWindow = main; Nullable dialogResult = login.ShowDialog(); if (dialogResult == false) { MessageBox.Show(“The app will be closed!”); this.Shutdown(); return; } splash.Show(false, true); timer.Stop(); int remainingTimeToShowSplash = MINIMUM_SPLASH_TIME – (int)timer.ElapsedMilliseconds; if (remainingTimeToShowSplash > 0) Thread.Sleep(remainingTimeToShowSplash); await Task.Run(() => { splash.Close(TimeSpan.FromMilliseconds(SPLASH_FADE_TIME)); Thread.Sleep(SPLASH_FADE_TIME); }); main.Show(); } } Hello, I asked a question about a month ago. How to delay the appearance of the main window. And in the text my issue was important for me information. There I had a decision of how to make a delay. Now I needed to make a delay again, but I forgot how. And I didn’t keep the text of that question. Could you send me an e-mail alexfarm2@yandex.ru the text of my question. Sincerely, Alexis Pretty simple and easy to implement. Thanks for sharing Great ! exactly as I want Thanks, dude. This was very helpful I wanted to thank you as well. Cheers I am glad this helped you. Wonderful, thank you for this! Anytime…I’m just glad it helped you. I needed to do it, so I documented it. Glad it helped you too.
https://www.wpfsharp.com/2012/02/14/how-to-display-a-splash-screen-for-at-specific-minimum-length-of-time-in-wpf/
CC-MAIN-2019-13
refinedweb
892
60.92
Write bytes to a file #include <unistd.h> ssize_t write( int fildes, const void* buf, size_t nbytes ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The write() function attempts to write nbytes bytes to the file associated with the open file descriptor, fildes, from the buffer pointed to by buf. If nbytes is zero, write() returns zero, and has no other effect. On a regular file or other file capable of seeking, and if O_APPEND isn't set, write() starts at a position in the file given by the file offset associated with fildes. If O_APPEND is set, the file offset is set to the end of file before each write operation. Before successfully returning from write(), the file offset is incremented by the number of bytes actually written. On a regular file, if this incremented file offset is greater than the length of the file, the length of the file is set to this file offset. On a file not capable of seeking, write() starts at the current position. If write() requests that more bytes be written than there's room for (for example, all blocks on a disk are already allocated), only as many bytes as there's room for are written. For example, if there's only room for 80 more bytes in a file, a write of 512 bytes would return 80. The next write of a nonzero number of bytes would give a failure return (except as noted below). When write() returns successfully, its return value is the number of bytes actually written to the file. This number is never greater then nbytes, although it may be less than nbytes under certain circumstances detailed below. If write() is interrupted by a signal before it has written any data, it returns a value of -1, and errno is set to EINTR. However, if write() is interrupted by a signal after it has successfully written some data, it returns the number of bytes written. If the value of nbytes is greater than INT_MAX, write() returns -1 and sets errno to EINVAL. See <limits.h>. Write requests to a pipe (or FIFO) are handled the same as a regular file, with the following exceptions: If you call write() with nbytes greater than PIPE_BUF bytes, it either transfers what it can and returns the number of bytes written, or transfers no data, returning -1 and setting errno to EAGAIN. Also, if nbytes is greater than PIPE_BUF bytes and all data previously written to the pipe has been read (that is, the pipe is empty), write() transfers at least PIPE_BUF bytes. When attempting to write to a file (other than a pipe or FIFO) that supports nonblocking writes and can't accept the data immediately: If write() is called with the file offset beyond the end-of-file, the file is extended to the current file offset with the intervening bytes filled with zeroes. This is a useful technique for pregrowing a file. If write() succeeds, the st_ctime and st_mtime fields of the file are marked for update. #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> char buffer[] = { "A text record to be written" }; int main( void ) { int fd; int size_written; /* open a file for output */ /* replace existing file if it exists */ fd = creat( "myfile.dat", S_IRUSR | S_IWUSR ); /* write the text */ size_written = write( fd, buffer, sizeof( buffer ) ); /* test for error */ if( size_written != sizeof( buffer ) ) { perror( "Error writing myfile.dat" ); return EXIT_FAILURE; } /* close the file */ close( fd ); return EXIT_SUCCESS; }
http://www.qnx.com/developers/docs/qnxcar2/topic/com.qnx.doc.neutrino.lib_ref/topic/w/write.html
CC-MAIN-2022-40
refinedweb
601
69.92
All dates in your server applications should be stored in the UTC timezone. This is because you always want to store time without the offset of the timezone you may be working in. Clients of your application may be in many different timezones around the world. However, storing all data in the UTC or GMT (same thing) timezone, is ideal as it gives your application the ability to present times and dates back in the same methodology. Option 1 We always import the datetime module, but this option allows us to make sure that we are providing times from the timezone.utc module. from datetime import datetime, timezone datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") Option 2 You can also exclude the timezone module and do it as follows: from datetime import datetime datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") Rationale I personally prefer the first option ( Option 1), as it is more timezone aware. Eventhough both options will work just fine, the former allows the ability to think more timezone centric.
https://ao.gl/how-to-get-the-utc-timestamp-in-python/
CC-MAIN-2020-45
refinedweb
178
61.77
Hi All, I've been working on a App and submitted it to the App Exchange. I have had some issue with the CSRF attacks. What is the best way in FLASK to do this? I am writing my app in Python. Answer by BradPark (312) | Dec 04, 2017 at 05:24 PM Like QName said, the best way to fix a CSRF attack with a flask app is by using the protections offered by Flask-WTF. By adding the module to your program, you’re able to easily and automatically check all POST, PUT, DELETE, and related methods. If you don’t modify data with a GET or related method (and you shouldn’t anyway), that should suffice. As a reminder, you should never use a GET to create, update, or delete information. Edit: Note: This is not a complete working example. These are the parts you could add to your app to implement this CSRF protection. from flask_wtf.csrf import CSRFProtect app = Flask(__name__) #This value should be unique per install, stored like the rest of your secrets, see bottom of post for more app.secret_key = data['SECRET_KEY'] #You'll want to give your session cookie a name specific to your app app.config.update( SESSION_COOKIE_NAME='MyApp-Session', ) #CSRF configuration csrf = CSRFProtect(app) csrf.init_app(app) #Every relevant request will be checked for the CSRF header @app.before_request def check_csrf(): csrf.protect() #No additional configuration is needed, routes need no additional decorators @app.route('/') def landing_page(): """ Landing page """ return render_template('index.html') Add this hidden field to any forums you submit, <form method="post"> #... Other elements <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/> #... Submit buttons and stuff </form> And add this if you make JavaScript requests <script type="text/javascript"> var csrf_token = "{{ csrf_token() }}"; $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrf_token); } } }); </script> You could write your own CSRF protection. While I always recommend using an existing library to save reinventing and maintaining the wheel, CSRF protection is one of the simpler issues to fix. An explanation as to what Flask-WTF does, CSRF attacks are defeated by having a unique, secret value sent with any request that can modify data that is NOT sent automatically by the browser (such as a cookie). Adding the CSRF token as part of the payload, or as a header of its own are good ways of doing this. The CSRF token should be randomly generated via a cryptographically secure means. This value must be the different per user per session. If you want to learn more, checkout the OWASP section on CSRF attacks, and protection. They have great articles. Edit: Addition on generating the app secret key Like you see above, I don't actually define my app.secret_key in the source code itself, that is because your app secret key should be unique per app install for security reasons. I won't give a particular code example, as the way config data handling varies greatly from app to app, but essentially what you want is a script that runs during your app startup phase. This script should check where your secret key is stored, and create it if it doesn't exist. #src_deps/init/keySetup.py #Psuedo-code example data = load(config_data) if data does not contain 'SECRET_KEY' OR data['SECRET_KEY'] is "": data['SECRET_KEY'] = cryptographically_secure_generator() Simply setting app.secret_key=cryptographically_secure_generator() would cut out the middleman, the downside is that your secret key is re-generated every time your app starts. From a security perspective this is OK, however this cause user experience issues if your app unexpectedly restarts and their CSRF tokens (or other values) generated with the old secret key are now invalid. This is confusing. The views.py file normally opens like this: from app import app from flask import request from flask import render_template Should that still be there? Also, can WTForms imports be completely ignored? It is WTFlask, after all. Also, according to the Support Functions docs, CSRF tokens are created and handled automatically, presumably in a header. If that's the case, is all this really necessary? Approaching this another way, is there a complete working example somewhere? Hi Daniel, I added a comment to the main post which will hopefully clarify. My code above is not a complete working example, but what you should add to use the Flask-WTF CSRF protection. From my understanding of the support docs you mention, those seem to be referring to interacting with Qradar's CSRF protection. It's a little confusing that we get CSRF tokens to interact with Qradar, and also need CSRF tokens to protect our own apps. Currently I do not have a working example, but I will try and find some time to build a fully functional app demonstrating this and some of my other posts on secure engineering. Thanks, Bradley. I still am confused. In your example, I'm still not sure if the usual imports need to be the same. It seems like "from app import app" and "app = Flask(name)" might conflict, and I don't see "Flask()" imported. Given what normally appears in views.py, and what you've written, is this the the proper way to start views.py? (I'm not a Flask expert.) from app import app from flask import request from flask import render_template from flask_wtf.csrf import CSRFProtect app = Flask(__name__) app.secret_key = data['SECRET_KEY'] csrf = CSRFProtect(app) csrf.init_app(app) Answer by QName (33) | Dec 04, 2017 at 03:42 PM The most common way is with CSRF tokens, using something like: 130 people are following this question.
https://developer.ibm.com/answers/questions/416755/qradar-app-exchange-secure-development-how-can-i-f.html?childToView=446212
CC-MAIN-2019-39
refinedweb
947
56.25
No project description provided Project description django-postgres-queue django-postgres-queue is a task queue system for Django backed by postgres. Why postgres? I thought you were never supposed to use an RDBMS as a queue? Well, postgres has some features that make it not as bad as you might think, it has some compelling advantages. Transactional behavior and reliability. Adding tasks is atomic with respect to other database work. There is no need to use transaction.on_commit hooks and there is no risk of a transaction being committed but the tasks it queued being lost. Processing tasks is atomic with respect to other database work. Database work done by a task will either be committed, or the task will not be marked as processed, no exceptions. If the task only does database work, you achieve true exactly-once message processing. Operational simplicity By reusing the durable, transactional storage that we’re already using anyway, there’s no need to configure, monitor, and backup another stateful service. For small teams and light workloads, this is the right trade-off. Easy introspection Since tasks are stored in a database table, it’s easy to query and monitor the state of the queue. Safety By using postgres transactions, there is no possibility of jobs being left in a locked or ambiguous state if a worker dies. Tasks immediately become available for another worker to pick up. You can even kill -9 a worker and be sure your database and queue will be left in a consistent state. Priority queues Since ordering is specified explicitly when selecting the next task to work on, it’s easy to ensure high-priority tasks are processed first. Disadvantages - Lower throughput than a dedicated queue server. - Harder to scale a relational database than a dedicated queue server. - Thundering herd. Postgres has no way to notify a single worker to wake up, so we can either wake every single worker up when a task is queued with LISTEN/NOTIFY, or workers have to short-poll. - With at-least-once delivery, a postgres transaction has to be held open for the duration of the task. For long running tasks, this can cause table bloat and performance problems. - When a task crashes or raises an exception under at-least-once delivery, it immediately becomes eligible to be retried. If you want to implement a retry delay, you must catch exceptions and requeue the task with a delay. If your task crashes without throwing an exception (eg SIGKILL), you could end up in an endless retry loop that prevents other tasks from being processed. How it works django-postgres-queue is able to claim, process, and remove a task in a single query. DELETE FROM dpq_job WHERE id = ( SELECT id FROM dpq_job WHERE execute_at <= now() ORDER BY priority DESC, created_at FOR UPDATE SKIP LOCKED LIMIT 1 ) RETURNING *; As soon as this query runs, the task is unable to be claimed by other workers. When the transaction commits, the task will be deleted. If the transaction rolls back or the worker crashes, the task will immediately become available for another worker. To achieve at-least-once delivery, we begin a transaction, process the task, then commit the transaction. For at-most-once, we claim the task and immediately commit the transaction, then process the task. For tasks that don’t have any external effects and only do database work, the at-least-once behavior is actually exactly-once (because both the claiming of the job and the database work will commit or rollback together). Comparison to Celery django-postgres-queue fills the same role as Celery. In addition to to using postgres as its backend, its intended to be simpler, without any of the funny business Celery does (metaprogramming, messing with logging, automatically importing modules). There is boilerplate to make up for the lack of metaprogramming, but I find that better than importing things by strings. Usage Requirements django-postgres-queue requires Python 3, at least postgres 9.5 and at least Django 1.11. Installation Install with pip: pip install django-postgres-queue Then add 'dpq' to your INSTALLED_APPS. Run manage.py migrate to create the jobs table. Instantiate a queue object. This can go wherever you like and be named whatever you like. For example, someapp/queue.py: from dpq.queue import AtLeastOnceQueue queue = AtLeastOnceQueue( tasks={ # ... }, notify_channel='my-queue', ) You will need to import this queue instance to queue or process tasks. Use AtLeastOnceQueue for at-least-once delivery, or AtMostOnceQueue for at-most-once delivery. django-postgres-queue comes with a management command base class that you can use to consume your tasks. It can be called whatever you like, for example in a someapp/managment/commands/worker.py: from dpq.commands import Worker from someapp.queue import queue class Command(Worker): queue = queue Then you can run manage.py worker to start your worker. A task function takes two arguments – the queue instance in use, and the Job instance for this task. The function can be defined anywhere and called whatever you like. Here’s an example: def debug_task(queue, job): print(job.args) To register it as a task, add it to your queue instance: queue = AtLeastOnceQueue(tasks={ 'debug_task': debug_task, }) The key is the task name, used to queue the task. It doesn’t have to match the function name. To queue the task, use enqueue method on your queue instance: queue.enqueue('debug_task', {'some_args': 0}) Assuming you have a worker running for this queue, the task will be run immediately. The second argument must be a single json-serializeable value and will be available to the task as job.args. Monitoring Tasks are just database rows stored in the dpq_job table, so you can monitor the system with SQL. To get a count of current tasks: SELECT count(*) FROM dpq_job WHERE execute_at <= now() This will include both tasks ready to process and tasks currently being processed. To see tasks currently being processed, we need visibility into postgres row locks. This can be provided by the pgrowlocks extension. Once installed, this query will count currently-running tasks: SELECT count(*) FROM pgrowlocks('dpq_job') WHERE 'For Update' = ANY(modes); You could join the results of pgrowlocks with dpq_job to get the full list of tasks in progress if you want. Logging django-postgres-queue logs through Python’s logging framework, so can be configured with the LOGGING dict in your Django settings. It will not log anything under the default config, so be sure to configure some form of logging. Everything is logged under the dpq namespace. Here is an example configuration that will log INFO level messages to stdout: LOGGING = { 'version': 1, 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'dpq': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, } } It would also be sensible to log WARNING and higher messages to something like Sentry: LOGGING = { 'version': 1, 'root': { 'level': 'INFO', 'handlers': ['sentry', 'console'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'sentry': { 'level': 'WARNING', 'class': 'raven.contrib.django.handlers.SentryHandler', }, }, 'loggers': { 'dpq': { 'level': 'INFO', 'handlers': ['console', 'sentry'], 'propagate': False, }, }, } You could also log to a file by using the built-in logging.FileHandler. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/django-postgres-queue/
CC-MAIN-2021-10
refinedweb
1,255
55.54
view raw I need to find the average of 5 assignments = two inputs. I'm getting a result, but its no correct. Here is what I have: def main(): # list of grades x = [] # count of students n = 5 # fill list with grades from console input # using pythonic generator x = [int(input('Please enter the grade you got on assignment {}: '.format(i+1))) for i in range(n)] midTermGrade = int(input('Please enter the grade you got on you Mid-Term: ')) finalGrade = int(input('Please enter the grade you got on you Final: ')) average_assignment_grade = sum(x) + midTermGrade + finalGrade / 7 print('Avg grade is ', average_assignment_grade) main()
https://codedump.io/share/doBYfOvZLdsa/1/find-average-of-list--2-inputs---python
CC-MAIN-2017-22
refinedweb
104
56.79
just want to move it to the new server, just leave it at 1.1. As an aside, I ran the make pointing to the .net 2.0 and changed the site on the w2003 box to be be 2.0 asp.net version and the web app worked. When I just move it over to the w2008 64 bit box, I get now get a different error. Server Error in '/' Application. -------------------------- Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load type 'WrkTrngStatus.WrkReadyGri Source Error: Line 1: <!--ASPX page @1-5DAFC528--> Line 2: <%@ Page language="vb" Codebehind="WrkReadyGrid.a Line 3: Line 4: <%@ Import namespace="WrkTrngStatus.W Source File: /WrkTrngStatus/WrkReadyGri -------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4927 Try making a new iis application pool and set it to 32 bit. With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you. In the w2003 world, it was set up as a virtual directory and that was all that was set for it on the w2008 box. I removed the virtual directory and told IIS to make it an application and now it is happy. Thanks again for your quick response.
https://www.experts-exchange.com/questions/26465690/How-to-migrate-an-asp-net-framework-1-1-app-from-W2003-32-bit-server-to-a-w2008r2-64-bit.html
CC-MAIN-2018-13
refinedweb
254
68.16
Windows Azure AppFabric October 2010 CTP - Service Bus Samples from my PDC Talk (Part 1) In my PDC talk I’m showing a few little samples that are not in the SDK for the CTP release. I’ve bundled them up and they’re attached to this post. The solution contains three samples: - SBMT is the ‘Service Bus Management Tool’, a small command line utility to create/view/delete ConnectionPoints and MessageBuffers using the new management model for Service Bus. I’ll explain the options of the tool below and will drill into the inner workings of the tool and the ideas behind the new management interface in the next post of this series. - EchoService/EchoClient are versions of the meanwhile probably familiar ‘Echo’ sample for Service Bus that illustrates the new load balancing capability with session affinity. - DurableMessageBufferSample is a variation of the SDK sample for the new durable message buffer that sends a sequence of 200 messages and fetches them back.> ..]</ - -n <namespace> - the Service Bus namespace created via - -a <account-name>– the service account name that’s set up in Access Control (defaults to ‘owner’) - -s <account-secret>– the service account key set up in Access Control (the key you find on the portal) - <type>– ‘cp’ for connection points, ‘mb’ for message buffers - <command>– ‘create’, ‘get’, or ‘delete’ (see below) - <resource-name>– a unique, friendly name for the resource (eg. ‘crm-leads’) - <uri>– the URI projection into the runtime namespace (e.g. ‘sb://<NAMESPACE>.servicebus.appfabriclabs.com/crm/leads/’) - <args>– further arguments (see below) Examples: - Create a connection point. ‘cp create’ requires a trailing argument after the URI that indicates the number of concurrent listeners (max. 20): sbmt.exe –n clemens –a owner –s […] cp create crm-leads sb://clemens.servicebus.appfabriclabs.com/crm/leads/ 10 - Delete a connection point: sbmt.exe –n clemens –a owner –s […] cp delete crm-leads - Show a connection point: sbmt.exe –n clemens –a owner –s […] cp get crm-leads - Enumerate all connection points: sbmt.exe –n clemens –a owner –s […] cp get - Create a message buffer: sbmt.exe –n clemens –a owner –s […] mb create jobs 10 - Delete a message buffer: sbmt.exe –n clemens –a owner –s […] mb delete jobs - Show a message buffer: sbmt.exe –n clemens –a owner –s […] mb get jobs - Enumerate all message buffers: sbmt.exe –n clemens –a owner –s […] mb get The Echo sample requires that you create a connection point in your namespace like this: - sbmt.exe –n –a owner –s […] cp create cp1 sb://<namespace>.servicebus.appfabriclabs.com/services/echo/ 10 The Message Buffer sample requires this setup, whereby the friendly name is asked for by the sample itself (‘mb1’, so you can choose that freely) - sbmt.exe –n –a owner –s […] mb create mb1 https://<namespace>.servicebus.appfabriclabs.com/mybuf/. pdc10-servicebus-oct10-ctp.zip (24.65 KB)
https://docs.microsoft.com/en-us/archive/blogs/clemensv/windows-azure-appfabric-october-2010-ctp-service-bus-samples-from-my-pdc-talk-part-1
CC-MAIN-2021-25
refinedweb
478
51.89
Opened 5 years ago Closed 5 years ago Last modified 5 years ago #8782 closed defect (fixed) MacroList should only display one help entry when there are multiple macros defined that differ only by case Description The MacroList macro should only display a single entry when multiple macros are defined that differ only in case. As an example, the th:wiki:EmailProcessorMacro allows [[Email]]. I briefly discussed this with the author in th:5713 (screen capture is shown there). With my limited knowledge of Trac, I believe this is due to the two entries in get_macros. def get_macros(self): """Yield the name of the macro based on the class name.""" yield 'email' yield 'Email' Would it be reasonable to alter MacroList so that only one help entry is displayed? Perhaps the header can show Attachments (0) Change History (8) comment:1 Changed 5 years ago by - Summary changed from MacroList should be case insensitive to MacroList should only display one help entry when there are multiple macros defined that differ only by case comment:2 Changed 5 years ago by comment:3 Changed 5 years ago by - Milestone set to next-minor-0.12.x comment:4 Changed 5 years ago by - Keywords bitesized added comment:5 follow-up: ↓ 6 Changed 5 years ago by Rather, create one entry for each macro_provider, grouping the macro_provider.get_macros() names as the macro names corresponding to the macro_provider.get_description(). comment:6 in reply to: ↑ 5 Changed 5 years ago by - Component changed from general to wiki system - Resolution set to fixed - Status changed from new to closed comment:7 Changed 5 years ago by - Owner set to cboos comment:8 Changed 5 years ago by - Milestone changed from next-minor-0.12.x to 0.12 I don't think assuming that macros whose name only differ in case are the same is a good idea. We could, however, group them if the documentation strings are non-empty and identical, as this would be a reasonable condition that they operate the same. I would be +0 on that. The [[MacroList]]macro is implemented in trac/wiki/macros.py(in case you want to try to implement the change yourself :-).
http://trac.edgewall.org/ticket/8782
CC-MAIN-2015-06
refinedweb
366
67.18
Logged In: YES user_id=11105 Does it work when you write it in this way: import dbi import odbc using the odbc module (from win32all), dbi.pyd is copied, but not in the library.zip : no dbi.pyo! thus not fould. Logged In: YES user_id=11105 Does it work when you write it in this way: import dbi import odbc I have observed no problem with 0.6.5 but with 0.6.6 the problem occurs: >type test_odbc.py if __name__ == '__main__': import odbc >type setup.py import distutils.core import py2exe distutils.core.setup( console = ['test_odbc.py'] ) >dist\test_odbc.exe Traceback (most recent call last): File "test_odbc.py", line 2, in <module> import odbc File "odbc.pyc", line 12, in <module> File "odbc.pyc", line 10, in __load odbc: Cannot import dbi module I have tried to find the difference between 0.6.5 and 0.6.6 that causes the error and found that the import works if I replace the run.exe from 0.6.6 by the one of 0.6.5 in the site-packages\py2exe directory. So I suppose the problem is not in the packageing itself but in the way modules are loaded in the resulting .exe file. It works with 0.6.6 if I import dbi before importing odbc as suggested in the comment. Leo Log in to post a comment.
https://sourceforge.net/p/py2exe/bugs/60/
CC-MAIN-2018-17
refinedweb
231
88.43
. I agree. I think a retry mechanism would be misused by new programmers. I don’t think there is too machine situations where it would be useful. In your example above with the file not being closed – rather than trying to retry the operation until the file was closed, wouldn’t it be better to work out why the file wasn’t being closed? For example, if this was allowed I could see the following code being written: File.Create(@"c:MyFile.txt"); try (10) { File.Open(@"c:MyFile.txt", FileMode.Open); } catch (IOException) { retry; } In this situation the user doesn’t realize that File.Create returns an open FileStream and they wonder why when they call the File.Open method that it fails. So rather then work out why they simply add a retry mechanism that ends up relying on the garbage collector to finalize the FileStream and close the handle. This is why I don’t like it. Personally, the biggest thing I would like with try-catch blocks is for the typed catch syntax to be recursive through the InnerException property. As in your example above, the catch statement would be "catch (MyFileNotFoundException e)", and it would automatically recurse down through the InnerException properties of the originally thrown one. It would probably have to be optional somehow I guess, maybe add a keyword to make it "catch recursively (MyFileNotFoundException e)", to prevent any breaking changes to existing code. I do see the pattern you show above a lot in pretty much every C# project I’ve worked on, and as you rightly point out it’s easy to make that mistake and just swallow everything silently. why not just do something like int retries = 10; bool fileopen = FALSE; int tryNumber = 0; while (!fileopen && tryNumber++ < retries) { try { Process(); fileopen = TRUE; } catch (MyFileNotFoundException e) { PrintHelpfulWarningMessage(tryNumber, retries) } } if (!fileopen) { DieAHorribleDeath(); } Seriously, it is a waste of time to discuss this feature in c#. Whatever we have currently can be used to get the same behavior. Exceptional "Exception Handling" comes from good architecture of the system. There is always an efficient design out there that does good exception handling. We obviously need another layer on top to customize it for individual applications. The other problem with retry logic is that sometimes developers will retry a method or a few lines of code, but not realize that the code itself is not transactional. For example, if the code fails, it is not necessarily the case that everything is in the same state as the first try. I think if you plan on adding retry logic to anything, you’d want to double check to make sure that the operations are somewhat atomic and a failure indicates that you pretty much are back in your original state. Eric Gunnerson has some advice about exception handling and recovery on his blog:thisThe vast majority… Jon>>Personally, the biggest thing I would like with try-catch blocks is for the typed catch syntax to be recursive through the InnerException property. Actually, I think Eric was arguing against wrapping exceptions needlessly. It’s been my experience that there is never a good time to be handling an InnerException. If an exception is wrapped, then the code that wrapped it is telling you that it is unrecoverable and is attempting to give you more information to fix the problem with your code. If the InnerException is something that should or could be handled by a consuming code, then it should not have been wrapped. I have seen plenty of examples where an exception was wrapped simply to say "I was here!". That’s what the stack trace is for. "I was here" wrapping exceptions are useless, yes. But when they add information about the parameters passed into the function (such as what filename to act on, or some other internal state) then they’re priceless. That’s actually one of the things that irritates me the most about the current exception stack traces — they don’t show the parameter values. Even if that was limited to native types (like ints and strings) it’d be a big help. <quote> Without any user-written exception handling, the behavior of your code WRT exceptions is fully specified. Every exception makes it up to the outmost layer, so you know about everything bad that happens. </quote> The fully specified part is correct – the outmost layer is wrong, specifically in the case where an exception is thrown which percolates down from one app domain to another but cannot be serialized across the boundary. I beat my head against a wall every time this happens since you lose the stack trace.* Another reason to do it is because some of the system developers one the .net side were either slack or too performance focused. e.g. from 1.1 ArrayList indexer: public virtual object get_Item(int index) { if ((index < 0) || (index >= this._size)) { throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); } return this._items[index]; } AAAAAARgh – ArgumentOutOfRangeException(string, object, string) exists to provide the bloody value! you have it, use it… Ok in this case that would trigger a box, not great (though a good case for providing an integral special case). But then IndexOutOfRangeException doesn’t bother to provide the index either… would it really have been that big a deal to provide an int field in this exception, ok in some cases the jit may make filling it in impossible (or at least computationally expensive) but come on – it is used by string GetChar() too. Hell even allowing the option of providing additional info in core exceptions as a compile / init constant would do. Matt * this is all written from the point of view of someone stuck with 1.1 for a while longer – no ideas if 2.0 works round this Talking about the last-chance handler. When your application is running in an unattended environment you do want to catch ALL unhandled exceptions and do two things: log as much information as possible about the exception and the state of the process and then recover from the problem (ultimately by rebooting). In the unmanaged world I have SetUnhandledExceptionFilter and MiniDumpWriteDump at my disposal but I have yet to find a perfectly matching (read: equally powerful) alternative in the managed environment. Currently I’m trying to get by with a watchdog application that uses MDBG to monitor the other process, stop on unhandled exceptions and dump as much information on the process that I can get (I currently managed to retrieve the exception, inner exceptions, the active thread stack, all other managed thread stacks, all AppDomains and the assemblies loaded in each AppDomain). I got this idea off one of the .NET debugging blogs if I remember well. But this all feels so amateur-like. I am craving for a .NET minidump! Matt, I thought about the thread and appdomain case when I was writing that, but I didn’t want to complicate the discussion needlessly. It is something you need to keep in mind when you’re planning how to handle exceptions at the global level, but I don’t think it invalidates my point. With regard to the "eating of exceptions bug" when handling specific inner exceptions, wouldn’t the following counter that? try { Process(); } catch (Exception e) { if (e.InnerException.GetType() == typeof(MyFileNotFoundException) { Recover(); // use your imagination for how this works } else { throw; // <- ADDED THIS TO RETHROW ORIGINAL EXCEPTION } } I have had some instances of really needing to recover something based on an inner exception: e.g. (from memory) while hosting winword in a Windows Forms application where on some machine configurations a COM exception with a specific error number, or exceptions you get back from that now obsolete emailer in the v1.1 System.Web namespace where the actual error including SMTP error response is a couple of levels of inner exceptions deep. I thought you would have 🙂 That certainly doesn’t invalidate the core point about avoiding anything but last chance handlers without a very good reason, for instance you can recover from it or you want to make sure some unanticipated user input doesn’t kill the whole system just perhaps their segment of it… The lack of detailed information in several of the core system parameters does mean that it becomes much more tempting to write "I was here"* exceptions but adding the calling parameters. so you can work out what went wrong faster. Were the System ones to supply more info the temptation would be removed. * good name Miral 🙂 It’s real important to also look at an exception handling scheme in regard to code maintenance. It’s not too hard writing code that works today and you feel comfortable beleiving the exception handling works (today). The difficult part comes a few years from now when you’ve moved on to another project and someone else starts making changes to your code. I am a firm believer in catching specific exceptions at the level they are thrown, perform the appropriate steps to put the object (or environment) in "good" state, and throw a more generic exception that wraps the specific exception. Attempting to recover from exceptions at a higher call level is a defect waiting to happen. In your example, if the Process method implementation is changed at a later point. It may be possible to have MyFileNotFoundException being thrown because several different reasons. Plus, the recovery logic may need to be changed for each case. Essentually, by attempting to handle specific recovery outside the point of the problem, you would have to know implementation details of the lower level and that breaks object encapsulation. I agree with miral. I often need to rethrow the exception because there is crucial data I need to diagnose the problem. My canonical case for this is wrapping SQL calls. It’s nice to know where it failed, but I need to know exactly what parameters or sql were being processed at the time the failure occurred. Given that I test heavily, it is likely that we have an error that only reveals itself under unusual data combinations. Without that info I’m seriously hampered. Other than this situation, I can easily support what Eric says. Miral>>But when they add information about the parameters passed into the function (such as what filename to act on, or some other internal state) then they’re priceless. That was my point exactly. InnerExceptions should not be handled. They are purely informational to diagnose the problem and correct the code. If the InnerException should be or could be handled by the consumer, then don’t wrap it, pass it on. So the choice I was presenting was between wrapping an exception to be left unhandled by the consumer, thus producing a visible error or not wrapping an exception if it is possible for the consumer to fix it in a try-catch block. Try-catch blocks should not be walking the InnerException stack. If that is happening then either the consumer is abusing the object or the producer was doing something stupid like "I was here" exception wrapping. The inner exception. or any other field, such as an error code, hresult, or message data, shoul not be used for recovery purposes. Reasons: there may be multiple chained exceptions, so there is no clear indication which inner exception should be examined for recovery purposes; the fields may have been changed by intermediate code, the value and meaning of a particular field may change over time or environment conditions, and the only guarantee made by the runtime is the type of exception caught by the catch handler. Ultimately, the only block of code that has a reasonable chance of having enough detailed information to really know what the root causes of that exception might be is the code that caught the initial exception. However, this also doesn’t help much because the code at that level typically does not have sufficient information to understand the context that it is operating in to make a retry decision; typically, only the code that initiated the original request has that context. The code closest to the exception site has specific fault information but little context to evaluate it with. About the catch/no catch decision….I disagree with the guidelines. A stack trace is often not sufficient for diagnostic purposes, and there are times when a stack trace is not even present. Even more compelling, a stack trace is not the same as context…what was it doing, and why was it doing it? Ultimately, the diagnostic information must be understandable by the end user so that they can figure out what they can do differently to avoid the problem the next time,m or just to understand the root causes of the problem. Displaying a NullReferenceException does not tell them what they need to know..why did it fail, and more importantly, what can they do differently the next time so that the request succeeds? I prefer to catch-wrap-throw at all major logic decision points, each time adding additional context to the exception message, such as method parameter values or meaningful internal state. The exception type itself can be cloned so that the type caught at the top of the stack is the same as the type originally thrown. A weakness of the current guidelines is that it does not distinguish between the strategies that different types of software should employ. There’s a difference between writing a component that many different types of software will consume and run in many different environments versus an application that must provide logging and diagnostic information to an end user. In my view, the ultimate guide on how to handle exceptions is not how to make it easy for developers to write code (though this is a good goal) but how to build a product that is end-user friendly. I put my thoughts about exception guidelines in my book Practical .NET2 and C#2 (). Here is the excerpt: When should you consider throwing an exception? The exception mechanism is generally well understood but quite often used improperly. The base principle is that an application which functions in a normal way should not throw exceptions. This forces us to define what an abnormal situation is. There are three types: — Those which happen because of a problem with the execution environment but can be solved by a modification to this environment (missing file, invalid password, non-well-formed XML document, network unavailability, restricted security permissions…). Here we talk of business exception. — Those which happen because of an execution environment problem which cannot be solved. For example memory hungry applications such a SQL Server 2005 may be limited to 2 or 3GB of addressing space in a 32-bits Windows process. Here we talk of asynchronous exceptions from the fact that they are not related to the semantic of the code which raised it. To manage this type of problem, you must use advanced CLR features syh as CER and critical finalizers. This is essentially equivalent to treating such abnormal situation as normal! Be aware that only the large servers with push the limits of its resources should encounter asynchronous exceptions and will need to use these mechanisms. — Those which happen because of a bug and which can only be solved by a new version which fixes properly the bug. What to do in exception handlers? When you catch an exception, you can envision three scenarios: — Either you are faced with a real problem but that you can address it by fixing the conditions which cause the problem. For this, you may need new information (invalid password -> ask the user to reenter the password…). — Either you are faced with a problem which you cannot resolve at this level. In this case, the only good approach is to rethrow the exception. It is possible that there may not be a proper exception handler and in this case, you delegate the decision to the runtime host. In console or windowed applications, the runtime host causes the whole process to terminate. Note that you can use the AppDomain.UnhandledException event which is triggered in this situation in order to take over the termination of the process. You can take advantage of this ‘last chance’ to save your data (as with Word) which without this would definitely lead to data loss. In an ASP.NET context, an error processing mechanism, is put in place. — In theory, a third scenario can be envisioned. It is possible that the exception that was caught represents a false alarm. In practice, this never happens. You must not catch an exception to simply log it and then rethrow it. To log exceptions and the code that they have traversed, we recommend using less intrusive approaches such as the use of specialized events of the AppDomain class or the analysis of the methods on the stack at the moment where the exception was thrown. You must not release the resources that you have allocated when you catch an exception. Also be aware that in general only unmanaged resources are susceptible of causing problems (such as memory leaks). This type of code to release resources must be placed in the finally block or in a Dispose() method. In C#, the finally blocks are often implicitly encapsulated in a using block which acts on objects implementing the IDisposable interface. Where should you put exception handlers? For a specific type of exception, asking this question comes down to asking yourself at which method depth this exception must be caught and what must be done about it. By method depth, we. Exceptions vs. returned error code You may be tempted to use exceptions instead of returning error codes in your methods, in order to indicate a potential problem. You must be careful as the use of exceptions suffers from two major disadvantages: — The code is hard to read. In fact, to understand the code, you must manually do the work of the CLR which consists in traversing the calls until you find an exception handler. Even if you properly separate your calls into layers, the code is still difficult to read. — Exception handling by the CLR is much more expensive than simply looking at an error code. The fundamental rule mentioned at the beginning of this section can help you make this decision: an application which functions within normal conditions does not raise exceptions. Never under estimate bugs whose consequences are caught by exception handlers those which goes uncaught such as indeterminist, unexpected or false results. Patrick Smacchia MVP.NET
https://blogs.msdn.microsoft.com/ericgu/2006/02/15/exception-handling-guidelines/
CC-MAIN-2018-13
refinedweb
3,111
60.35
04-01-2009 08:35 PM I have a PlayerListener that's supposed to call invalidate on a Field while the Player is playing. I don't know why but the field is not being repainted. Here's the code: public class PlayerHandler implements PlayerListener { public PlayerHandler() { } public void playerUpdate(Player player, String event, Object data) { if (event == (PlayerListener.STARTED)) { new Thread(new SelectFieldUpdate()).start(); } else if (event == (PlayerListener.STOPPED)) { field.invalidate(); } } private class SelectFieldUpdate implements Runnable { public void run() { while(player.getState() == Player.STARTED) { field.invalidate(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } of course, i add this listener to my player. any help will be appreciated. Thanks! 04-02-2009 12:50 AM 04-02-2009 01:55 AM - last edited on 04-02-2009 02:04 AM yeah I tried the debugger. invalidate is definitely being called. i'm not sure if anything is actually happening though. it looks like paint may have ran once and that's it, but invalidate keeps being called, presumably because of the while loop, so that much is correct. I don't really have a good grasp of the UI Stack and such. is there something that could be interfering with the painting? needless to say the Player is running at the moment, although that should be running in a different thread as well. i tried encapsulating the insides of paint() in a Runnable, but instead nothing got drawn. no clue what's going on.... edit: instead of invalidate() i tried to call setText() on a different LabelField within that Runnable and I got a IllegalStateException what the heck does this mean? 04-02-2009 10:16 AM 04-02-2009 10:18 AM - last edited on 04-02-2009 10:19 AM UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { //set Text } });
http://supportforums.blackberry.com/t5/Java-Development/PlayerListener-not-working/td-p/201043
crawl-003
refinedweb
304
59.5
V1.2 (21-11-2001) - Fixed typo in Create_TCP_Connection code snippet - CoUnIntialize() should be CoUninitialize() - IID_LPDIRECTPLAYLOBBY2A should be IID_IDirectPlayLobby2A V1.1 (11-4-2000) Abstract Seeing that there are few (if any) tutorials on DirectPlay, and that it is such a pain to learn DirectPlay from the MSDN (like I have), I thought I would alleviate some of the agony by writing this tutorial. Also I have this day off since I'm waiting for the monstrous 100 MB DX 7 SDK download. If you find any errors, please email me at robin@cyberversion.com What This Tutorial is About The tutorial will use Directx 5.0 or the IDirectPlay3 interface. I know DX 7.0 is out but I am still downloading it and I passed with DC 6. Although DC 5.0 is inefficient (every packet has high overhead), it seems the new versions are getting better. Anyway, the idea should mainly be the same. The demo will be a chat program that I am using for my game. It is not a lobby server (a lobby server is something like Blizzard's BattleNet), just a client/server program. The user is assumed to be familiar with C/C++ and some Win32 programming (Of course, DX too). Some networking concepts would help. No MFC, I hate MFC. Putting another layer on Win32 API bothers me when you can access Win32 functions directly. Also, I will only use TCP/IP. If you want to use IPX, modem, or cable, check out the MSDN. They are roughly equivalent. This tutorial by no means teaches you everything about DirectPlay. Any networking application is a pain to write, and you should consult the MDSN documentation for more information (mostly where I learnt DirectPlay from). There is no sample demo exe too as I don't have time to write one out to show you. Let's get started What DirectPlay is About DirectPlay is a layer above your normal network protocols (IPX, TCP/IP etc). Once the connection is made, you can send messages without needing to know what the user is connecting with. This is one of the best features (IMO) and though some of you may come up with more efficient messaging protocols with WinSock, I'd rather use DirectPlay and save me hordes of trouble. BTW, DirectPlay uses Winsock too. Sessions in DirectPlay A DirectPlay session is a communication channel between several computers. An application must be in a session before it can communicate with other machines. An application can either join an existing session or create a new session and wait for people to join it. Each session has one and only one host, which is the application that creates it. Only the host can change the session properties (we will get to that detail later). The default mode in a session is peer-to-peer, meaning that the session complete state is replicated on all the machines. When one computer changes something, other computers are notified. The other mode is client/server, which means everything is routed through a server. You manage the data in this mode, which is probably the best in a chat program. However, I used sort of a hybrid in this tutorial. Players in DirectPlay An application must create a player to send and receive message. Messages are always directed to a player and not the computer. At this point, your application should not even know about the computer's location. Every message you sent is directed at a specific player and every received message is directed at a specific local player (except for system messages; more on that later). Players are identified only as local (exist on your computer) or remote (exist on another computer). Though you can create more than one local player on your machine, I find it not very useful. DirectPlay offers additional methods to store application specific data so you don't have to implement a list of players but I'd rather do my own list. You can also group players in the same session together so any message sent to you will get directed to the group. This is great for games where you can ally with other people and you want to send messages to your allies only. Unfortunately, you have to explore that area on your own. If at this point you find all this very troublesome, try writing your own network API. You will be glad what DirectPlay does for you. Messages in DirectPlay Now we have a session and a player, we can start sending messages. As I said, each message sent is marked by a specific local player and can be sent to any player. Each message received is placed in a queue for that local player. Since I create only one player, all the messages belong to that player. You don't need to bother about this queue; all you need is to extract the messages from it and act on them. The application can poll the receive queue for messages or use a separate thread and events. I tried the thread method and it works great, except for when I use MessageBox to notify the user (in case you don't know, MessageBox displays a message box in Windows). If you want to use threads, you need to pause the thread when the application displays a message box and somehow it gets very messy with synchronization. So I opted for the poll method. Feel free to use threads if you think you can handle it. There are two types of messages: player and system. Player messages have a sender and receiver. System messages are sent to every player and are marked sent from the system (DPID_SYSMSG). DP stands for DirectPlay, ID for identification. If you cannot understand messages, go and learn more about DirectDraw first. System messages are generated when the session state is changed, i.e. when a new player joins the session. Note: There are also security features using the Security Support Provider Interface (SSPI) on windows. These messages are encrypted and such. I don't think this is of much use in gaming. Actual implementation Whew. Now we get to more details. If you didn't quite understand any of the above, please read them again till you do. If you have any questions like "What if..." it will be answered soon. So let's move on. The first thing to do is to include the DirectPlay header files: #include <dplay.h> // directplay main #include <dplobby.h> // the directplay lobbyAlso add DPLAYX.LIB to your project. If you are wondering why there is a dplay.lib and dplayx.lib, add the dplayx.lib cause I think there are more methods there used in the lobby. Also if you are asking why am I including the dplobby methods when I am not using a lobby server, it will become clearer later. Also you need to define INITGUID or add the dxguid.lib. Define this at the very top of your project. #define INITGUID // to use the predefined idsNext you need to give you application a GUID (Global Unique Id). This ID is to distinguish the application in the computer. You don't want your application to send messages to your browser, only your application. You can use guidgen.exe to create a id for your application. Microsoft guarantees that it will never mathematically create the same GUID twice, so we take their word for it. It will look something like DEFINE_GUID(our_program_id, 0x5bfdb060, 0x6a4, 0x11d0, 0x9c, 0x4f, 0x0, 0xa0, 0xc9, 0x5, 0x42, 0x5e);Now to define our globals LPDIRECTPLAY3A lpdp = NULL; // interface pointer to directplay LPDIRECTPLAYLOBBY2A lpdplobby = NULL; // lobby interface pointerIf you are wondering what the A behind the interface stands for, it means ANSI version. There are two versions for DirectPlay – ANSI and Unicode. (Unicode is a standard for using 16 bits to represent a character instead of 8 bits, just for internationalization. Just use the ANSI version and forget about supporting multiple languages. Makes everybody happy.) The next thing is the main loop of the program. This is the bare skeleton of what it looks like. // Get information from local player // Initialize Directplay connection from the information from above while(1) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE) { // Your normal translating message } // end if PeekMessage(..) else { // Your game loop // Receive messages – We will implement this } // end else } // end of while(1) // Close Directplay ConnectionHow you get information from the user is up to you. You can do it via a dialog box or any other way you deem. The main thing you need to get is the name and whether if it is the server or client. If it is the server, you get the session name. If it is the client, you get the TCP/IP address to connect to. Anyway, we store those in a global below: BOOL gameServer; // flag for client/server char player_name[10]; // local player name, limit it to 10 chars char session_name[10]; // name of session, also limit to 10 chars char tcp_address[15]; // tcp ip address to connect toI'm sorry if you are firmly against globals. Feel free encapsulate them, but I think globals simplify the learning process here. Also I do not do much error checking here; theoretically you should test the result of every function call. Now before we move on, we should implement a list of players in the current session. Although it will not be necessary here, you will need it in larger applications. You create a list with the following item element: Class DP_PLAYER_LIST_ELEM{ DPID dpid; // the directplay id of player char name[10]; // name of player DWORD flags; // directplay player flags // any other info you might need };You need to implement a list class that adds a player and deletes a player with a specific dpid. Do not reference the players by their names because players can have the same name. Use the id to differentiate players. Due to space constraints, I will not include any code here. Alternatively you can use arrays to hold the global player information, but this is not scalable and more troublesome. Then we define a global pointer to the class: DP_PLAYER_LIST *dp_player_list; // list of players in current sessionThat is about all the globals you need. You should also create a local player struct for additional information for local players only. Setting up Connection Initialization To set up the connection, we will write a function that takes a TCP/IP string and create a TCP/IP connection. This is also where the lobby interface comes in. Side note: Although DirectPlay has a method for enumerating the connections available, the method will enumerate all connections even if they are not available. So if you do not have an IPX connection, the enumeration will return an IPX option to connect and the connection would fail only when the user tries to make the connection. This seems redundant to me so I recommend you skip this part and give the options to the user straight, failing only when the user tries to make the connection. In case you don't know about enumeration, we will talk more about it later. Enumerating things in DirectX is for the user to provide a function that is called (repeatedly) by a process in DirectX. This is known as a callback function. Here goes the function. Remember you should do error checking for every function call. int Create_TCP_Connection(char *IP_address) { LPDIRECTPLAYLOBBYA old_lpdplobbyA = NULL; // old lobby pointer DPCOMPOUNDADDRESSELEMENT Address[2]; // to create compound addr DWORD AddressSize = 0; // size of compound address LPVOID lpConnection= NULL; // pointer to make connection CoInitialize(NULL); // registering COM // creating directplay object if ( CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay3A,(LPVOID*)&lpdp ) != S_OK) { // return a messagebox error CoUninitialize(); // unregister the comp return(0); } // creating lobby object DirectPlayLobbyCreate(NULL, &old_lpdplobbyA, NULL, NULL, 0); // get new interface of lobby old_lpdplobbyA->QueryInterface(IID_IDirectPlayLobby2A, (LPVOID *)&lpdplobby)); old_lpdplobbyA->Release(); // release old interface since we have new one // fill in data for address Address[0].guidDataType = DPAID_ServiceProvider; Address[0].dwDataSize = sizeof(GUID); Address[0].lpData = (LPVOID)&DPSPGUID_TCPIP; // TCP ID Address[1].guidDataType = DPAID_INet; Address[1].dwDataSize = lstrlen(IP_address)+1; Address[1].lpData = IP_address; // get size to create address // this method will return DPERR_BUFFERTOOSMALL – not an error lpdplobby->CreateCompoundAddress(Address, 2, NULL, &Address_Size); lpConnection = GlobalAllocPtr(GHND, AddressSize); // allocating mem // now creating the address lpdplobby->CreateCompoundAddress(Address, 2, lpConnection, &Address_Size); // initialize the tcp connection lpdp->InitializeConnection(lpConnection, 0); GlobalFreePtr(lpConnection); // free allocated memory return(1); // success } // end int Create_TCP_Connection(..)First we initialize COM to increment its count by 1 and we create the DirectPlay object using CoCreateInstance. This is another method of creating DirectX objects, which is actually the method the wrapper function uses. We have to pass in the class identifier and such but the main thing to note is the IID_DirectPlay3A parameter. This is the identifier of the IDirectPlay3A interface. So if you want to get an IDirectPlay2A interface, set the parameter to IID_DirectPlay2A. Similarly if you want an IDirectPlay4A interface. Then we create the DirectPlay lobby object and we query for the 2A version. Since there is a macro DirectPlayLobbyCreate, we do not need to initialize COM like above. Underneath, this function does the same (COM and CoCreateInstance) except it gets the lowest interface, ie IDirectPlayLobbyA. So we need to get the 2A version, which is done by querying it with the interface identifier (note you query all DirectX objects in the same manner). Then we close the old lobby since we have a new one. Next we create an address that holds the information about the TCP connection. Since we did not use EnumConnections, we need to build that information ourselves. You can use the information from the enumeration and jump straight to initialize but I prefer to reduce callback functions to a minimum. We set the fields of the address structure and we set the type to the TCP/IP service provider id. This is from defined in dxguid.lib or the including INITGUID above. We set the second element to the address string. You can get all these information from the MSDN, and which parameters to pass to create other types of connection. Then we get the size of buffer required for the connection by passing in a NULL parameter. The size required will be stored in the variable Address_Size. Note this method will return DPERR_BUFFERTOOSMALL since we are getting the size. Do not interpret this as an error condition. We then allocate memory from the system heap using GlobalAllocPtr, rather than using malloc. We then create the address information by passing the allocated buffer to the function again. Using that we call the DirectPlay Initialize method and we would have created a TCP/IP connection. If InitalizeConnection returns DPERR_UNAVAILABLE, it means the computer cannot make such a connection and it's time to inform the user no such protocol exists on the computer. People may wonder why I chose to do things the hard way when I could have used DirectPlayCreate and be happy. Well, the main thing is I want to override the default dialog boxes that would pop up to ask the user to enter the information. You don't see that in StarCraft, do you? (Sorry, love Blizzard) Do note that you should test every function call and return the appropriate error. I do not do that here because of space and also I'm lazy. Also as for how this function works, you pass "" as the string if you are the hosting the session, else you pass the IP of the machine you are connecting to. So in the "Getting user information", you should have enough information to call this function like: if (gameServer) // if host machine Create_TCP_Connection(""); // empty string is enough else Create_TCP_Connection(tcp_address); // passed the global ip from userIf you think this is the end of connecting, think again. Remember, we need to have a session and a player before we send messages. But before that let's close the connection. int DirectPlay_Shutdown() { if (lpdp) // if connection already up, so it won't be null { if (lpdplobby) lpdplobby->Release(); lpdp->Release(); CoUninitialize(); // unregister the COM } lpdp = NULL; // set to NULL, safe practice here lpdplobby = NULL; return(1); // always success } // end int DirectPlay_Shutdown();Stick this function at the close connection section. Sessions You will have no choice but to do a callback function here. The main functions you mainly need to do session management are: EnumSessions - enumerates all the session available sessions Open - joins or hosts a new session Close - close the session GetSessionDesc - get session properties SetSessionDesc - set session propertiesI will only talk about the 3 functions above that we will use in this tutorial. Once you understand them, it is very easy to understand the others. lpdp->Close();Simple. Just close the session before you call DirectPlay_Shutdown(): All the local players created will be destroyed and the DPMSG_DESTROYPLAYERORGROUP will be sent to other players in the session. lpdp->EnumSessions(..); // enumerates all the sessionsThis function will only be called by the client side so if you are hosting the session, call Open. What is so troublesome is that the client needs to search for a session to join when they have made a connection, and since there may be more than one session in the host, we need to get every available session and present them to the user. This will require the use of a callback function. The callback function prototype is: BOOL FAR PASCAL EnumSessionsCallback2(LPCDPSESSIONDESC2 lpThisCD, LPDWORD lpdwTimeOut, DWORD dwFlags, LPVOID lpContext);Things to note: This callback function that we implement will be called once for each session that is found using EnumSessions. Once all the sessions are enumerated, the function will be called one more time with the DPESC_TIMEOUT flag. Any pointers returned in a callback function are only temporary and are only valid in the callback function. We must save any information we want from the enumeration. This applies to the player enumeration later. EnumSessions has the prototype: EnumSessions(LPDPSESSIONDESC2 lpsd, DWORD dwTimeOut, LPDPENUMSESSIONSCALLBACK2 lpEnumSessionCallback2, LPVOID context, DWORD dwFlags);If you wondering why there is a 2 behind certain typedefs, the two means the second version of the type. A rule of thumb is to always use the latest typedefs as they encapsulate more things. The first parameter is a session descriptor so you need to initialize one. DPSESSIONDESC2 session_desc; // session desc ZeroMemory(&session_desc, sizeof(DPSESSIONDESC2)); // clear the desc session_desc.dwSize = sizeof(DPSESSIONDESC2); session_desc.guidApplication = our_program_id; // we define this earlierThis will ensure our program only returns sessions hosted by our program. ZeroMemory is similar to memset to 0 and as you should know, many DirectX calls require you to put the size in the structure passed. The second parameter should be set to 0 (recommended) for a default timeout value. The third parameter is the callback function so we pass the function to it The fourth parameter is a user-defined context that is passed to the enumeration callback. I will describe how to use it later. The fifth is the type of sessions to enumerate. Just pass it the default 0 meaning it will only enumerate available sessions. Check out the MSDN for more options. All these seem to be a good candidate for a function so let's do it. // our callback function BOOL FAR PASCAL EnumSessionsCallback(LPCDPSESSIONDESC2 lpThisSD, LPDWORD lpdwTimeOut, DWORD dwFlags, LPVOID lpContext) { HWND hwnd; // handle. I suggest as listbox handle if (dwFlags & DPESC_TIMEOUT) // if finished enumerating stop return(FALSE); hwnd = (HWND) lpContext; // get window handle // lpThisSd-> lpszSessionNameA // store this value, name of session // lpThis->guidInstance // store this, the instance of the host return(TRUE); // keep enumerating } // end callback // our enumeration function int EnumSessions(HWND hwnd, GUID app_guid, DWORD dwFlags) { DPSESSIONDESC2 session_desc; // session desc ZeroMemory(..); // as above // set size of desc // set guid to the passed guid // enumerate the session. Check for error here. Vital lpdp->EnumSessions(&session_desc, 0, EnumSessionsCallback, hwnd, dwFlags); return(1); // success } // end int EnumSessionsI suggest sending a listbox handle as the context so we can save the information and display it to the user. In the callback function, you must allocate space to hold the guidInstance. This is the instance of the program that is hosting the session. You need to pass this information for the user to select which one session. I have commented out the name and the instance. You save them in whatever way you want. Declare a global array and fill in the member. Whatever. I suggest a listbox so you can send messages via the hwnd parameter. Remember, the instance and name are only valid inside the callback function so you must save them to be able to present them later. Note: If you return false in the callback, the enumeration will stop and return control the EnumSessions. If you don't stop it, it will loop forever. Also return false if you encounter an error inside. It is imperative you check the value from EnumSessions especially if you are not enumerating available sessions only. Also, the whole program will block while you are enumerating because it has to search for sessions. You can do an asynchronous enumeration too. Check it out yourself. lpdp->Open(LPDPSESSIONDESC2 lpsd, DWORD dwFlags)This functions hosts or joins a session using the dwFlags. If you are joining a session, you only need to fill the dwSize and guidInstance (you saved it somewhere) of the descriptor. So we define a descriptor as: DPSESSIONDESC2 session_desc; ZeroMemory(&session_desc, sizeof(DPSESSIONDESC2)); session_desc.dwSize = sizeof(DPSESSIONDESC2); session_desc.guidInstance = // instance you have save somewhere; // and join the session lpdp->Open(&session_desc, DPOPEN_JOIN);If you are hosting a session, you need to fill in, in addition to the above, the name of the session, the maximum number of players allowed in the session and the session flags. You set the flag to Open as DPOPEN_CREATE | DPOPEN_RETURNSTATUS. The return status flag hides a dialog box displaying the progress status and returns immediately. Although the documentation says I should keep calling Open with the return status flag, I have not found a need to do so (nor can I comprehend the reason they gave). You can change the session properties if you are a host using the other two methods I didn't cover. The flags in the session desc you should set in this tutorial are: DPSESSION_KEEPALIVE – keeps the session alive when players are abnormally dropped. DPSESSION_MIGRATEHOST – if the current host exits, another computer will become the host.You can Or the flags together like so: FLAG_1 | FLAG_2 | FLAG_3. Check out the MSDN for more flag options. Player Creation We are just about done setting up. Now we create a local player using CreatePlayer. You have to define a name struct like so: DPNAME name; // name type DPID dpid; // the dpid of the player created given by directplay ZeroMemory(&name,sizeof(DPNAME)); // clear out structure name.size = sizeof(DPNAME); name.lpszShortNameA = player_name; // the name the from the user name.lpszLongNameA = NULL; lpdp->CreatePlayer(&dpid, &name, NULL, NULL, 0, player_flags);This function will return a unique id for the local player within the session. Use this to identify the player rather than using the name. Save this in the local player struct. The player_name passed is obtained earlier in the information asked from user. The middle parameters are used if you do not want to poll the receive queue. Use them if you want to do multithreading. The player flags is either DPPLAYER_SERVERPLAYER or 0, which means non-server player. There can only be one server player in a session. There is also a spectator player but its meaning is defined by the application so we don't use it here. The other function needed is EnumPlayers. I know you all are masters at enumerating now so I leave you all to implement this. Remember the global list of players we defined earlier? Just add the player inside the callback. It works the same way as the enumeration above. You don't have to enumerate the players in this chat but it is cool that you can see who is also connected at the same time. You do not need to destroy the player because closing the session does that automatically and I don't see why you need to destroy and create another player while you are still connected. Still, it is your application. Message Management Now that we have a player, we need to know how to send and receive messages. I will talk about sending messages first. Sending Messages There is only one way to send a message and that is through the Send function. (Actually there is another if you use a lobby). If you remember, sending a message requires the id of the sender and the receiver. Good thing you have saved the local player id in a local player struct and all the players' ids in a global player list. So call the function as follows: lpdp->Send(idFrom, idTo, dwFlags, lpData, dwDataSize);The idFrom is the id of the local player. This must be set to a locally created player only (we don't want to impersonate another player, do we?) which in most cases is only one. The idTo is the receiver's id. Use DPID_SERVERPLAYER to send to the server only and DPID_ALLPLAYERS to send to everybody (except yourself). Note you cannot send a message to yourself. If you want to direct the message to a specific player, use the player list. You do not have to use a player list in a chat; instead you can add everything to a listbox. But later in the game, a list of players comes handy. The flag parameter is how should the message be sent. The default is 0, which means non-guaranteed. The other options are DPSEND_GUARANTTED, DPSEND_ENCRYPTED and DPSEND_SIGNED. Sending a guaranteed message can take more than 3 times longer than a non-guaranteed one so only use guaranteed sending for important messages (like text). The signed and encrypted messages require a secure server, which we did not setup. Also any message received is guaranteed to be free of corruption (DirectPlay performs integrity checks on them). Something to note: If you create a session that specifies no message id, their message idFrom will make no sense and the receiver will receive a message from DPID_UNKNOWN. Why anyone would want to disable message id is beyond me. The last two parameters are a pointer to the data to send and the size of that block. Note that DirectPlay has no upper limit of the size you can send. DirectPlay will break large messages into smaller packets and reassemble them at the other end. Beware when sending non-guaranteed messages too; if one packet is lost, the whole message is discarded. Since we are doing a chat program, I will show an example of sending a chat message // types of messages the application will receive const DWORD DP_MSG_CHATSTRING = 0; // chat message // the structure of a string message to send typedef struct DP_STRING_MSG_TYP // for variable string { DWORD dwType; // type of message char szMsg[1]; // variable length message } DP_STRING_MSG. *DP_STRING_MSG_PTR; // function to send string message from local player int DP_Send_String_Mesg(DWORD type, DPID idTo, LPSTR lpstr) { DP_STRING_MSG_PTR lpStringMsg; // message pointer DWORD dwMessageSize; // size of message // if empty string, return dwMessageSize = sizeof(DP_STRING_MSG)+lstrlen(lpstr); // get size // allocate space lpStringMsg = (DP_STRING_MSG_PTR)GlobalAllocPtr(GHND, dwMessageSize); lpStringMsg->dwType = type; // set the type lstrcpy(lpStringMsg->szMsg, lpstr); // copy the string // send the string lpdp->Send(local_player_id,idTo, DP_SEND_GUARANTEED, lpStringMsg, dwMessageSize); GlobalFreePtr(lpStringMsg); // free the mem return(1); // success } // end int DP_Send_String_Mesg(..)We first define the types of messages we can have. Since this is a chat program, there can only be one type, which I set to DP_MSG_CHATSTRING. You may add others and set the type so you can reuse the string sending function for different things. That is why the string message struct has a type to differentiate the string contents. The send function basically allocates space and sends the function to the desired player. Note the local_player_id is stored somewhere globally, or you can set it to pass another variable to set the local_player_flag. Do check the errors returned especially with allocation routines. Receiving Messages Receiving messages requires slightly more work than sending. There are two types of messages we can receive – a player message and a system message. A system message is sent when a change in the session state occurs. The system messages we trapped in this chat are: DPSYS_SESSIONLOST - the session was lost DPSYS_HOST - the current host has left and you are the new host DPSYS_CREATEPLAYERORGROUP – a new player has join DPSYS_DESTROYPLAYERORGROUP – a player has leftSome of those messages are only sent if certain flags are specified when then host creates the session. Consult the MSDN. The Receive function has similar syntax to the Send function. The only different thing worth mentioning is the third parameter. Instead of the sending parameter, it is a receiving parameter. Set that to 0 for the default value, meaning extract the first message and delete it from the queue. The whole difficult part about the receiving is that we need to cast the message to DPMSG_GENERIC and it gets messy there. So I give you the function and explain it below. void Receive_Mesg() { DPID idFrom, idTo; // id of player from and to LPVOID lpvMsgBuffer = NULL; // pointer to receiving buffer DWORD dwMsgBufferSize; // sizeof above buffer HRESULT hr; // temp result DWORD count = 0; // temp count of message // get number of message in the queue lpdp->GetMessageCount(local_player_id , &count); if (count == 0) // if no messages return; // do nothing do // read all messages in queue { do // loop until a single message is read successfully { idFrom = 0; // init var idTo = 0; // get size of buffer required hr = lpdp->Receive(&idFrom, &idTo, 0, lpvMsgBuffer, &dwMsgBufferSize); if (hr == DPERR_BUFFERTOOSMALL) { if (lpvMsgBuffer) // free old mem GlobalFreePtr(lpvMsgBuffer); // allocate new mem lpvMsgBuffer = GlobalAllocPtr(GHND, dwMsgBufferSize); } // end if (hr ==DPERR_BUFFERTOOSMALL) } while(hr == DPERR_BUFFERTOOSMALL); // message is received in buffer if (SUCCEEDED(hr) && (dwMsgBufferSize >= sizeof(DPMSG_GENERIC) { if (idFrom == DPID_SYSMSG) // if system mesg Handle_System_Message((LPDPMSG_GENERIC)lpvMsgBuffer, dwMsgBuffersize, idFrom, idTo); else // else must be application message Handle_Appl_Message((LPDPMSG_GENERIC)lpvMsgBuffer, dwMsgBufferSize,idFrom,idTo); } } while (SUCCEEDED(hr)); if (lpvMsgBuffer) // free mem GlobalFreePtr(lpvMsgBuffer); } // end void Receive_Mesg()First we check if there are any messages in the loop. If not, we break out of this function. We then keep trying to receive the message in the buffer by allocating the new buffer. When the return value is not DPERR_BUFFERTOOSMALL, it means either we have received the message or another serious error has occurred. So we check if the hresult is successful before determining whether it is a system or application message, by which we call the appropriate functions. System messages come from DPID_SYSMSG, which is a reserved value in DirectPlay. The 2 functions should be implemented as follows: int Handle_System_Message(LPDPMSG_GENERIC lpMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo) { switch(lpMsg->dwType) { case DPSYS_SESSIONLOST: { // inform user // PostQuitMessage(0) } break; case DPSYS_HOST: { // inform user } break; case DPSYS_CREATEPLAYERORGROUP: // a new player { // cast to get message LPDPMSG_CREATEPLAYERORGROUP lp = (LPDPMSG_CREATEPLAYERORGROUP)lpMsg; // inform user a new player has arrived // name of this new player is lp->dpnName.lpszShortNameA } break; case DPSYS_DESTROYPLAYERORGROUP: // a lost player { // cast to get message LPDPMSG_DESTROYPLAYERORGROUP lp = (LPDPMSG_DESTROYPLAYERORGROUP)lpMsg; // inform user a player has left // name of this new player is lp->dpnName.lpszShortNameA } break; default: // an uncaptured message. Error here } // end switch return(1); // success } // end int Handle_System_Message(..) int Handle_Appl_Message(LPDPMSG_GENERIC lpMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo) { switch(lpMsg->dwType) { case DP_MSG_CHATSTRING: { // cast to get the message we defined DP_STRING_MSG_PTR lp = (DP_STRING_MGS_PTR)lpMsg; if (gameServer) // if server, relay the message to all players { lpdp->Send(local_player_id,DPID_ALLPLAYERS, DPSEND_GUARANTEED, lp, dwMsgSize); } // update your chat window } break; default: // unknown application message, bad } // end switch return(1); // success } // end int Handle_Appl_Message(..)The two functions are very similar. To get the actual message, we need to cast the message to the appropriate type before extracting the individual components. Even if the application message comes through, we need to cast it get the data within. The dwType parameter we defined in the chat string struct above enables us to differentiate the different messages the application defines. Although the chat requires only one message, which is the chat message, there is definitely a need for more messages types the application should handle. Every new message type you define should include a dwType parameter so the application can differentiate the messages. Putting it Together Now you know how it should be implemented, I will piece the various parts together (in WinMain) // Get information from local player // Connection creation if (gameServer) Create_TCP_Connection(""); else Create_TCP_Connection(tcp_address); // Session part if (gameServer) // if host // open connection else // if client { // EnumSessions // Open connection } // Player creation if (gameServer) // set flags to create serverplayer // set flags to DPID_SERVERPLAYER // create local player while(1) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE) { if (msg.message == WM_QUIT) break; // translate and dispatch message } // end if PeekMessage(..) else { // Your game loop Receive_Mesg(); } // end else } // end of while(1) // close session DirectPlay_Shutdown();The reason I do not have a sample application to show is because the interface code would be as long as all this code and it would require another tutorial as long as this to explain how to do interface. However if you really do not know how to do a chat interface, I recommend looking at the control EDIT in the MSDN. For simplicity, the chat window can be implemented as a multi-line edit. Anyway I hope this makes DirectPlay clearer and the documentation makes more sense.
http://www.gamedev.net/page/resources/_/technical/directx-and-xna/a-directplay-tutorial-r764
CC-MAIN-2016-40
refinedweb
5,592
54.63
This is a Java Program to check whether a point lies inside, outside or on the circle. For any point t (xt, yt) on the plane, its position with respect to the circle defined by 3 points (x1, y1) , (x2, y2), (x3, y3). s = (x-xt)^2 + (y-yt)^2 – r*r If s < 0, t lies inside the circle; if s > 0, t lies outside the circle; if s = 0, t lies on the circle. s = (x-xt)^2 + (y-yt)^2 – r*r If s < 0, t lies inside the circle; if s > 0, t lies outside the circle; if s = 0, t lies on the circle. Here is the source code of the Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Plane. The Java program is successfully compiled and run on a Windows system. The program output is also shown below. //This is a java program to check whether point d lies inside or outside the circle defined by a, b, c points import java.util.Random; import java.util.Scanner; public class Position_Point_WRT_Circle { public static void main(String args[]) { Random random = new Random(); int x1, y1, x2, y2, x3, y3; double m1, m2, c1, c2, r; x1 = random.nextInt(10); y1 = random.nextInt(10); x2 = random.nextInt(10); y2 = random.nextInt(10); x3 = random.nextInt(10); y3 = random.nextInt(10); m1 = (y1 - y2) / (x1 - x2); m2 = (y3 - y2) / (x3 - x2); c1 = ((m1 * m2 * (y3 - y1)) + (m1 * (x2 + x3)) - (m2 * (x1 + x2))) / (2 * (m1 - m2)); c2 = ((((x1 + x2) / 2) - c1) / (-1 * m1)) + ((y1 + y2) / 2); r = Math.sqrt(((x3 - c1) * (x3 - c1)) + ((y3 - c2) * (y3 - c2))); System.out.println("The points on the circle are: (" + x1 + ", " + y1 + "), (" + x2 + ", " + y2 + "), (" + x3 + ", " + y3 + ")"); System.out.println("The center of the circle is (" + c1 + ", " + c2 + ") and radius is " + r); System.out.println("Enter the point : <x>,<y>"); Scanner scan = new Scanner(System.in); int x, y; x = scan.nextInt(); y = scan.nextInt(); double s = ((x - c1) * (x - c1)) + ((y - c2) * (y - c1)) - (r * r); if (s < 0) System.out.println("The point lies inside the circle"); else if (s > 0) System.out.println("The point lies outside the circle"); else System.out.println("The point lies on the circle"); scan.close(); } } Output: $ javac Position_Point_WRT_Circle.java $ java Position_Point_WRT_Circle The points on the circle are: (5, 9), (4, 7), (2, 0) The center of the circle is (34.5, 23.25) and radius is 39.960136386153636 Enter the point : <x>,<y> 3 5 The point lies inside the circle The points on the circle are: (0, 1), (2, 3), (5, 4) The center of the circle is (3.5, 4.5) and radius is 1.5811388300841898 Enter the point : <x>,<y> 1 2 The point lies outside the circle Sanfoundry Global Education & Learning Series – 1000 Java Programs. Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms. » Next Page - Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
http://www.sanfoundry.com/java-program-check-if-point-d-lies-inside-or-outside-circle-defined-points-a-b-c-plane/
CC-MAIN-2017-39
refinedweb
516
74.9
An Ellipse is defined by two points, each called a focus. If any point on the Ellipse is taken, the sum of the distances to the focus points is constant. The size of the Ellipse is determined by the sum of these two distances. The sum of these distances is equal to the length of the major axis (the longest diameter of the ellipse). A circle is, in fact, a special case of an Ellipse. An Ellipse has three properties which are− Centre − A point inside the Ellipse which is the midpoint of the line segment linking the two foci. The intersection of the major and minor axes. Major axis − The longest diameter of an ellipse. Minor axis − The shortest diameter of an ellipse. In JavaFX, an Ellipse is represented by a class named Ellipse. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create an Ellipse node in JavaFX. This class has 4 properties of the double datatype namely − centerX − The x coordinate of the center of the ellipse in pixels. centerY − The y coordinate of the center of the ellipse in pixels. radiusX − The width of the ellipse pixels. radiusY − The height of the ellipse pixels. To draw an ellipse, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, as shown below − Circle circle = new Circle(centerX, centerY, radiusX, radiusY); Or, by using their respective setter methods as follows − setCenterX(value); setCenterY(value); setRadiusX(value); setRadiusY(value); Follow the steps given below to draw an Ellipse an Ellipse in JavaFX by instantiating the class named Ellipse which belongs to a package javafx.scene.shape. You can instantiate this class as follows. //Creating an Ellipse object Ellipse ellipse = new Ellipse(); Specify the x, y coordinates of the center of the Ellipse → the width of the Ellipse along x axis and y axis (major and minor axises), of the circle by setting the properties X, Y, RadiusX and RadiusY. This can be done by using their respective setter methods as shown in the following code block. ellipse.setCenterX(300.0f); ellipse.setCenterY(150.0f); ellipse.setRadiusX(150.0f); ellipse.setRadiusY(75.0f); In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Ellipse (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as shown in the following code block − Group root = new Group(ellipse); step an Ellipse using JavaFX. Save this code in a file with the name EllipseExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Ellipse; public class EllipseExample extends Application { @Override public void start(Stage stage) { //Drawing an ellipse Ellipse ellipse = new Ellipse(); //Setting the properties of the ellipse ellipse.setCenterX(300.0f); ellipse.setCenterY(150.0f); ellipse.setRadiusX(150.0f); ellipse.setRadiusY(75.0f); //Creating a Group object Group root = new Group(ellipse); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing an Ellipse"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac EllipseExample.java java EllipseExample On executing, the above program generates a JavaFX window displaying an ellipse as shown below.
https://www.tutorialspoint.com/javafx/2dshapes_ellipse.htm
CC-MAIN-2019-35
refinedweb
607
55.13
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} module Control.Concurrent.STM.TChan.Class where import qualified Control.Concurrent.STM.TChan as C import Control.Concurrent.STM -- | A class capturing Chan operations in STM. class SplitTChan i o | i -> o, o -> i where -- | Write a value to the in chan. writeTChan :: i a -> a -> STM () -- | Read the next value from the out chan. readTChan :: o a -> STM a -- | Get the next value from the @TChan@ without removing it, -- retrying if the channel is empty. peekTChan :: o a -> STM a -- | A version of 'peekTChan' which does not retry. Instead it -- returns @Nothing@ if no value is available. tryPeekTChan :: o a -> STM (Maybe a) -- | A version of 'readTChan' which does not retry. Instead it -- returns @Nothing@ if no value is available. tryReadTChan :: o a -> STM (Maybe a) -- |Returns 'True' if the supplied 'TChan' is empty. isEmptyTChan :: o a -> STM Bool -- | A class for 'SplitTChan' types that can be instantiated without programmer -- input. /e.g./ the standard haskell @TChan@ is a member of this class, however -- a bounded chan type that took an @Int@ to define the buffer size would not. class (SplitTChan i o)=> NewSplitTChan i o where newSplitTChan :: STM (i a, o a) -- instances -- -- one-bounded chan: instance SplitTChan TMVar TMVar where readTChan = takeTMVar writeTChan = putTMVar peekTChan = readTMVar tryReadTChan = tryTakeTMVar tryPeekTChan = tryReadTMVar isEmptyTChan = isEmptyTMVar instance SplitTChan C.TChan C.TChan where writeTChan = C.writeTChan readTChan = C.readTChan peekTChan = C.peekTChan tryReadTChan = C.tryReadTChan tryPeekTChan = C.tryPeekTChan isEmptyTChan = C.isEmptyTChan instance NewSplitTChan TMVar TMVar where newSplitTChan = do v <- newEmptyTMVar return (v,v) instance NewSplitTChan TChan TChan where newSplitTChan = do v <- C.newTChan return (v,v)
http://hackage.haskell.org/package/chan-split-0.5.0/docs/src/Control-Concurrent-STM-TChan-Class.html
CC-MAIN-2014-42
refinedweb
268
69.07
This tutorial explains Bubble Sort algorithm with an example showing multiple iterations of the algorithm. It then shows how to implement bubble sort in Java and explains the code. What is Bubble Sort: Bubble Sort, considered by many to be the simplest of sorts, works by progressively in-place sorting(ie. not using up extra space while sorting) a list of items by moving the lowest valued item to the to the top or largest valued item to the bottom(for an ascending sort). It keeps lining bigger and bigger elements below the earlier smaller ones. In this way the whole array gets sorted. You can see a whiteboard animation video explanation of how bubble sort works and get a code walk-through in this YouTube video Bubble Sort’s working in detail -Lets say our list to be sorted is [1000, 1, 100, 101, 15].As per bubble sort, we will move progressively the largest valued items to the bottom/end of the list. First Pass of Bubble Sort Algorithm Lets start with the first pass from left to right in the list [1000, 1, 100, 101, 15]. The various comparisons that happen in the first pass are – - 1000 is compared to 1. As 1000>1 it is swapped. The list is now [1,1000,100,101,15]. - 1000 is now compared with 100. As 1000 > 100 the two items are swapped. The list now is [1,100,1000,101,15] - 1000 is now compared with 101. As 1000 > 101 they are swapped. The list now is [1,100,101,1000,15] - 1000 is now compared wiuth 15. As 1000>15 they are swapped. The list now is [1,100,101,15,1000] The first pass is now complete. Note that the largest element in the list(1000) has bubbled to the rightmost and correct place. List at the end of the first pass is [1,100,101,15,1000]. Second Pass We again start from left and move to the right – - 1 is compared with 100. As 1 < 100 nothing is done. List remains [1,100,101,15,1000] - 100 is now compared with 101. As 100 < 101 nothing is done. List remains the same. - 101 is now compared with 15. As 101 > 15 they are swapped. The list now is [1,100,15,101,1000]. The second pass ends at this point as the last element(1000) was already marked as greatest in the first pass. The second-last element(101) is the second largest at the end of the second pass now. List at the end of the second pass is [1,100,15,101,1000]. Further Passes Similar to the first and second pass, passes keep bubbling up largest elements to the right while the size of the unsorted list keeps reducing. After exactly n-1 passes the list is considered to be sorted as all the elements are now in their correct position. package com.javabrahman.algorithms.sorts; public class BubbleSort { static int intArray[] = { 1000, 1, 100, 101, 15 }; public static void doSort() { for (int outer = 0; outer < intArray.length; outer++) { for (int inner = 0; inner < intArray.length - outer- 1; inner++) { if (intArray[inner] > intArray[inner + 1]) { int temp = intArray[inner]; intArray[inner] = intArray[inner + 1]; intArray[inner + 1] = temp; }/ to length – 1 times. ie. 1 less than the number of items times. - The loop with the counter innerrepresents the sorted element being moved/bubbled forward. It continues from 0to length-outer-1times. This is because the size of the unsorted part of the array keeps reducing in exact correlation with the number of passes completed i.e number of elements sorted and put in their correct place. - The main()method orchestrates the sorting. - The instance element intArray[]holds the list to be sorted.
https://www.javabrahman.com/algorithms-in-java/bubble-sort-in-java/
CC-MAIN-2018-34
refinedweb
630
75.3
Polymorphism in Expression trees While trying to be extra-clever today, I found a potential nasty issue when dealing with strongly-typed reflection. Suppose I have a simple hierarchy of objects: public abstract class Base { public abstract string Foo { get; } } public class Child : Base { public override string Foo { get { return "asdf"; } } } An abstract base class and a child class that implements the one abstract member. Suppose now we want to do some strongly-typed reflection with the child type: [Test] public void PolymorphicWeirdness() { Expression<Func<Child, object>> func = child => child.Foo; var body = (MemberExpression) func.Body; body.Member.DeclaringType.ShouldEqual(typeof (Child)); } Many frameworks, AutoMapper being one of them, take advantage of this strongly-typed reflection to get to MemberInfo information on the property or method used in the expression. Unfortunately, the above test fails. Instead of the MemberInfo’s DeclaringType being “Child”, it’s “Base”. If I’m using Expressions to do things like interrogate the MemberInfo for things like custom attributes, I won’t be getting the whole story here. Lots of other OSS tools use Expressions quite a bit, so I’m very curious to see what those tools do with this behavior. Note, it’s only the Expression tree with the polymorphism issue. Once you compile the Expression, all of the normal CLR resolution rules are applied. This seems like someone would have written about this issue by now, so I’m off to do some sleuthing to see how others deal with this.
https://lostechies.com/jimmybogard/2009/02/25/polymorphism-in-expression-trees/
CC-MAIN-2018-26
refinedweb
248
52.09
Hello everyone OS : Windows 10 / XP PsychoPy version: 1.84.1 Standard Standalone? (y/n) yes What are you trying to achieve?: I am trying to setting up an fMRI experiment. For this, I want the routine to start, when the MRI scanner starts to send TR pulses. The MRI pulses will be received by the parallel port. What did you try to make it work?: I created a routine with following code component. Begin experiment: from psychopy import parallel parallel.setPortAddress(address=0xCFE9) globalClock = core.Clock() wait_msg="waiting for scanner…" msg = visual.TextStim(win, color=‘DarkGray’, text=wait_msg) Begin routine: msg.draw() win.flip() while True: if parallel.readPin(13) == 1: break globalClock.reset() logging.exp('parallel trigger: start of scan') win.flip() # blank the screen on first sync pulse received The parallel port address is also configured in the settings. What specifically went wrong when you tried that?: When I run the experiment I get this error message: return PORT.readPin(pinNumber) AttributeError: ‘NoneType’ object has no attribute ‘readPin’ What did I miss? I hope this is enough information to help me with this problem. I would be really happy for any advice so that I can run my fMRI experiment with no problems. Thanks!!
https://discourse.psychopy.org/t/mri-experiment-start-routine-by-mri-pulse-from-parallel-port/1135
CC-MAIN-2021-39
refinedweb
207
54.08
this library provides support to construct graphs and their coloring graphs. a coloring graph is a metagraph representing all the valid colorings of a graph. each vertex of a coloring graph represents a coloring of the base graph. Project description libcolgraph libcolgraph homepage on the web a coloring graphs library written in C++ for speedy computation and wrapped in Python for ease of development and extension! what this library provides support to construct graphs, their coloring graphs, and biconnected component metagraphs. a coloring graph is a graph representing all the valid colorings of a graph. each vertex of a coloring graph represents a coloring of the base graph. two colorings are considered adjacent if they differ in only one vertex's color. in this project, we represent a coloring as an integer, which, when converted to base k (for a k-coloring), is a number of length |V| and represents the vertex-wise colors [0,k) for each vertex. the library is under development, being written using Python and C/C++. the web application uses the library to provide useful GUI for quick drawing and graph construction. in the future, we plan to develop a supplemental subsection of the library containing useful graph algorithms and ability to run simulations to test structural graph theoretic conjectures about graph coloring and coloring graphs. for documentation, feel free to take a look inside libcolgraph/ and read the docstrings. for questions, reach out. screenshot of the web GUI [Clockwise] A 7 vertex BaseGraph that is a hexagon with a central vertex and a missing 'spoke' leads to a quite complex ColoringGraph with k=4 colors. You can see the formation of polyps at the edges. The structure of the resultant ColoringGraph is shown in the Meta ColoringGraph produced by a run of modified Tarjan's algorithm for biconnected components. The central 'mothership' can be seen, adjacent to which there are cut vertices, and finally the stray singular coloring vertices at the tips of polyps. for a static demo, go to the project's gitlab pages. usage as a module plot a BaseGraph, its ColoringGraph, and the Meta ColoringGraph generated by Tarjans. you would need to have a graph formatted in an adjacency matrix file. opens plots in new browser windows. launch web GUI: libcolgraph.web [-h] [-i INPUT_FILE] [-n] [-s] [-k COLORS] [-v] [-p PORT] [-w] [-r] [-d] [-t] optional arguments: -h, --help show this help message and exit -i INPUT_FILE, --input-file INPUT_FILE read in BaseGraph from adjacency matrix file -n, --new open a blank canvas? -s, --select_file open file choosing gui dialogue? -k COLORS, --colors COLORS number of colors to use to create ColoringGraph -v, --verbosity set output verbosity -p PORT, --port PORT port to launch GUI on -w, --webbrowser open app in default web browser window? -r, --render_on_launch render to-generate componenets on initial launch? -d, --debug launch Flask app in debug mode? -t, --threaded allow multiple threads? as a library import libcolgraph bg = libcolgraph.BaseGraph() bg.load_txt('./in/hexmod.in') cg = bg.build_coloring_graph(4) print('bg {} led to a cg {}'.format(bg, cg)) for v in cg.get_vertices(): print(v) installation for installation from source refer to detailed install instructions python3 -m pip install libcolgraph [--upgrade] things to note: - currently a binary wheel is available only for manylinuxdistributions e.g. centOS, Debian family, RedHat family, etc. - if your distribution is not manylinux-supported, then pip will need to compile locally using swigand setuptools. in that case, make sure you have setuptoolsand swig installed, as they will be needed for compilation. - we periodically release wheels for MacOS as well. these might not be as frequently maintained, however, so your best bet would be to compile locally using swig. contribute visit full API documentation who Coloring Graphs lab, University of Richmond. (C) 2017-2020 Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/libcolgraph/
CC-MAIN-2021-21
refinedweb
661
56.15
User talk:Joto/How to invent tags Hi Jochen, there are still a few pages that deal with this topic: But I absolutely agree that this needs to be more centered on one single page and the community has to make clear how to add new features or change existing features --!i! 10:11, 1 November 2010 (UTC) - Thanks. I added the first link because it also talks directly about the same thing I am talking about. Because you already added the "Tagging guidelines" category to the page, I probably don't need to add all those links that will show up when people look at the category page. --Joto 08:04, 3 November 2010 (UTC) Abbreviations, acronyms This is one point you could add. It's already enough complicated for non-native english speakers to use english tags (even through editors presets). We should really try to avoid abbreviations like 'atm' (too late now), 'ngo' or 'aed'. --Pieren 10:33, 2 November 2010 (UTC) - Good suggestion. There was already a sentence about abbreviations in there, but I made it clearer by promoting it to have its own heading and I added acronyms. --Joto 08:04, 3 November 2010 (UTC) Hi Jochen, don't you want to "publish" the article How to invent tags? I mean to move it to the root namespace. I would like to translate it to Czech language. Thanks, Dalibor Chrabros (talk) 09:00, 8 March 2017 (UTC)
https://wiki.openstreetmap.org/wiki/User_talk:Joto/How_to_invent_tags
CC-MAIN-2018-09
refinedweb
242
70.33
You need to create the Proxy class when you want to consume a web service as described in the article How to consume a web service in ASP.NET. The first option is described in the article How to create the proxy class with wsdl command-line tool in ASP.NET. As a second option, you can create the Proxy class by adding a web reference in the client project in Visual Studio 2010. Web references point to a web service with a WSDL contract. In this case you should follow the next steps: 1. Right-click the client project in the Solution Explorer, and select Add Service Reference. Then press buttons Advanced and Add Web Reference. Add Service Refence dialog box Service Reference Settings dialog box 2. The Add Web Reference dialog box opens, as shown next. This window provides options for searching web registries or entering a URL directly. It also has a link that allows you to browse all the web services on the local computer or search a UDDI registry. The Add Web Reference dialog box 3. You can browse directly to your web service by entering a URL which points to the .asmx file. The test page appears in the window as shown next, and the Add Reference button is enabled. Adding a web reference 4. In the Web Reference Name text box you can change the namespace in which the proxy class is generated. 5. To add the reference to this web service, click Add Reference at the bottom of the window. 6. The web reference appears in the Web References group for your project in the Solution Explorer window. Important notes 1. You need to update your proxy class by right clicking the web reference and choosing Update Web reference if web service us changed. Web references aren’t updated automatically when you recompile the application. 2. When you are developing and testing a web service in Visual Studio, it’s often easiest to add both the web service and the client application to the same solution. This allows you to test and change both pieces at the same time. To choose which application you want Visual Studio to launch when you click Start, right-click the appropriate project name in the Solution Explorer and select Set As StartUp Project. When you add a web reference, Visual Studio saves a copy of the WSDL document in your project: 1. In a web application, Visual Studio creates the App_WebReferences folder (if it doesn’t already exist) and then creates a folder inside it with the web reference name (which you chose in the Add Web Reference dialog box). Finally, Visual Studio places the web service files in that folder. However, Visual Studio doesn’t generate the proxy class. Instead, it’s built and cached as part of the ASP.NET compilation process. This is a change in the behavior from ASP.NET 1.x. 2. In any other type of application, Visual Studio creates a WebReferences folder and then creates a folder inside it with the web reference name. Inside that folder it places all the support files you see in a web application (most important is a copy of the WSDL document). It also creates a file named Reference.cs (assuming it’s a C# application) with the proxy class source code. By default, this class is hidden from view. To see it, select Project ➤Show All Files. Categories Top © 2018 HowToASP.NET - All Rights Reserved. Last Updated 10/15/2018 | About Us | Privacy | Terms | Write for UsAll trademarks are property of their legal owners.
http://www.howtoasp.net/asp-net-tutorials/how-to-create-the-proxy-class-with-visual-studio-in-asp-net/
CC-MAIN-2018-43
refinedweb
602
65.12
User Account Control on Windows Vista provides a convenience feature which allows you to elevate a process without leaving the current desktop. (For a discussion of why this is a convenience feature, rather than a security feature, see Mark Russinovich's blog entry here:). Let's explore this at a fairly high level. To simplify things, let's assume you are running as an administrator with UAC enabled (although, to be more secure, it is better to run as a standard user). When you log in, you create a new token. We then detect that you have UAC enabled, we log in a second time, and end up with a new (highly restricted) token, which we use to launch the shell. There are two separate login events. When you are prompted to elevate, you go through consent.exe, which is able to leverage the Application Information service to essentially call CreateProcessAsUser with the fully-charged admin token. Remember - we are calling CreateProcessAsUser with a token generated with a separate login. This convenience feature makes it easier to run into issues with mapped network drives. Prior to Windows 2000 SP2, device names remained globally visible until explicitly removed or the system restarted. For security reasons, we modified this behavior beginning with Windows 2000 SP2. From this point forward, all devices are associated with an authentication ID (LUID) - CreateProcessAsUser, but UAC dramatically increases the number of users who will be using these concepts.) The result? If you elevate a command prompt, you will no longer see any local namespace mapped drives created from your original login (whether created through a logon script, WNetAddConnection, or otherwise). We do put a mitigation in place for the scenario of launching from the shell. If you double click on an executable that is either detected as a setup or is manifested as requireAdministrator, we can detect that we just elevated and suddenly are getting an error message indicating that the path was not found, and copy that drive mapping over from the original LUID. However, that is the only scenario that we can automate. So, if you need to leverage mapped drives from an elevated process, you should be certain to map these drives in the contect of the elevated login. you can set this value and you will get access to those drives from both integrity levels. UAC team is working on a KB, and I will have a post on this before too long. Last time around, we looked at an application compatibility side-effect of User Account Control on Windows So how does MS expect us to change our logon scripts to work by mapping network drives? Shouldn’t there be some documentation on how to do this appropriately. I did try the Launchapp.wsf on the TechNet article but errors out with a syntax error just launching the script. I have tried the registry key EnableLinkedConnections and it works. However you can’t make a startup script edit the registry to deploy such a change. It seems this is a catch 22 situation. Does anybody else know how to make this work? What is the error you are seeing? I assume you are talking about the article at ? I cannot get the EnableLinkedConnections to work. Anyone else successful? I have a variation on this behaviour. If the user is a standard user the log on script works fine and maps the drives. However, if I add the user to the local admin group the mappings fail to appear. You must reboot after you set the new DWORD. I map network drive in elevated contect, however, if after this I start a DOS window also in elevated contect, I CANNOT see any of the mapped drives. However, if I start DOS windows in non-elevated mode, it’s ok. Why is this so inconsistent? Mapped drives are associated with a logon session, as mentioned before. It’s not just elevated or non-elevated, but each time you log in. We just happen to have two different logon events when creating the split token we use in Vista. If you’re seeing the drives in a non-elevated command shell (DOS is long gone, but I know what you mean), then the mapped drives must have been created from that logon session, and not from the session from which your elevated token came. How are you mapping these drives, and from what application? I have also been unsuccessful with utilizing the EnableLinkedConnections = 1 registry fix. I have rebooted as well. It just doesn’t work for me. On a side note, before applying this fix, if I opened a command prompt under the limited token, my drives show (net use) and are available. If I opened an elevated command prompt, the drives are listed, however they are all marked "unavailable", thus inaccessible as well. This functionality existed before and after the registry fix above. Any thoughts on how to get this to work?! The registry key is not supported. I’d re-run the script to map your drives after you elevate, or else use UNC paths instead of mapped drives. In ref. to If the user is NOT an administrator on the Vista computer to which they are logging, the standard drive mapping script (XP) works; but the launchapp approach does not. If they ARE an administrator, then the standard mapping script fails; but the launchapp approach works. Steve.Darnall I guess we are seeing similar issue when we execute our setup program from a network mapped drive in explorer but don’t see that drive in our setup program (InstallShield 12). Any solution or workaround for us to try out? We should be catching and detecting the launch of the setup program and then mapping that over so you can execute after you elevate. What exactly are you doing in the setup that isn’t seeing this? I’m not familiar with all of the versions of InstallShield out there. Are you creating an MSI? Is this a custom action? How are you retrieving the mapped drive? What are you then trying to do with it? Chris, We’re porting a legacy app that uses Wise Install System. Our app uses mapped drives; it can’t use UNC. I, too, am having trouble getting mapped drives to be visible to the Wise Installer. Whether (as we prefer so we avoid your scanning a 100mb file) I use a tiny Setup.exe stub marked as RequiresAdmin which simply shells to the Wise-created .exe, or just run the Wise .exe standalone, no mapped drives are seen by the installer. As a developer, I’m running as an admin. I believe that EnableLinkedConnections is necessary for me to see the mapped drives. But as a standard user, I’ve yet to be able to see them from the elevated Wise installer, even if it’s launched from the Explorer. In the past we’ve had users map drives in the Windows Explorer and then run our installer and then our app. But it appears that there are additional steps required here? I’m not sure what steps are required, or how to make them straight-forward for our end-users. Any help? Thanks. Tom (across Lake Washington in Seattle) Hi Tom, If you have a setup.exe stub, why not just map the drives in the elevated login session from the stub before launching the installer? Thanks, Chris Hi, Chris, Thanks for the suggestion. My stub is running elevated to admin. Are you suggesting that somehow it can detect what drives the standard user had mapped, and then do the mapping again? Or do I need two stubs: the first runs **without** elevation, a makes a list (say, to the registry) of the mapped drives, then shells out to stub #2, which asks for elevation to admin, reads the registry list and re-maps the drives. Sounds kinda Rube Goldberg-like to me! I’m not familiar with what API functions are available for reading and creating mapping. Can you point me in the right direction? (I’m in Delphi…) I REALLY appreciate your help on this. Hi tfield98 (Tom?), No, I wouldn’t go about trying to figure out what you have from non-elevated and then marshall that data across and re-create them elevated. Too much work. 🙂 The drives are being mapped in the non-elevated context somehow. Just find that source, and run it again – only elevated. To answer the API question, WNetAddConnection3 can be used to create mapped network drives. Thanks, Chris Hi, Chris, I’ve got the code working now. It was a combination of using EnableLinkedConnections and making sure that drives mapped as a standard user were also mapped when elevated to an admin user. I REALLY appreciate your having taken the time. Thanks again!!!! Tom (tfield98!) I have a .wsf file on a server. It is called from an HTA also on the same server. The user logs in as their username not administrator. Each user also has local admin privileges. The .hta runs fine but I get a permission denied error when I try to run the .wsf file. All works fine in XP. Problems occur using Vista. Is this related to the discussion here? mike_wilson@dell.com So, if you need to leverage mapped drives from an elevated process, you should be certain to map these drives in the contect of the elevated login. But when the machine is restarted, the mapped network drive lost the elevated token, I mean, the drive which was mapped in the context of the elevated login, after reboot a elevated process can not see it, for example a setup.exe (which require an Admin token). or am I doing something wrong? By the way, can I do this (modify the Windows Registry) HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem EnableLinkedConnections =(dword)1 without lost the Vista logo? Mike Wilson – that sounds like UAC, scripts can’t be set up to elevate. You may want to check this out: IJ – I’m not a logo expert. You should try not to depend on this. You should prefer UNC to mapped drives, however, anyplace you can. I know this post is about Vista, but some of the side comments lead me to believe you might have an answer to this question. On Windows XP I’m using LogonUser, LoadUserProfile, ImpersonateLoggedOnUser, then finally CreateProcessAsUser to have a process running as a service start user applications running in console mode. They appear to run correctly under the logged on username, but the user’s mapped network drives all appear as unavailable (for example, start a .BAT file that has a "net use" command, and the output shows the mapped drive letters and paths but all have a status of "Unavailable"). Is this a known limitation, or should there be a way for me to get around this and use the user’s mapped drive letters? Thanks. Mike- You’re facing the same issue on XP that I’m describing on Windows Vista. The call to LogonUser creates a new logon session. Mapped drives are stored with each logon session, so you don’t have them. What you want to do is re-use the same logon session. Both COM and scheduled tasks allow you to use the credentials of the interactive user, so I’d probably explore these options. HTH, Chris
https://blogs.msdn.microsoft.com/cjacks/2007/02/19/mapped-network-drives-with-uac-on-windows-vista/
CC-MAIN-2019-13
refinedweb
1,903
64.91
Lesson 7 - LINQ in C# - Revolution in querying In the previous lesson, Queue and stack in C# .NET, we talked about queues and stacks. In today's tutorial, we're going to introduce the revolutionary LINQ technology. LINQ refers to a set of tools for querying data which simplifies and generalizes working with any sort of data. Motivation We've all worked with different kinds of collections and used them in different ways. We look for an element in an array in a different way than when we read data from an XML file and when we search for a user in a database. Now, imagine if there was a unified way to query data. In other words, to be able to run the same query on both ordinary arrays and on an XML file or a database. As you may have guessed, LINQ provides us this functionality. This is an enormous abstraction whose only toll is an insignificant amount of performance reduction. This technology brought programming in C# to new heights. LINQ as a language LINQ is a rather extensive and sophisticated technology. Its name is an acronym for Language INtegrated Query. As the name suggests, it's a query language that is integrated directly into the C# language syntax. It's a part of the language since C# 3.0 and the .NET Framework since version 3.5. On newer versions, it even runs on multiple threads which increases its efficiency. LINQ is very similar to the SQL language, so it's a declarative language. We tell the program what we're looking for and we let it work its magic. The advantage to LINQ's integration into C# is the syntax checking during compile time. Let's make a small example before we go any further. Create a new project (a console application), and name it LINQ. Let's create a simple array of strings. string[] names = {"David", "Martin", "Daniel", "Peter", "John", "Elisa"}; Now, using a LINQ query, we'll select the array items whose lengths are greater than 5 letters. Add the following code to the program: var query = from n in names where (n.Length > 5) select n; The query looks a lot like SQL, those who know it have a leg up on everyone else. I bet none of you have ever called an SQL query on an array, have you? We'll go over what the query is doing in a bit, but first, let's finish our program by having it print the query result to the console: {CSHARP_CONSOLE} string[] names = {"David", "Martin", "Daniel", "Peter", "John", "Elisa"}; var query = from n in names where (n.Length > 5) select n; // printing the result foreach (string name in query) { Console.WriteLine(name); } Console.ReadKey(); {/CSHARP_CONSOLE} The program's output: Console application Martin Daniel What the query looks like Let's return to our query, which looked like this: var query = from n in names where (n.Length > 5) select n; SQL programmers will surely be surprised to see that the query is backwards. There is a reason behind this, which we'll get into later. First, we specify where we want to select the data using the from keyword. From is followed by a variable that will represent an item from the collection for the rest of the query. Then, the in keyword follows along with the collection. It works sort of like the foreach loop. We write queries on multiple lines to keep things clear. This is especially important for more complex queries. To add a condition, all you have to do is add a line with the where keyword, followed by the condition. We write conditions in the same way as we did before. On the last line, we have a select keyword which we use to determine the values that we want to select. In the example above, we select all of the elements in the collection, i.e. n. However, this way, we're only able to select things like lengths using n. For example, n.Length. The var keyword We store the query into a variable of the var type, which is new to us. In fact, it's not even a data type. The var keyword allows us to leave the data type choice up to the compiler. Meaning that C# will determine what the data type should be automatically when compiling it. Theoretically, we could use var in other cases. For example: var s = "C# will recognize that this is a string and it will assign the string type to the variable s"; var i = 10; The above code will be translated to this: string s = "C# will recognize that this is a string and it will assign the string type to the variable s"; int i = 10; In other words, var allows to determine the data type at compile time and saves us from having to specify it. In ordinary programs, using var would be rather confusing, since providing data types makes sense. With that in mind, we'll set data types as we're used to. Don't substitute all data types with the var keyword as some amateurs do. Var was introduced along with LINQ due to three reasons. First, the data types in LINQ queries are rather complex, so it'd be complicated to specify them explicitly every time. Second of all, if we change the collection type, we would also have to change the query type, which would require us to edit the code and the technology wouldn't be all that universal. Third of all, anonymous types come with LINQ, and we need var to be able to store them. We'll get to them soon. What you need to know is that var has its place in queries and shouldn't be used in regular code (even though it could be used there theoretically). Generally, it's best to only use var if it simplifies the declaration and it's still clear of which type the variable is. Let's make four examples with and without using var: int a = 10; List<Dictionary<string, string>> dictionaries = new List<Dictionary<string, string>>(); IOrderedQueryable<Uzivatel> fromNY = from u in db.Users where u.City == "New York" orderby u.Name select u; int b = a; We can modify the code using var like this: var a = 10; var dictionaries = new List<Dictionary<string, string>>(); var fromNY = from u in db.Users where u.City == "New York" orderby u.Name select u; int b = a; Var doesn't help us much with the first variable. However, using it with the generic list for generic dictionaries is correct since we can still say from the right side of the assignment of which type the dictionaries variable is. Either way, it'd be much more clear to write a separate class instead. Storing collections in collections is not a good practice. As for the LINQ query, the data type is complex. If we removed the orderby clause, the type would change to IQueryable<User>. Using var, we don't have to worry about the data type nor change to fit the query. The last var is a rather deterrent example, since we have no way of telling which data type the b variable is. Another common mistake is that people think that var declares a variable of a dynamic type, therefore, they'd be able to store whatever they want in it. This isn't true, the type is strictly assigned at compile time and cannot be changed afterward. With that in mind, you should be able to understand why the code below won't work: // this code will not work var variable = "It contains text now"; variable = 10; // Now it contains a number The program above creates a variable of the string type and then shows an error because the code tried to assign an int to a string data type. Under the hood How does it all work? If you look at the beginning of your source code, you will see that it contains the following: using System.Linq; This bit of code is prepared by default for all types of projects. Let's see what happens if we comment it out. As soon as you do, Visual Studio will underline the variable names in the query from our previous example. LINQ works using providers. There are several types of providers and you can even define your own. Next, we'll use LINQ to Objects, which is implemented in the System.Linq namespace and extends the regular collections such as List and Array with some more methods. In other words, it uses extension methods. Now, let's (keep that last bit commented out) invoke the VS list of methods on our array. Write name. (name and a dot), so we can see them: Now, uncomment the line and do the same thing once again: There are suddenly lots of new method for an ordinary array. When C# performs a LINQ query, it calls these collection methods on the background. We use lambda expressions within them, which we've already gone over in the OOP course. Our query: {CSHARP_CONSOLE} string[] names = {"David", "Martin", "Daniel", "Peter", "John", "Elisa"}; var query = from n in names where (n.Length > 5) select n; // printing the result foreach (string name in query) { Console.WriteLine(name); } Console.ReadKey(); {/CSHARP_CONSOLE} This query is translated by C# to the following: var query = names.Where(n => n.Length > 5).Select(n => n); You can test that the query actually works the same. We can work with LINQ like this as well, but using an SQL-like notation is much nicer. Either way, we've just explained why we added a where before the select in the query. The data must be found using the where() method before we map the result as we need it using the select() method. The reason being the method order called internally from the LINQ technology. Last of all, we'll reveal what that mysterious var type represents in our example. The final type for the query on our array is: System.Linq.Enumerable.WhereArrayIterator<string> Since we can't know what type a LINQ query will return (more precisely, we should be relieved from that), the var type was introduced, as mentioned above. Next time, LINQ providers, anonymous types, grouping and sorting in C#, we'll continue with more queries. Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily. DownloadBy downloading the following file, you agree to the license terms Downloaded 3x (145.45 kB) Application includes source codes in language C# No one has commented yet - be the first!
https://www.ictdemy.com/csharp/collections-and-linq/linq-in-csharp-revolution-in-querying
CC-MAIN-2021-31
refinedweb
1,797
72.26
Comparing Closures in Java, Groovy and Scala Comparing Closures in Java, Groovy and Scala Join the DZone community and get the full member experience.Join For Free. Why those languages? Because they are the three JVM languages I'm most interested in. I suppose I could also have compared the closure support in Jython, JRuby or... well, there are a few to choose from, but this blog is going to be plenty long enough with just three. Let's start with the Java example that was given, remembering that this is a proposed syntax, that may or may not make it to Java 7 or later. As I understood the example it was this: imagine you want to add the ability to time a block of code, and you wanted to do it in a way that would look almost like a new keyword has been added to the language; and you wanted to pass in a parameter to name what you were timing; and the block you're timing returns a result, or might throw an exception. So, quite an involved case. BGGA Proposed Syntax Here's how the current Java proposal looks: // Here's a method that uses the time call: int f() throws MyException { time("opName", {=> // some statements that can throw MyException }); time("opName", {=> return ...compute result...; }); } So we're timing a couple of operations, and we're doing this inside a method, f, that returns an integer. The implementation would be.... interface Block<R, throws X> { R execute() throws X; } public <R, throws X> R time( String opName, Block<R, X> block) throws X { long startTime = System.nanoTime(); boolean success = true; try { return block.execute(); } catch (final Throwable ex) { success = false; throw ex; } finally { recordTiming( "opName", System.nanoTime() - startTime, success); } } As you can see, time takes an arbitrary text label and a block of code, runs the block and tells you how long the block took to run and if it succeeded or not. That's the example that was given at JavaOne. Now for the same thing in Groovy... Same example in Groovy To make runnable code for Groovy (and for Scala), I had to decided to time something. So I'm timing a block of code that randomly throws an exception or returns something. And then timing a block of code that just returns a number. In Groovy that would be: def time(opname, block) { long start_time = System.nanoTime() boolean success = true try { return block() } catch (Throwable ex) { success = false; throw ex } finally { diff = System.nanoTime() - start_time println "$opname $diff $success" } } int f() throws Exception { time("a") { Random r = new Random() if (r.nextInt(100) > 50) throw new IOException("Boom") else return 42 } time("b") { return 7 } } println f() An example of running the code, showing one run where no exception was thrown, and operation "a" and "b" where both successfully and took a certain amount of time.... $ groovy time.groovy a 37116000 true b 69000 true 7 ...and an example where an exception was thrown when timing operation "a": $ groovy time.groovy a 39998000 false Caught: java.io.IOException: Boom at time$_f_closure1.doCall(time.groovy:21) at time$_f_closure1.doCall(time.groovy) at time.time(time.groovy:6) at time.f(time.groovy:18) at time.run(time.groovy:31) at time.main(time.groovy) Note that the Java example is typed in that it uses a generic type, R, for the return value which gives you some compile-time checks. That is, when you run time() and use the result, the compiler will enforce that your declaration of the result has the same type as the return type of the block you're timing. Although Groovy does support generics, I've not used them here, and as a result the Groovy example doesn't have that type-safety. I think that's the way one would typically write Groovy code. Same example in Scala Now a look at the same code in Scala: def time[R](opname: String)(block: => R) = { val start_time = System.nanoTime() var success = true try { block } catch { case ex: Throwable => { success = false; throw ex } } finally { val diff = System.nanoTime() - start_time println(opname + " " + diff + " "+success) } } def f():Integer = { val answer = time("a") { val r = new Random() if (r.nextInt(100) > 50) throw new java.io.IOException("Boom") else "42" } println ("the answer, "+answer+" is of type "+ answer.getClass()) val seven:Integer = time("b") { 7 } println ("seven is of type "+seven.getClass()) return seven } f() I'm still not using Scala day-to-day, so this might be a little awkward: thank you to the London Scala User Group for helping me clean up my syntax, but all the mistakes are mine. This code has the same properties as the Java code (type safety via the R generic type), but seems a little shorter and neater. Additionally, the thing I like about the Scala code (and the Groovy code) is that the languages return the value of the last statement in a block, and that the syntax allows a clean time("thing") { ... } format. One observation: I've used the Integer class, which is deprecated, in order to be able to print out the class of the return types in the function f(). Without the :Integer declaration I was getting weird compile errors. As I said, my understanding of Scala and type inference isn't there yet. The output from running the code: a 913000 true the answer, 42 is of type class java.lang.String b 13000 true seven is of type class java.lang.Integer ...and an example where the method threw an exception: a 936000 false java.io.IOException: Boom at Main$$anonfun$1.apply((virtual file):26) at Main$$anonfun$1.apply((virtual file):23) at Main$.time$1((virtual file):8) at Main$.f$1((virtual file):23) at Main$.main((virtual file):44) at Main.main((virtual file)) // rest of stack trace removed Conclusions There's no conclusions here. It's just an exercise in comparing closures code in three different languages. I've probably missed some of the nuances of the Java example, but hey... it's a starting point. Original Blog Post: Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/comparing-closures-java-groovy
CC-MAIN-2019-18
refinedweb
1,049
65.22
Creating Your Own NuGet Package Introduction NuGet is a free and open source package management system for .NET applications. The primary goal of NuGet is to help developers simplify the process of incorporating third party libraries into their .NET applications. There are several NuGet packages available for you to use or you can build your own. This step-by-step article shows what it takes to create your own NuGet package. The package can then be submitted to NuGet Gallery or can be hosted locally. Creating a Library That Will Go as a Package Before you create any NuGet package you will need to create and assemble all the pieces that go as a package. As an example, you will bundle a .NET class library and its help file into a package. So, begin by creating a class library project in Visual Studio 2010. Name the project NuGetPkgLib. The class library will have a single class named TemperatureConverter that converts temperatures from Celsius to Fahrenheit and vice versa. The TemperatureConverter class is shown below: namespace NuGetPkgLib { public class TemperatureConverter { public decimal ToFahrenheit(decimal t) { return (t * 1.8m) + 32; } public decimal ToCelsius(decimal t) { return (t - 32) / 1.8m; } } } Creating a NuSpec File In order to create a NuGet package you need to create an XML file containing metadata of the package. This file is referred as NuSpec file and has an extension of .nuspec. Though you can create a NuSpec file manually from scratch, here you will use the NuGet.exe command line tool for that purpose. The NuGet command line tool can produce the NuSpec file with basic XML markup that you can modify as per your requirements. You can download the NuGet Command Line here. Once you download NuGet.exe in a well-known location of your machine (say C:\NuGet) you can run the tool as follows: NuGet.exe spec Running NuGet command line tool with spec option generates a new NuSpec file with basic XML markup. You can, of course, modify the markup to suit your needs. If you run the above command in a folder where your class library project file (.csproj) resides, then the generated NuSpec file will assume the same name as the class library project (NuGetPkgLib.nuspec); otherwise the NuSpec file will have name Package.nuspec. In any case the NuSpec file contains certain XML tags. The meaning of these tags is given in the following table. Now open the newly created .nucpec file in Visual Studio or Notepad and modify it as shown below: <?xml version="1.0" encoding="utf-8" ?> <package> <metadata schemaVersion="2"> <id>TemperatureConverter</id> <version>1.0.0.0</version> <authors>Bipin Joshi</authors> <description> TemperatureConverter helps you convert temperatures from Celsius to Fahrenheit and vice a versa. </description> <projectUrl></projectUrl> <licenseUrl></licenseUrl> <requireLicenseAcceptance>true</requireLicenseAcceptance> <tags>Temperature Celsius Fahrenheit</tags> <iconUrl>C:\Bipin\NuGetPkgLib\NuGetPkgIcon.png</iconUrl> </metadata> </package> All the information mentioned above appears in the "Manage NuGet Packages" option of Visual Studio 2010. The following figure shows the "Manage NuGet Packages" dialog with NuGetPkgLib package selected. Figure 1: The "Manage NuGet Packages" dialog with NuGetPkgLib package selected Notice how all the information is displayed in the main area (center of the dialog) and information pane (right side). The XML markup tags shown in the above table are just the basic ones. The complete reference of available tags can be read from NuGet website. It would be worthwhile to note a couple of XML tags that you may need frequently in addition to the ones mentioned above. Your package might be dependent on some .NET framework assemblies such that referring those assemblies in the client project is mandatory. You can automatically add reference to .NET framework assemblies when the client installs your package by adding the following markup: <frameworkAssemblies> <frameworkAssembly assemblyName="System.Drawing" /> </frameworkAssemblies> As you can see, the <frameworkAssemblies> section includes one or more assembly references (System.Drawing in this case). When a NuGet package is installed, references to these assemblies are automatically added. At times you may want to explicitly specify the files to be included in the package. In such cases you can use <files> section as shown below: <files> <file src="bin\debug\NuGetPkgLib.dll" target="lib" /> <file src="help\Overview.htm" target="help" /> </files> In the above example only NuGetPkgLib.dll and Overview.htm files will be copied to the target folder after the package is installed. Build the Package Now that your NuSpec file is ready, let's build the package based on it. Go in the folder where the NuGetPkgLib.nuspec file resides and execute the following command: NuGet.exe pack The NuGet command line tool will then read the .nuspec file and generate a NuGet package file having the extension .nupkg. You can also specify the .nuspec file name explicitly as follows: NuGet.exe pack NuGetPkgLib.nuspec Publish the Package Once you build a NuGet package you are ready to publish it. If you wish to make the package available to the world then you need to publish it into NuGet Gallery. For the sake of this article, however, you will publish the package locally so that you can use it in your projects. First of all, create a folder on your machine and name it as NuGetPkg. Copy the .nupkg file generated earlier to this folder. Now, open Visual Studio and locate Tools > Options menu item. Locate Package Manager Options and select Package Sources. Figure 2: Package Manager Options Add a new package source with name My Packages and folder NuGetPkg (or whatever you named it at your end). Adding a new package source will enable Visual Studio to search and locate your local packages. Install the Package Now that you have added a package source let's use the package in a client application. Create a new Console Application and name it as NuGetPkgClient. Right click on the project in the Solution Explorer and select "Manage NuGet Packages". Doing so will open a dialog as shown below: Figure 3: NuGetPkgClient - Manage NuGet Packages Select My Packages under Installed Packages and you should see the TemperatureConverter package you created earlier. Click on the Install button so as to install the package and associated files. The following figure shows how the TemperatureConverter.dll assembly is added to the client application. Figure 4: How the TemperatureConverter.dll assembly is added to the client application Notice how reference is automatically added to NuGetPkgLib and System.Drawing (since we specified it in NuSpec file) assemblies. Summary Creating your own NuGet package involves creating a NuSpec file, building a package based on the metadata of NuSpec file and then publishing the package. A NuSpec file is an XML file that can be generated using the NuGet command line tool - NuGet.exe - and contains metadata of the package. The metadata of a package includes its Id, description, version, authors, licensing URL, project URL, tags, referenced assemblies and files. Based on the NuSpec file a package can be built using the NuGet command line tool. The package thus created can be hosted in the NuGet Gallery for global consumption or it can be hosted locally. Publishing package as a nuget feed in VSOPosted by Mayuri on 10/05/2016 11:21am Hi, Your article above is very helpful in creating your own nuget packages and making them available to other projects. But followed these steps for my project but I want my package to be published as a nuget package feed on VSO. I have created a feed in VSO but how can I link my package to it? will be very grateful if you could provide some help. ThanksReply
https://www.codeguru.com/csharp/article.php/c19247/Creating-Your-Own-NuGet-Package.htm
CC-MAIN-2019-13
refinedweb
1,278
57.67
NOTE: if you plan to use it, see better plugin bellow - Code: Select all from math import * from random import * import sublime, sublimeplugin class MiniPyCommand(sublimeplugin.TextCommand): def run(self, view, args): script = "" for region in view.sel(): script = view.substr(region) view.replace(region, str(eval(script))) def isEnabled(self, view, args): return True and binding: - Code: Select all <binding key="ctrl+e" command="miniPy"/> so, just ctrl+e on a selected text, and tada! THANKS EJ12N !!! anyway, i write this here because of my limited python knowledge. i thought it would be really nice if i could do something like: - Code: Select all $x=0 $x++ $x++ ... or - Code: Select all $x = "a." $x".my_class" etc. any idea how to implement it? if at all? to be clear i want use variables which will be alive on this mini program, i chose to mark it with $ but that just an idea ideas/help will be appreciated vim.
http://www.sublimetext.com/forum/viewtopic.php?p=1762
CC-MAIN-2015-14
refinedweb
159
74.08
BYTE STREAMS in Java – File Reading and Writing Example using Byte Streams Performing input and output operations using a Byte Stream is one of the most common and the low level input output operation that a java program can perform. In this data is processed(read/write) in the form of a byte or we can use buffered approach for more structured fast and convenient input output operations. Click here to read Stream basics before continuing with Byte Streams In Byte Streams all the classes are the descendents of 2 abstract classes- InputStreamfor input operation. OutputStreamfor output operation. And the 2 most important methods in all the classes that are used for I/O operations are- public int read() throws IOException– It reads a byte from Stream. public void write(int i) throws IOException– it writes the specified byte into the Stream. Now lets have a look at Some Important classes for Byte Streams File Reading and Writing Example using Byte Streams - To show you the use of Byte Streams here in this example I will take image as an input file so that it could be clear that Byte Streams can be used for all types of files( except Strings or text files) but ensure that the file is in classpath or provide a fully qualified pathname of the file. - Also we are using Java 7 feature named try with resourcesin which we are declaring and Initializing both the Streams along with try and we don’t need to close them explicitly but ensure that every resource you initialize inside try should implement AutoClosable interface. package codingeekExamples; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class ByteStreamsExample { public static void main(String[] args) throws IOException { try ( // Declaring and initializing both the Streams inside try so that there // is no need to close them. You can do this with many other classes but // make sure that they all implements the Closable Interface InputStream inputStream = new FileInputStream("input.jpg"); OutputStream outputStream = new FileOutputStream("output.jpg") ) { Integer c; //continue reading till the end of the file while ((c = inputStream.read()) != -1) { //writes to the output Stream outputStream.write(c); } } } } -> In the beginning I said that this is a low level operation and it should be avoided if you can because this program spends a lot of time in looping i.e reading from input stream and writing to output stream and these operations are really costly. So what is the need of Byte Streams? These are of utter importance as all other Streams are basically based upon Byte Stream only and it could be used for all kind of data like images, files, networking operations etc. BUT still there are some cases where we don’t use Byte Streams and prefer to use specialized Streams for that purpose like for reading and writing text files. Where Byte Streams should not be used? We should not use Byte Stream for the Streams that represent the character data i.e. for the input output operations of text data. It is because For example if the file uses UNICODE system of encoding than each character will be denoted by two Bytes but Byte Stream will treat them differently and you have to handle the case using some programming logic. Such Streams are known as Character Streams and we use specialized classes for this purpose, Example – BufferedReader, InputStreamReader, FileReader etc. Resources:- Oracle Byte Streams
http://www.codingeek.com/java/io/read-and-write-file-using-byte-streams-in-java-example/
CC-MAIN-2017-04
refinedweb
581
60.55
Python alternatives for PHP functions import os content = os.listdir('/some/dir/') #example for filename in os.listdir('/some/dir/'): print filename (PHP 4, PHP 5) readdir — Read entry from directory handle Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem. The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed. Returns the filename on success, or FALSE on failure. This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.);}?>
http://www.php2python.com/wiki/function.readdir/
CC-MAIN-2017-51
refinedweb
131
58.89
I am looking to add social sharing into our applications but cannot figure out how to access the sharing API from Qt/QML. The sharing UI feature is documented here: The key differentiator is that any app or service could handle the share request. The MeeGo open source project hosts the sharing libraries here: I have tried to adapt some of the examples in the git repository, but they all rely on importing ShareUI ie #include <ShareUI/Item> which I cannot resolve. I can see that the SharingUI libs are built into the SDK on this path: <Qt SDK Root>/Madde/sysroots/harmattan-arm-sysroot/usr/include/ShareUI but I do not see the ShareUI dir in the same location on the N950. Any advice on this would be most appreciated. Thanks, Maciej
http://developer.nokia.com/community/discussion/showthread.php/226370-Accessing-ShareUI-on-Harmattan-MeeGo?p=850571&viewfull=1
CC-MAIN-2014-23
refinedweb
133
54.97
A Gentle Introduction to TypeScript Talk given at Fullstack Talks (NC San Diego) - 02/2o/2020 This information has been updated since the talk (mostly extra info added, some grammar/spelling errors corrected). Who am I? - Principal Software Engineer at Peachjar - 3/4 Stack Developer (or Pear-shaped Developer) - Former Marine Corps Meteorologist - Virgo - Foodie - Reluctant TypeScript Zealot Peachjar's History w/ TypeScript - Hired at Peachjar, told it would be our primary language for our new stack. - No one had professional experience with TypeScript - I started learning TypeScript 2 weeks before I joined PJ. - We went from 0 lines of TS to 4 React/Apps, ~30 microservices, and 3 internal service frameworks (it will be 2 years in April). - We are now starting to codify our CI pipelines in TS (using Github Actions). Mike made feel insecure about my level of TS knowledge, so I show you this to prove how much we use TS. 😞😞😞 Roadmap - Compilation and Running TypeScript - Basic TypeScript - Intermediate TypeScript - Why TypeScript: Myths, Advantages, and Disadvantages of TypeScript - Code from Live Demo Compilation and Running TypeScript # Install globally or into a project npm i -g typescript # Create a file with the ".ts" extension echo 'console.log("Hello");' > index.ts # Compile using the "tsc" command tsc index.ts # The file will be compiled in the same dir ls > index.js index.ts # Run the "compiled" file node index.js # You can also "skip" the compilation step and directly # with ts-node (but this is slow) npm i -g ts-node ts-node index.ts There are a ton of ways to configure the TS build process (like generate source maps, push code to a build directory, etc.). Most teams will develop conventions around how they build and run TS projects. NOTE: during the blooper reel that was my live demo, you saw that the standard configuration of TS does not include the ES2017 features. You will need a tsconfig.json file to enable that feature. Basic TypeScript - Primitives - Arrays - Tuples - Objects - Type Aliases - Enums null, undefined, any - Functions Primitives: // When you initialize a variable without a type, // the compiler will give it the most restrictive type // based on the value. const foo = 'bar' const foo: string = 'bar' const bar = 1 const bar: number = 1 const yomama = true const yomama: boolean = true let isReassignable = true isReassignable = false isReassignable = 'no' // compile error (type is boolean) Arrays (homogenous - items of the same type) const sodas = ['pepsi', 'coke'] const sodas: string[] = ['pepsi', 'coke'] // More complex: const bucket = [1, 'hello', true] // Any element in the array can be a number, string, or boolean const bucket = (number | 'string' | boolean)[] = [1, 'hello', true] Tuples (heterogeneous - items of specific types) If not familiar, it's a "finite ordered list (sequence) of elements" (Wikipedia). const latlon: [number, number] = [33.123456, -116.134123] const wind: [string, number, number] = ['SW', 10, 15] Objects const options = { username: 'foo', password: 'bar', timeout: 1000, } const options: { username: string; password: string; timeout: number } = { username: 'foo', password: 'bar', timeout: 1000, } ^ this is ugly, right? Type Aliases type BucketItem = number | 'string' | boolean type Bucket = BucketItem[] const bucket: Bucket = [1, 'hello', true] type LatLon = [number, number] const latlon: LatLon = [33.123456, -116.134123] type Options = { username: string password: string timeout: number } const options: Options = { username: 'foo', password: 'bar', timeout: 1000, } Type Aliases of Primitives lead to better clarity type int = number type milliseconds = int type Options = { username: string password: string timeout: milliseconds } But we can even do better with type restrictions type knots = int type Direction = 'N' | 'NE' | 'E' | 'SE' | 'S' | 'SW' | 'W' | 'NW' type SustainedSpeed = knots type GustSpeed = knots type WindMeasurement = [Direction, SustainedSpeed, GustSpeed] const wind: WindMeasurement = ['SW', 10, 15] Unfortunately, types are inaccessible at runtime console.log(Direction) // compile error // This is true of any type const gust: GustSpeed = 25 const isGust = typeof gust === 'GustSpeed' // false A better strategy for "enumerated" values is an enum enum Direction { North = 'N', NorthEast = 'NE', East = 'E', SouthEast = 'SE', South = 'S', SouthWest = 'SW', West = 'W', NorthWest = 'NW', } // Under the hood, enums are just objects: console.log(Object.keys(Direction)) // I use this aspect with validation: import * as Joi from 'joi' const DirectionSchema = Joi.string() .valid(Object.values(Direction)) .required() const { error } = Joi.validate('SW', DirectionSchema) null let foo = null foo = 'bar' // compile error // If we want something to be null or something else, we have to declare // the type that way: let foo = string | null = null foo = 'bar' undefined type Options = { foo: string | undefined bar: number } const options: Options = { bar: 1234, } const options: Options = { foo: 'baz', bar: 1234, } TypeScript will enforce checks of null and undefined properties before use const options: Options = { bar: 1234, } // compile error (null | string) not compatible with type "string" const foo: string = options.foo // But you can tell the compile you know better: const foo: string = options.foo! // ^ but here's the gotcha - YOU DIDN'T KNOW BETTER! // This works because we checked for the existence of "foo" const foo = options.foo ? options.foo : 'unknown' "Optional Chain" Operator type Link = { id: number, to: Link | undefined | null, from: Link | undefined | null, } const head: Link = { id: 1 } const link2: Link = { id: 2, from: head } head.to = link2 const link3: Link = { id: 3, from: link2 } link2.to = link3 const link4: Link = { id: 4, from: link3 } link3.to = link4 const fourDeep = head.to?.to?.to // Should be link 4 // undefined const wayBack = link4.from?.from?.from?.from?.from?.from?.from?.from any (try not to use any) // the value can be anything (welcome back to JS) let foo: any foo = {} foo = 'yeah' foo = 123 We will come back to "any" in a little bit functions function addTwo(num: number): number { return num + 2 } const addTwo = (num: number): number => num + 2 // Since functions can be passed, they also can have type definitions: const addTwo: (num: number) => number = function addTwo(num: number): number { return num + 2 } const addTwo: (num: number) => number = (num: number): number => num + 2 // In general, I recommend using type definitions for clarity: type AddTwo = (num: number) => number const addTwo: AddTwo = (num: number): number => num + 2 void (indicate no return value) function printHello(name: string): void { console.log(`Hello: ${name}`) } function printHello(name: string): void { console.log(`Hello: ${name}`) return } In some cases any is great for succinct functions (but bad for indicating intent) function purchaseCart(cart: Cart): any { if (cart.items.length === 0) { return console.log('No items in cart!') } // return nothing sendPurchaseToCheckout(cart) } never (rarely used, but you should be aware of it) function sendPurchaseToCheckout(cart: Cart): never { throw new NotImplementedError() } variadic arguments function printGreeting(greeting: string, ...names: string[]) { for (const name of names) { console.log(`${greeting} ${name}$`) } } printGreeting('Hello', 'Richard', 'Brandee', 'Aurora', 'Sophia') Intermediate TypeScript - Classes - Interfaces - Generics Classes (yey, OOP!) class Foo { yo: string mama: number constructor(yo: string, mama: number) { this.yo = yo this.mama = mama } get yoMama(): string { return `yo: ${this.yo}, mama: ${this.mama}` } } Inheritance works just like you would think: class Bar extends Foo { constructor() { super(yo, mama) } printMama(): void { console.log(this.mama) } } Simplified visibility and property setting class Foo { constructor(public yo: string, public mama: number) {} } class Foo { constructor(protected yo: string, private mama: number) {} protected bar() {} // methods can be set like any other property in JS. private alwaysTrue = () => true } Interfaces interface Notifier { myField: string notify(userId: string, message: string): void } class ConsoleNotifier implements Notifier { myField = 'foo' notify(userId: string, message: string): void { console.log(`Hey ${userId}, ${message}`) } } Function Interfaces interface notify { (userId: string, message: string): void } const consoleNotify: notify = (userId: string, message: string): void => console.log(`Hey ${userId}, ${message}`) // One thing I have not mentioned yet is that a lot of times // you can leave off the param/return types if TS is told // what type a "thing" is supposed to be. const consoleNotify: notify = (userId, message) => console.log(`Hey ${userId}, ${message}`) Duck Typing interface notify { (userId: string, message: string): void } function doThingAndNotify(notify: notify): void { // do'in it notify() } // console.log is able to meet the type requirement, therefore // the compiler "considers" it to have "implemented" the interface doThingAndNotify(console.log) Types vs Interfaces There are not many practical differences between interfaces and types. - Interfaces can be extends - Interfaces can be explicitly 'implemented' - Types cannot be redeclared in the same context; if interfaces are redeclared, their properties are merged. type Foo = string type Foo = string // compile error interface Bar { prop1: string } interface Bar { prop2: string } Advanced TypeScript (sorry, not today) - Symbols - Advanced Generics - Modules - Namespaces - Decorators Why TypeScript? Myths about TS: - Types will increase the complexity of my codebase (you already have a ton of hidden complexity that you don't know about.) - Types will force me to use OOP (you can be 100% functional, and I would argue you will get closer to categorical compositions because of types [e.g. monads, etc]. I will say, if you are familiar with Java and .NET, TS will be easier). - I won't be able to use pure JavaScript libraries (you can create type definitions for external libs) - Err me gerd, not another CoffeeScript/Flow/whatever (fair - but I think TS has far greater traction). - TS code will be unusable in pure JavaScript (TS is just JS). - TS is going to dramatically slow development (I think its the opposite, really). - Unit tests are enough - I don't need TS! (oh boy, wait until you see the holes in your code.) - TS is all I need - No more unit tests! (oh boy, wait until you see the holes in your code.) Benefits of TypeScript - Greater clarity in what your code ACTUALLY does. - Ability to model abstract concepts divorced from implementations (which JS does not support). - Intuitive type system (it doesn't feel like writing Java code in JavaScript). - Compile time checks to catch obvious errors. - All the great futuristic JS features (now!) - Fantastic ecosystem (actually, I would say TS type definitions are the de facto standard for new libs). - Awesome IDE support (better than JavaScript). - A reduction in the need for JSDocs (code documentation) -- you should strive for greater code clarity (make it a game - how can my code be so obvious that the type system alone is all I need to describe the functionality). Drawbacks of TypeScript - No runtime introspection of types (the type system doesn't exist after compilation). - Complex types (with generics) can sometimes be confusing - Having to create type definitions for plain JS libraries can be a sad process. Demo Code: Setup npm init npm i -S typescript axios mkdir src touch src/index.ts cp ~/.../tsconfig.json . tsconfig.json { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": ["dom", "es2017", "esnext.asynciterable" ], "declaration": true, "sourceMap": true, "outDir": "./dist/", "rootDir": "./src", "strict": true, "esModuleInterop": true } } Add Build Step to package.json { // ... "scripts": { "build": "rm -rf dist && ./node_modules/.bin/tsc --pretty", }, // ... } src/index.ts import Axios from 'axios' const hollaApiUrl = "<holla-api>" async function main(): Promise<void> { const { data } = await Axios.get(`${hollaApiUrl}/say/hi-fullstackers`) console.log(data) } main() Compile and Run npm run build node dist/index.js Output Not pretty with the HTML entities, but it works! Mark actually created a version that rendered beautifully on the command line, but I don't have the URL to the new instance of the service in ECS. Conclusion - Demonstrated Basic and Intermediate Usage of TS - Discussed Strengths and Weakness of TS Stumbling my way through the great wastelands of enterprise software development.
https://rclayton.silvrback.com/a-gentle-introduction-to-typescript
CC-MAIN-2020-40
refinedweb
1,875
51.78
Gröbner Bases and Optics Ge $ \int dx’ G(x,x’)$. In geometrical optics, which was Huygens original intent I think (these old school guys were VERY geometrical), this is the curious operation of taking the geometrical envelope of the little waves produced by each point. The gist of Huygens principles. Ripped from wikipedia Taking the envelope of a family of lines. Ripped from wikipedia You can describe a geometrical wavefront implicitly with an equations $ \phi(x,y) = 0$. Maybe the wavefront is a circle, or a line, or some wacky shape. The wavelet produced by the point x,y after a time t is described implicitly by $ d(\vec{x},\vec{x’})^2 - t^2 = (x-x’)^2 + (y-y’)^2 - t^2 = 0$. $ \phi$ from sympy import * x1, y1, x2, y2, dx, dy = symbols('x1, y1, x2, y2, dx, dy') def dist(x,y,d): return x**2 + y**2 - d**2 e1 = dist(x1,y1,2) # the original circle of radius 2 e2 = dist(x1-x2 ,y1 - y2 , 1) # the parametrized wavefront after time 1 # The two envelope conditions. e3 = diff(e1,x1)*dx + diff(e1,y1)*1 e4 = diff(e2,x1)*dx + diff(e2,y1)*1 envelope = groebner([e1,e2,e3,e4], y1, x1, dx, dy, x2, y2, order='lex')[-1] plot_implicit(e1, show=False) plot_implicit(envelope, show = True). Original circle radius = 2 x12 + y12 - 4 = 0 Evolved circles found via grobner basis. (x22 + y22 - 9)*(x22 + y22 - 1) = 0 Here’s a different one of a parabola using e1 = y1 - x1 + x1**2 Original curve y1 - x1 + x1**2 = 0 After 1 time step. 16x26 - 48*x25 + 16x24y2**2 + 32x24y2 + 4x24 - 32x2**3y22 - 64x23*y2 + 72*x23 + 32x22y2**3 + 48x22y2 - 40x22 - 32x2y23 + 16x2y22 - 16x2y2 - 4x2 + 16y24 + 32y23 - 20*y22 - 36y
https://www.philipzucker.com/grobner-bases-and-optics/
CC-MAIN-2021-39
refinedweb
294
68.6
This is the mail archive of the archer@sourceware.org mailing list for the Archer project. Chris> Just FYI, this patch breaks a handful of existing tests: Chris> gdb.base/setvar.exp Chris> gdb.cp/classes.exp Chris> gdb.cp/m-data.exp Chris> gdb.cp/m-static.exp Chris> cp/namespace.exp Chris> gdb.mi/mi-var-display.exp Chris> gdb.python/py-value.exp Yeah. Chris> None of them are hard to fix in the expects--I just wanted The World Chris> to realise that there are going to be noticeable consequences to this Chris> fairly minor nicety. It'll take me a bit to fix the t/cs--if The Chris> Powers That Be would rather this patch not proceed, I'd appreciate it Chris> if you'd let me know sooner rather than later and spare me all the Chris> fix-up work. Usually you just have to do it and see what happens. Even if we all agree on a format here, someone else might disagree on gdb-patches, or they might think of some new reason for it to be different. I, personally, want some form of this change, because every time I type "p FOO" and get "$1 = FOO", I think, grrr, gdb could have told me what I really wanted to know. If enough people dislike it we can always add 'set print blah blah'. Tom
http://sourceware.org/ml/archer/2010-q1/msg00066.html
CC-MAIN-2014-42
refinedweb
234
74.9
Apart from being unhappy about the performance, it's been a very unstable/shacky start for me (June 2003) to get it all working. Overall, the installation of NEMO now works, but I always seem to need some tinkering, which appears to depend on the OS patch level.... My new system (baught June 2004!) fared a little better, no doubt 10.3 is better than 10.2 (and I've also been spoiled too much with Solaris and Linux....). Don't even get me started on this inferior Aqua. By now i feel Gnome has surpassed it in capabilities. At least out of the box, i'll say that. There are tons of tools to make Aqua more useful, but take out your credit card and/or be ready to babysit some downloading, installation and disk "optimizing"! /usr/lib/crt1.o definition of _NXArgc in section (__DATA,__data) /usr/lib/crt1.o definition of _NXArgc in section (__DATA,__data)this seems to depend on the version of autoconf, 2.57 is ok, 2.59 - which comes with mac - does not [this was done with gcc-3.3 (build 1809) on os-x 10.4.5 where the default compiler was actually 4.0.0 (build 4061) - but this version cannot compile gyrfalcON] % cd $NEMO/usr/dehnen/falcON % edit Makefile -shared => -flat_namespace -bundle -undefined suppress (see also $NEMOBIN/ldso; not sure if we can even use shared libs since their official extension is .dylib, not .so) % edit make/defs -rdynamic : remove it, this flag is not needed on mac -rpath : remove it, this flag cannot be used on mac (or: make sure you use STATIC compile only) -lg2c => -lgfortran : but only if you wind up using gcc4 % make -i CXX=g++-3.3 nemo_bins some executables might fail to compile... but gyrfalcON works And performance? Well, nothing is for free. So far i get just a tad (10-20%) lower performance on a G4 vs. a P4 (at the same clock speed, given that most P4's run about 2-3 faster than a G4, well... to me that's a no brainer). If you normalize that by the price, we're 4-6 times off. If you have money, and energy to reprogram your code for altivec, or use dual processors, yes, go and make my day. But i still feel that the P4's are beating the G4's. G5? Come on, they only give you about 10-20% improvement at the same clock speed.... PS: yes. i'm a tad over-reacting. I spent just way too much money on this, and finding working software (despite fink) isn't as easy as i had hoped. gosh, it makes living with rpm's look easy now! PSPS: I'm also keeping some links on darwin as i'm learning more about this, as well as my miriad/MacOSX notes which sometimes remind me of tricks of the Mac trade. Many thanks to Gaurav Khanna, Mark Bellon and Nicolas Martin for their patience in guiding me through this new forest. 1. Download: (use tar or cvs, make sure you get the CVS/pgplot version, not the one via Caltech, it doesn't have the darwin config files) cvs -Q co nemo cd nemo (mkdir local; cd local; cvs -Q co pgplot) 2. Configure the system. Some G5 systems may have the IBM compiler, which can confuse configure. Setting these 3 environment variables will set them more reliably for the gnu compiler: setenv CC gcc setenv F77 g77 setenv CXX g++ ./configure --with-yapp=pgplot --with-pgplot-prefix=`pwd`/lib Check the output, notably if X11 was detected properly for pgplot. Also, consider running autoconf yourself to overwrite the configure script, but it currently breaks more things than it fixes. 3. Important: For MacOSX you now need to edit makedefs and NEMORC.gen (or NEMORC.local if it was already there) and rid them of any references to -lcrt1.o -lcrt2.o and/or -lcrtbegin.o in the FLIBS and YAPPLIB variable resp. (which ones you see seem to depend on the compiler version and/or phase of the moon): emacs NEMORC.gen makedefs Oddly enough one persons 10.3 is not another persons... My own phase of the moon was clean, i had to change nothing!! 4. Set the NEMO environment for user and programmer source nemo_start make postconfig source NEMORC.local Note that NEMORC.local is a copy of NEMORC.gen, so on MacOSX make sure there are no references to the .o files mentioned in item 3. If you edited NEMORC.gen the step before, you're ok. 5. Compile the pgplot library (inside $NEMOLIB) - there may be some fatal errors with complaints about undefined symbols like restFP and saveFP, but those won't have an impact on NEMO. make pgplot 6. Compile the NEMO library, it will silently do this and log the results in install.log make libs rehash 7. Now compile two sample routines to check if a simple and a more complex (graphics) program compile ok: mknemo tsf mknemo tabhist 8. If this is ok, continue to install the testsuite, if not, probably need to tinker with NEMORC.local (source it again) and/or $NEMOLIB/makedefs: src/scripts/testsuite -b There will be a few small errors still, to be resolved. 9. For MacOSX users who have an unpatched HFS+ filesystem, there could be a few duplicate files that were mapped on top of each other (the filecase bug), you'll have to figure this out yourself. I believe as of April 2004 NEMO is now clean of such duplicates.
http://bima.astro.umd.edu/nemo/macosx.html
crawl-001
refinedweb
936
74.79
Ruby Eye for the Java guy: Constants. java.lang.Integer.MAX_VALUE java.lang.String" MyClass::MY_VAR[1] = "z" puts MyClass::MY_VAR #=> "xzx" freeze class MyClass MY_VAR = "xxx" MY_VAR.freeze end puts MyClass::MY_VAR #=> "xxx" MyClass::MY_VAR = "yyy" #=> "warning: already initialized constant MY_VAR" MyClass::MY_VAR[1] = "z" #=> "in '[]=': can't modify frozen string (TypeError) module MyModule MY_VAR = "xxx" MY_VAR.freeze end MyConstants.freeze MyModule::MY_VAR = "YYY" #=> "can't modify frozen module (TypeError) class MyClass include MyConstants end MyClass::VAR = "qqq" MyClass::VAR[1] = 'r' puts MyClass::VAR #=> "qrq" module MyConstants VAR = "xxx" VAR.freeze end MyConstants.freeze class MyClass class Constants include MyConstants end Constants.freeze end puts MyClass::Constants::VAR #=> "xxx" A rack up with sketchup. Ruby script to toggle CVS root in a workspace file file. :pserver:username@extranet.foo.com:/cvs CVS/Root :pserver:username@intranet.foo.com:/cvs .cvsignore "Neutered Theme" for Java Studio Creator Update to PropertyResourceProvider There was a bug in the first version of the PropertyResourceProvider that I made available from this blog a few months ago (see DataProvider component for internationalizing Creator applications), which manifested itself in the glassfish application server. The order of two elements in the library's faces-config file was incorrect. I have fixed the bug and updated the complib available for download. You can download the updated PropertyResourceProvider Component Library here. (2006-12-13 15:07:06.0) Permalink NetBeans Free-Form Projects as Library Wrappers When the developer defines a library in NetBeans 5.x, the library definition is stored locally, in the user directory. This makes it difficult to share library definitions among more than one workspace. While library definitions are stored locally, references to them, in the form of entries in a project's properties file, are typically stored along with all other project files, in a remote code repository. When a user first fetches the project from the repository and opens it in NetBeans, a missing references error will occur. All missing local library definitions must be created anew in each local workspace. One solution to this problem is to store shared libraries in the remote workspace, and to make projects depend directly on the libraries' constituent JAR files. Such dependencies are stored in the project's properties file as relative paths to the JAR files, so assuming that the directory structure that includes both project and library remains the same in all users' workspaces, no local definitions are needed. There are however drawbacks to this solution. Under the Libraries node of the project logical view, only the JAR file name is displayed. If your project depends on a large number of libraries, it can be difficult to distinguish among them by file name alone. The names may by cryptic, or worse, there may be files in different directories that share the same name. There is also no way of determining from the project logical view that a group of JAR files form a logical unit, unless they share a common infix. As an example, consider the following project, in which one library provided JAR files aaa and bbb, and another library provided another JAR file, also named aaa: aaa bbb There is a hack that I have used to improve the quality of the information available about JAR files in the project logical view, which does not require use of the local storage. Instead of grouping them into library definitions, I add them to free-form projects. Projects may then be declared to depend on the library wrapper projects. Here is the same example, with the JAR files from the two libraries exported from two free-form library projects: How to create a free-form library wrapper project To create a free-form library wrapper project, start by putting all JAR files that belong together into a directory, which will serve as the project root directory. For this example, I will define two libraries, 01 and 02, the first containing two JAR files, aaa.jar and bbb.jar, and the second containing just one, aaa.jar: aaa.jar bbb.jar lib01/aaa.jar lib01/bbb.jar lib02/aaa.jar ./src build.xml <project name="01_Library_Wrapper" default="build" basedir="."> <target name="build"/> <target name="clean"/> </project> To create the project, from within NetBeans, choose File->New Project, and choose a "Java Project with Existing Ant Script" within the General category. In the next wizard panel, select as location the project's directory, e.g. ./lib01. NetBeans will fill in the build file information. You'll want to choose a short, but descriptive, project name, as this will be the name that appears under the Libraries node once you have declared a dependency on this library wrapper project. I chose the names "01 Library Wrapper Project" and "02 Library Wrapper Project". In the next, penultimate wizard panel, NetBeans will fill in the ant targets found, and in the final panel it will prompt you for a source directory. Choose the source directory that you created earlier. ./lib01 [It may seem superfluous to create an empty source directory and empty build targets, but I discovered that without these, some actions in the IDE can have the side effect of removing the exported JAR definintions.] After the project is created, bring up the project's properties window, and choose Output. Here you will declare the JARs that this free-form project exports. Select all the JARs that you put into the library wrapper project directory. When later you declare a dependency on this project, these are the JARs that will be added to the class path. Here is what this step looks like for my first library, 01: And that's it! Now you are ready to declare project dependencies on your new library wrapper projects. Right-click on the Libraries node in the project logical view, and choose "Add Project...". Select the project directory. All JARs in the project will be added as dependencies. (2006-12-04 22:47:43.0) Permalink DataProvider component for internationalizing Creator applications The JavaServer Faces standard JSP tag library includes the loadBundle tag, which allows the developer to bind component values to keys in a Java properties resource bundle. While Java Studio Creator includes this tag on the component palette, there is a lack of good design-time support for binding to keys in the resource bundle, and bound values cannot be displayed at design-time. There have been a lot of complaints in the developer forum about this, and it is something that the Creator development team intends to address in an upcoming release. loadBundle In the meantime, I have put together a simple DataProvider component, PropertyResourceProvider, which plays the same role, but has much better design-time support. How to install the PropertyResourceProvider Download the PropertyResourceProvider complib to a local directory. From within Creator, open up Tools -> Component Library Manager, and click on "Import". Use the browse feature to locate the downloaded component library, and select it. The library contains a single component, PropertyResourceProvider, which you can import into its own category, or into a pre-existing category. How to use the PropertyResourceProvider A PropertyResourceProvider wraps a Java resource bundle file, and makes the keys in the bundle file appear as data fields. In general, you should use one PropertyResourceProvider per resource bundle file. The component has a single property, baseName, which should contain the qualified base name of the resource bundle file. The property editor for the baseName property will show a list of all resource bundles available in the current scope, so you can just choose one from the list. If you aren't familiar with Java resource bundles, there is an SDN technical article that provides a good overview. baseName The overhead involved in creating a PropertyResourceProvider is minimal, so it is probably easiest to add them to each page on which they are needed. Localizable component values will need to be added to a resource bundle, instead of being set directly on the component. There are a number of ways of adding new keys to a resource bundle file. You can click on the file in the project view to edit it directly (look under the Source Packages node), or you open the file node and right click on a locale node to add key and value pairs, one by one. To bind a component to a localizable value, right-click on the component and choose "Bind to Data". Select the appropriate PropertyResourceProvider, and the keys currently defined in the resource file will appear as fields. Select a field, and Creator will set the property's value to an expression that binds to the selected field. Close the binding window, and you will see the property value appear in the designer. PropertyResourceProvide is just like any other DataProvider, so you can also edit property values in the component's properites sheet, or by choosing the "Property Bindings..." context menu item. The PropertyResourceProvider will automatically choose the correct bundle file to load based on the locale of the Faces context for each request. This locale is determined by examining the client locale of the incoming HTTP request, and the list of supported locales given in the application's faces-config file. Typically, adding a locale to a project involves two steps: <application> <locale-config> <default-locale>en</default-locale> <supported-locale>fr</supported-locale> <supported-locale>es</supported-locale> </locale-config> </application> Hope this helps! (2006-08-23 15:36:49.0) Permalink Rough Guide: Editing Themes for Creator 2.0 The components that ship with Java Studio Creator 2.0 derive their look and feel, and in some cases, their behavior, from a theme. At the most basic level, a theme is simply a JAR file that contains resources such as CSS stylesheets and graphical icons. An easy way to create your own look and feel is to edit the contents of the default Creator theme. The following guidelines explain how to do it. A theme JAR file has three main types of content: You'll find a copy of the default theme jar (defaulttheme.jar) in the Creator install directory, under rave2.0/modules/ext. Or, after you have deployed an application, in the application directory build/web/WEB-INF/lib. defaulttheme.jar rave2.0/modules/ext build/web/WEB-INF/lib Expand the file into a new directory. Users of M$ Windows may find it more convenient to rename defaultheme.jar to defaulttheme.zip, so that they can expand its contents using the Explorer. defaultheme.jar defaulttheme.zip Step One: Updating the manifest The first thing to do is to give your theme a name, and to edit the manifest accordingly. I'll start by renaming the Creator default theme, from defaulttheme to isopaleocopria. The theme name is given in the manifest entry X-SJWUIC-Theme-Name. At the same time, I'll modify the package names for the various resources so that they are based on a namespace that I own. defaulttheme isopaleocopria X-SJWUIC-Theme-Name Here's the new manifest: Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.2 Created-By: 1.4.2_07-b05 (Sun Microsystems Inc.) Name: com/sun/rave/web/ui/theme/ X-SJWUIC-SWAED-Version: 3.0 X-SJWUIC-Theme-Version: 1.0 X-SJWUIC-Theme-Name: isopaleocopria X-SJWUIC-Theme-Prefix: /theme X-SJWUIC-Theme-Messages: org.isopaleocopria.themes.messages.messages X-SJWUIC-Theme-Images: org.isopaleocopria.themes.properties.images X-SJWUIC-Theme-JavaScript: org.isopaleocopria.themes.properties.javascript X-SJWUIC-Theme-Stylesheets: org.isopaleocopria.themes.properties.stylesheets A few important points about the manifest: org.isopaleocopria.themes.properties.images org/isopaleocopria/themes/properties/images.properties If the above conditions are not met, Creator will reject the theme. Nota Bene: According to the spec, lines in a JAR manifest file are limited to a maximum length of 72 bytes. When you extract and first open the manifest for editing, you may notice that some lines longer than 72 bytes have been wrapped, and the enjambed portion has been indented with a single space character. You'll need to patch these lines back together again before reconstituting the JAR or ZIP file. Step Two: Editing theme content Before editing the content, you'll want to move it to your own package. In order for the theme manager to find the content in its new location, you'll need to update the path values in the various property files listed above. For example, as part of developing my new theme I would move the Javascript file /com/sun/rave/web/ui/defaulttheme/javascript/table.js to org/isopaleocopria/themes/javascript/table.js, and update the corresponding value in the javascript.properties file. /com/sun/rave/web/ui/defaulttheme/javascript/table.js org/isopaleocopria/themes/javascript/table.js javascript.properties After updating the theme name and the locations of the property files, it's time to edit the theme content. In some cases, the key names in the property files will help you to identify which theme artifact belongs to which component. The CSS stylesheets also generally use a truncated version of the name of the component as the prefix of style class names that apply to the component. Step Three: Importing the edited theme into Creator When you are finished modifying the theme content, you will need to repackage the contents as a JAR or ZIP file which can then be imported into Creator. To import the theme file, start Creator and open or create a project. From the menu, open Tools -> Library Manager. Select the Theme Libraries section, and click on "New Library". Give the library a name, e.g. IsoPaleoCopria (note that spaces are not accepted, probably a bug), and add the theme JAR or ZIP file to the library's classpath and to its runtime, using the appropriate tabs. Finally, to apply the theme to the current project, select it in the project hierarchy, right-click, and choose "Apply Theme". Have fun! (2006-02-08 15:36:48.0) Permalink Fraters Libertas (sic). (2004-11-10 11:00:04.0) Permalink Craving crack. NetBeans sex exception? NetBeans 3.6 threw an IllegalStateException today while I was creating a new project. The exception was announced in a pop-up window, and also on the command line, with the message: gris-118% sex exception: java.lang.IllegalStateException: can't declare any more prefixes in this context New meta-blog about XML There is a new website that aggregates RSS feeds from several bloggers well-known in the XML community, dubbed "Planet XMLhack":. (2004-10-01 10:22:48.0) Permalink Markup as protest Michael Sperberg-McQueen used to say that all markup is interpretation. And some markup is demonstration: </Bush>. I suppose I don't need to point out that the Bush element isn't well formed. Or that maybe it should be empty. (2004-09-26 18:46:45.0) Permalink Actually Thanks to Gary Trudeau, I now know what "actually" means: Doonesbury. (2004-09-26 18:21:19.0) Permalink Twice baked Sometimes a word describing a technique can take on localized forms, which effectively describe local variations in the technique. Take biscuit. The word comes to us from Latin via French, and means, literally, "twice baked". Baked goods were passed a second time through the oven to ensure their longevity. At the English table, it refers generally to savories; at the French, to sweets. Italy has given us a sweet variant, often with anise, that we have imported along with the Italian name for the technique: biscotto. And from Germany, that ultimate in crackers for teething babies, zwieback. These are baked once as bread, and then toasted. (2004-09-20 16:52:26.0) Permalink Today's Page Hits: 29
http://blogs.sun.com/gjmurphy/
crawl-002
refinedweb
2,630
54.93
Greetings, printf() only takes one string literal in the first argument. To learn more about printf(), click here. By sending printf("Hello %s World""SBL") to printf(), you will retrieve an error because the string literal can only contain one string. Each "" contains one string, and the data inside. Any addition variables are called leading arguments which take a comma to seperate the difference: printf("Test %s %i %d", abc, def, ghi); Example 1.1: Leading arguments The string literal is everything between the "" double quotations, and everything after the comma(s) are the leading arguments. It is quite simple to fix your coding problem. Just add a comma between the two string literals, as "SBL" is looked at as one of the leading argument(s). printf("Hello %s world", "SBL"); - Stack Overflow Now how come when i run and compile it the dos screen flashes real fats and goes away instead of staying and printing to the screen as my professor explained it??? Try: #include<stdio.h> int main( ) { char str[]="SBL"; printf("Hello %s World", str); return 0; } The printf function is wainting to print a string designated by "%s". > the dos screen flashes real fats and goes away Well, are you double-clicking on the DOS program, or running it in Command Prompt? If you are doing the first, DOS programs always do that unless you need to retreive some type of data, or freeze the screen. DOS applications are usually run inside a Prompt, but if not, Windows treats it like an application. My best bet would be to either pause the screen using: system("pause"); Or for a more recommended step, just use conio.h's function called getch(): #include <conio.h> int main() { getch(); // wait for key press return 0; } How getch() works The function is normally defined in <conio.h>.(). Why system() calls aren't safe Using system("pause") is a bad habit. By calling system(), you are invoking the default shell. The shell executes the command-line given to it which runs the 'pause.exe' program. So your simple c program is relying on two external programs for checking a single key press. Though, what if someone deleted or renamed 'pause.exe'? Better yet, what if someone tried to compile your program on unix, or another operating system...It wouldn't work. There are always alternatives: #include <stdio.h> void cmdwait(void) { int c; do { c = getchar(); if (c == EOF) break; } while (c != '\n'); } int main() { // press any key to continue cmdwait(); return 0; } Instead of calling on system("pause"); just call on cmdwait(); It's alot safer. I hope this helps, - Stack Overflow
https://www.daniweb.com/programming/software-development/threads/11194/error-message-when-i-run-my-program-in-c
CC-MAIN-2016-50
refinedweb
442
72.87
plib.classes 0.9.1 Useful Python classes. The PLIB.CLASSES package contains a number of useful packages and modules that extend the Python standard library. Note: PLIB.CLASSES works with Python 2.7. If you are using Python 3, see the PLIB3.CLASSES package, available at. The setup.py script for PLIB.CLASSES uses the setuputils helper module, which helps to automate away much of the boilerplate in Python setup scripts. This module is available as a separate release at. The PLIB.CLASSES Package The following classes are available in the plib.classes namespace: - The StateMachine class implements a basic finite state machine with customizable code to be run at each state transition. Installation To install PLIB.CLASSES, - Requires plib.stdlib (>=0.9.22) - Provides plib.classes-0.9.1.xml
https://pypi.python.org/pypi/plib.classes
CC-MAIN-2017-43
refinedweb
132
54.29
Even if you make them up yourself, acronyms should be treated as words like any other words used in Java names. There is no need to keep them in upper case. Consider how ugly the acronym “TCP/IP” looks in the following example if the English language acronymn rule is followed to the letter. package com.playpen.TCP_IP; public class TCP_IPManager { : public static final int MAX_TCP_IP_CLIENTS = 100; public TCP_IPConnection getConnection(long msecsTCP_IPTimeout) { : } } Name the TCP/IP related variables and methods like the rest of the code, treating it as one word. package com.playpen.tcpip; public class TcpipManager { : public static final int MAX_TCPIP_CLIENTS = 100; public TcpipConnection getConnection(long msecsTcpipTimeout) { : } } This works fine for most acronyms, even two letter ones. For single letter acronyms or words, try not to use them at all – find a longer alternative. English language upper case acronymn conventions do not translate well into Java, so treat them as words.
http://javagoodways.com/name_acronym_Acronyms_are_words.html
CC-MAIN-2021-21
refinedweb
153
50.46
Introduction to File Processing Overview of File Processing and Definitions. Streaming Prerequisites To support file processing, the .NET Framework provides the System.IO namespace that contains many different classes to handle almost any type of file operation you may need to perform. Therefore, to perform file processing, you can include the System.IO namespace in your project. The parent class of file processing is Stream. With Stream, you can store data to a stream or you can retrieve data from a stream. Stream is an abstract class, which means you cannot use it to declare a variable in your application. As an abstract class, Stream is used as the parent of the classes that actually implement the necessary operations. You will usually use a combination of classes to perform a typical operation. For example, some classes are used to create a stream object while some others are used to write data to the created stream. Practical Learning: Introducing Streaming Private the files are still using extensions. Applications can also be configured to save different types of files; that is, files with different extensions. Based on this, if you declare a String variable to hold the name of the file, you can simply initialize the variable with the necessary name and its extension. Here is an example: Private The Path to a File If you declare a string as above, the file will be created in the the made folder must be separated by backslashes..
http://functionx.com/vb/fileprocessing/introduction1.htm
CC-MAIN-2018-51
refinedweb
244
64.61
CBR using SOAP with Namespacestoby saville Nov 13, 2007 5:56 AM Hello, I am trying to route a SOAP message using CBR. The SOAP is: <soapenv:Envelope xmlns: <soapenv:Header/> <soapenv:Body> <om:dslCheck> <order> <solutions> <services> <customer> <phoneNumber>02072740056</phoneNumber> <address> <postCode>sw48dx</postCode> </address> </customer> </services> </solutions> </order> </om:dslCheck> </soapenv:Body> </soapenv:Envelope> My CBR rule is: rule "dslchecker" when xpathMatch "/om:dslCheck" then Log : "DSLChecker"; Destination : "om:dslchecker"; end It doesn't work. However, if i remove the om: namespace from both the SOAP mesasge and the CBR rule, it works. any suggestions why this might be? cheers, Toby 1. Re: CBR using SOAP with NamespacesTom Fennelly Nov 13, 2007 6:01 AM (in response to toby saville) Kurt will be better able to answer this when he comes online, but my guess would be that the xpathMatch part of the DSL needs to support namespaces i.e. binding "om" to it's namespace etc. Not sure if it does that, but Kurt will know for sure. 2. Re: CBR using SOAP with Namespacestoby saville Nov 13, 2007 6:09 AM (in response to toby saville) thanks Tom. 3. Re: CBR using SOAP with Namespacestoby saville Nov 14, 2007 6:49 AM (in response to toby saville) Hello, Any updates on why this might be happening or how to configure namespaces in my CBR action? cheers, toby 4. Re: CBR using SOAP with NamespacesKurt Stam Nov 14, 2007 9:47 AM (in response to toby saville) Yep the XPath is takes into the account the namespace which is why your XPath doesn't match anything. So you either write that such that is accounts for the namespace, or and this is probably nice we should have an option to ignore namespaces. You can take a look at the org.jboss.internal.soa.esb.services.routing.cbr.DslHelper class where the XPath is executed. It should not too terribly hard to figure out how to make it ignore the namespace, so if you please send us a patch if you figure it out. Thx! --Kurt 5. Re: CBR using SOAP with Namespacestoby saville Nov 14, 2007 10:17 AM (in response to toby saville) I know how to do it with Jaxen, but is there a preferred method of getting the namespace from a String representing XML (remembering the org.w3c.dom.Document doesnt give access to the namespace prefix). 6. Re: CBR using SOAP with Namespacesjaigates vg Apr 11, 2013 11:33 AM (in response to toby saville) this should work rule "dslchecker"use namespaces " when xpathMatch "/om:dslCheck" om=" then Log : "DSLChecker"; Destination : "om:dslchecker"; end
https://developer.jboss.org/thread/143427
CC-MAIN-2019-22
refinedweb
442
58.32
T. Introduction From its inception in May 2000, TheServerSide.com has been an exceptionally successful information portal. TheServerSide.com is a typical, high volume web site. Incoming requests are dispatched to a front controller servlet for processing (this is very similar to how a Struts application is organized). JSPs are used for rendering response pages. A stateless session bean provides access to business logic, acting as a façade around a number of entity EJBs (using bean-managed persistence). In many cases, data transfer objects move between the different layers. All in all, this was a common architecture considering the state of J2EE when the portal was first created. Over time, projects tend to grow, and functionality ever expands. Past a point, the architecture began to get in the way, preventing TSS from rolling out new functionality. The chief issues were: - The home grown front controller servlet was primitive. It was fine for simple pages, but as soon as your use case expanded beyond simple CRUD (Create Update Delete) style pages, to something with a more complex workflow (such as a wizard), you were left to your own devices – often, a confusing tangle of HTTP query parameters and HttpServletRequest attributes, with code spread across servlets and JSPs. - The overall architecture had many layers. A change to the object model would require a raft of changes: to the database schema, to the entity beans, and to the DTOs (data transfer objects) that moved between the application layers. This highly coupled state led to a brittle application, where even simple object model changes entailed a high degree of risk. - Testing was hard. You have to jump through hoops to test the entity beans, and the web tier. It was obvious that the implementation needed to be refactored to allow for a more agile environment for the development team. The next question was: what solution would be used? After surveying the many options available, the open-source Tapestry project was selected for the presentation tier. Two developers were allocated; Eric Preston and Howard Lewis Ship (an independent consultant, and leader of the Tapestry project). Meanwhile, in parallel, a conversion from entity EJBs to JDO was performed by a second two member team. Because of the architecture of the original site, which funneled all backend access through a set of stateless session beans, it was tractable to rewrite the presentation layer front end at the same time as the database access back end, simply by keeping the interfaces of the stateless session beans stable during the process. Goals The existing (1.0) version of TheServerSide.com is entirely stateless – no HttpSession was allowed; the new version, 2.0, inherited this same requirement. Performance could not be sacrificed either -- TheServerSide.com receives upwards of seven million hits per month. As a content-focused site, it was extremely important that the untold number of external links pointing to articles and discussions on TheServerSide.com remain valid even after the transition. This was a very forward thinking approach; re-architect the existing system in such a way that only the most observant would even detect a change but, in doing so, position for the rapid rollout of visible features. Converting JSPs to Tapestry pages The majority of the work was the straightforward transformation of the JSP pages into Tapestry pages. In many ways, this was a purely mechanical effort, converting JSP tags and scriptlets (Java code embedded within a JSP) into proper Tapestry pages and templates. The 1.0 site included a large number of "components", in the form of JSP snippets that were included by top-level JSPs to form complete pages. Tracking down these individual files and replicating their behavior was a painstaking, but manageable, chore. One of the joys of Tapestry is handling the little ugly issues that occur when formatting complex layouts for the web. For example, consider the title bars used throughout the application, such as the "New content around the community" title bar on the home page: If you look very carefully at the text, you'll see that there is a subtle shadow, and equally subtle shading of the edges of the bar. The HTML developer accomplished this using a mix of cascading style sheets and background images, but the HTML required to achieve the desired result is verbose and awkward: <table class="box" cellspacing="0"> <thead> <tr> <th> <img src="" height="18" width="8"/> <span class="container"> <span class="text">New content around the community</span> <span class="shadow">New content around the community</span> </span> <span class="fill">New content around the community</span> </th> <td> <img src="" height="18" width="7"/> </td> </tr> <tr> <td colspan="2" class="barbottom"> < img </td> </tr> </thead> <tbody> <tr> <td colspan="2"> <h2><a href=""> AspectWerkz 2: An Extensible Aspect Container </a> </h2> . . . </td> </tr> </tbody> </table> Not only is this a lot of typing, but the same pattern is repeated, with subtle variations, throughout dozens of JSPs … a painful violation of the Don’t Repeat Yourself principle on many levels (including the way "New content around the community" is repeated three times!). When using Tapestry, one of your chief problem solving tools is to create new components. Tapestry makes creating custom components natural and easy, and in fact, TheServerSide.com contains dozens of such components. For this situation -- unwanted duplication of HTML and logic -- a Box component, used in many HTML templates, replaces all the gory detail above with the much more streamlined: <span jwcid="@Box" title="New content around the community"> <h2><a href=""> AspectWerkz 2: An Extensible Aspect Container </a> </h2> . . . </span> The Box component is responsible for outputting the <table> and other tags, integrating in the title provided as a parameter, and the content in its body. Because Tapestry components can have their own templates, it is simply a matter of refactoring the earlier example into its own HTML template, Box.html: <table cellspacing="0" class="box"> <thead> <tr> <th><img src="" height="18" width="8"/> <span jwcid="@HeaderBarLabel" value="ognl:title"/></th> <td> <img src="" height="18" width="7"/></td> </tr> <tr> <td colspan="2" class="barbottom"> < img</td> </tr> </thead> <tbody> <tr> <td colspan="2"><span jwcid="@RenderBody"></span></td> </tr> </tbody> </table> Most of this template is just static HTML; the tags with a jwcid attribute are Tapestry components. HeaderBarLabel is another custom component, which outputs the set of three <span> tags used to format the text in title bar (and the shadow on that text). The RenderBody component renders the body of the component, the portion of the page template enclosed by its tags (the <h2> tag and other content from the earlier example). All that's needed to finish the Box component is a component specification, a file used to identify the details of the component (including information about parameters). This file is called Box.jwc: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE component-specification PUBLIC "-//Apache Software Foundation//Tapestry Specification 3.0//EN" ""> <component-specification <parameter name="title" type="java.lang.String" direction="in" required="yes"/> </component-specification> These two files, Box.html and Box.jwc, are simply stored in the application's WEB-INF folder and are automatically available for use within any page or any other component within the application. Many useful components, such as this one, don't require even a single line of Java code. Because creating components is such a common tool when building Tapestry applications, the framework makes it exceptionally easy to do so. This same approach was taken throughout the application – identifying common behaviors and encapsulating them as reusable components. This applies to much more than simple "macro-like" components such as Box … much more sophisticated components are also common. For example, each of the major categories of the application (News, Discussions, Patterns, etc.) includes pages for listing forums, listing threads within a single forum, and listing messages within a single thread, as well as pages for posting a new thread and posting a reply to an existing thread. Each of these pages is a simple "shell" around a more involved component that provides the desired functionality. Once again, the Don’t Repeat Yourself principle … the code and templates related to (for example) posting a new thread into a forum, including the code that interacts with the backend logic in the stateless session bean, is isolated into a single place: the PostForm component. Maintaining URLs One of the great challenges in this project was to make the transformation as invisible as possible, by keeping all the URLs the same, before and after deployment of the 2.0 code base. This is somewhat against the grain for Tapestry, which normally controls URLs entirely. Fortunately, the existing URL format universally used a ".tss" extension (the ".tss" extension was mapped to JSP files, for obscure historical reasons) . For example, a link to a thread within the news category was of the format /news/thread.tss?thread_id=30111. Of course, in the new application, there are no JSPs at all … just Tapestry pages with equivalent functionality. The solution was to create a new servlet, mapped to the ".tss" extension, that would identify the old style links and perform a server-side redirect to the Tapestry application (mapped to /tss), passing the correct parameters, in the format expected by Tapestry. With over seventy pages, and (in some cases) multiple operations per page, that servlet would become very complex! In fact, a more appropriate approach to mapping from old to new is a data driven solution, where the servlet uses configuration data to decide how to handle each request. Data driven solutions are what the HiveMind services and configuration microkernel is all about (HiveMind is another open source project, a kind of sister project to Tapestry); using HiveMind it was possible to create a configuration point that contains several dozen entries, each defining how to map from an external URL (in the old format) to an internal URL (in the Tapestry format). For example: <redirect match- These entries combine path matching with regular expression parsing of the query string (the list of query parameters). From this, a new internal URL is generated, in the format that Tapestry expects. Because the redirect path is a server-side forward (not a client side redirect), the user will still see the external, "old style", URL in their browser's address field. These kind of transformations can also be accomplished using Apache server's mod_rewrite module … however, that means for any testing, an Apache reverse proxy must be set up. Much of TheServerSide.com was tested from within the IDE using Jetty, a light-weight servlet container. Because the rewrite rules were handled in-container, using a servlet and driven by HiveMind, the configuration was constantly tested during normal development. In addition, not having rules inside httpd.conf means that much less configuration needs to be managed during software installation and updates. It was not enough to recognize the old URLs, it was also necessary to generate URLs in the external format. In a typical Tapestry application, existing generic components (such as DirectLink or ExternalLink) are used. For this application, new domain-specific components were created, such as ThreadLink and UserLink. These components would assemble a URL with the expectation that the previously described mapping would occur. Again, the end result was that the links users see, in the live Tapestry application, match exactly the URLs created by the 1.0 version. Dependency Injection The HiveMind microkernel was not relegated to just transforming URLs; it was a central feature in the implementation of the application. Moving business logic out of the presentation tier is always a good idea – the presentation tier is notoriously hard to test because of all the cruft (HTML, query parameters, Servlet API) that gets in the way of simply invoking methods and checking results. In sensible Tapestry applications, the page and components classes should be concerned with just moving and formatting data … any more involved behaviors should be moved elsewhere, where they can be tested outside of the constraints of the web application environment. Many Tapestry applications make use of Spring beans to store such logic, but TheServerSide.com uses HiveMind, which offers a similar services model (based on singletons), and also provides the configuration mechanism (used for URL rewriting as just discussed, and many other things throughout the application). In any case, it is one thing to have your business logic coded and tested … it is another to access it from the web tier. For TheServerSide.com, we leveraged Tapestry's property specification feature, which allows new properties to be added to existing page and component classes. We would then inject HiveMind services into those properties. For example, on the Search page, we needed access to the Searcher service, a kind of wrapper around the Lucene text search engine. Inside the Search.page specification file, we defined a property to hold the service, and accessed the HiveMind Registry to set the default value for the property: <property-specification registry['portal.Searcher'] </property-specification> The portal.Searcher string is the fully qualified service id of the Searcher service, which implements the portal.services.Searcher interface. Inside our code, the Searcher service appears as an abstract property: public class Search extends . . . public abstract Searcher getSearcher(); public void pageBeginRender(. . .) { . . . SearchResults results = getSearcher().search(sc, getReturnCount(), getStartIndex()); . . . Again, this pattern was followed on many pages in the application; business logic was refactored out of servlets and into HiveMind services, and those services were injected into Tapestry pages (or components). This resulted in a much cleaner separation of the presentation logic (in the pages and components) from the business logic (in the HiveMind services), which made it much easier (or even just possible) to unit test the business logic code. Sneaking In Some Improvements The goal of the project was to reproduce all the existing functionality and set the stage for adding new functionality in the future. However, in many cases, it was easier for the developers, and better for the end users, to bend the rules a little and improve things. For example, in the 1.0 version of the application, you could log in from almost any page … but after logging in, you would be returned to the home page, not the page you were looking at prior to entering your email address and password. For the 2.0 version, after logging in, you are returned to the same page, and the same page state. That is, if you have navigated to the third page of news items on the "More News" page and log in, you will still see the third page of new news items. That's a tall order for a supposedly stateless application. It's made possible by a number of specific concepts in Tapestry: - Each page has a unique name, and every page knows its own name. - Page state, even transient page state, is stored in JavaBeans properties of the page object. - Tapestry's Hidden component can store an object (using serialization) into an HTML form, and recreate the object when the form is submitted. Combining these together, the login form stores a memento of the page containing the name of the page, and copies of the page's key properties (such as the new item index on the More News page). When the login form is submitted, the memento is reconstituted, and then used to restore the state of the page after logging in. The application acts as the user expects, in a stateful manner, even though there is no HttpSession to store that state. Another improvement is the announcement zone, an area of the page at the top right of the page reserved for messages and errors. For example, after logging in to the application, you'll see a confirmation message: In fact, this zone isn't limited to just text; using Tapestry's powerful Block component, it's possible to "link" in a portion of another page or another component. This shows up most powerfully in the administrative functions (that most users don't see), where entire forms show up in this space: This kind of behavior would be very difficult to graft into a pure servlet application; because Tapestry is built on a true component object model, these types of manipulations become natural, and the user benefits from a more consistent, more thoughtful layout. Pain Points Very few of the pain points in the conversion were caused by Tapestry. The most troublesome parts of the application were areas where there was a lack of consistency … for example, tech talks vary considerably in layout and format, so building pages to display any single tech talk, or building components to link to a tech talk, proved tedious. The other pain point was the necessity of doing a big bang conversion, rather than some form of incremental conversion. In retrospect, this could have been accomplished, but initially was dismissed. This necessitated the occasional use of the live production application as a reference for functionality when converting a JSP to a Tapestry page. Some best practices evolved over the course of the project, perhaps the most important one being the need to relate old content files to new template files. TheServerSide.com is a content-driven application, and that content is scattered through dozens of different HTML and JSP files. As part of the conversion, files were often renamed, split apart, or moved to entirely new locations. For the content maintainers, it was a necessity to generate and maintain a comprehensive cross-reference of old and new files. Conclusion The conversion of TheServerSide.com to Tapestry has been an unqualified success. Performance and stability are at least as good as the 1.0 version of the application (largely thanks to improved caching provided by the combination of Solarmetric Kodo JDO for database access, and Tangosol Coherence for cluster-wide caching). End users have barely noticed the changes, except in the form of user interface improvements. Several developers have already been able to make bug fixes and improvements to the code with little or no guidance from the primary development team. The HTML page templates are decidedly easier to read and maintain. With the 2.0 code in place, work is already going forward with a 2.1 release which will actually add new features, features that would have been impractical to implement on the original code base. Tapestry has delivered on all fronts: simpler Java code, simpler HTML templates and generally faster and easier development. References Jakarta Tapestry – Jakarta HiveMind – Object Graph Navigation Language – Spring Framework – Lucene – Solarmetric Kodo – Tangosol Coherence -- Jetty – Author Howard Lewis Ship is the creator and lead developer for the Jakarta Tapestry and Jakarta HiveMind projects. He has over fifteen years of full-time software development under his belt, with over seven years of Java. He cut his teeth writing customer support software for Stratus Computer, but eventually traded PL/1 for Objective-C and NeXTSTEP before settling into Java. Howard is the author of Tapestry in Action for Manning Publications, and is currently an independent open-source and J2EE consultant, specializing in customized Tapestry training. He lives in Quincy, Massachusetts with his wife Suzanne, a novelist. Dig Deeper on Web application framework and Java middleware PRO+ Content Find more PRO+ content and other member only offers, here. Start the conversation
http://www.theserverside.com/news/1365138/TSS-Relaunches-on-Tapestry
CC-MAIN-2018-09
refinedweb
3,228
51.07
We're going to be in EGL land on an increasing number of platforms, and working more with extensions for EGL for EGLImage, EGLSync, and hopefully eventually EGLStream. Created attachment 630734 [details] [diff] [review] patch Created attachment 630739 [details] [diff] [review] patch Adds NS_ERRORs when the extensions are 'supported', but their functions are not exposed. Comment on attachment 630739 [details] [diff] [review] patch Review of attachment 630739 [details] [diff] [review]: ----------------------------------------------------------------- ::: gfx/gl/GLContext.cpp @@ +539,5 @@ > #else > const bool once = true; > #endif > > + mAvailableExtensions.Load(extensions, sExtensionNames, !once); To remove the negation here and generally be more explicit, maybe you could use a |firstTime| variable here. ::: gfx/gl/GLContext.h @@ +1568,2 @@ > bool& operator[](size_t index) { > + NS_ASSERTION(index < Size, "out of range"); This should be a MOZ_ASSERT similar to bug 732607. Created attachment 632051 [details] [diff] [review] patch with nits fixed Carrying forward r+ with nit fixes. Comment on attachment 632051 [details] [diff] [review] patch with nits fixed [Approval Request Comment] Required by bug 728524 Comment on attachment 632051 [details] [diff] [review] patch with nits fixed Approving supporting patches for bug 687267
https://bugzilla.mozilla.org/show_bug.cgi?id=762265
CC-MAIN-2017-22
refinedweb
181
50.16
Working With Dates and Times in Python Python has lots of power when it comes to working with dates. These modules are helpful for creating an app that needs to that keeps track of appointments or run on certain days. Join the DZone community and get the full member experience.Join For Free Python.data. datetime.date Python can represent dates several different ways. We’re going to look at the datetime.date format first as it happens to be one of the simpler date objects. >>> datetime.date(2012, 13, 14) Traceback (most recent call last): File "<string>", line 1, in <fragment> builtins.ValueError: month must be in 1..12 >>> datetime.date(2012, 12, 14) datetime.date(2012, 12, 14) This code shows how to create a simple date object. The date class accepts three arguments: the year, the month and the day. If you pass it an invalid value, you will see a ValueError, like the one above. Otherwise, you will see a datetime.date object returned. Let’s take a look at another example: >>> import datetime >>> d = datetime.date(2012, 12, 14) >>> d.year 2012 >>> d.day 14 >>> d.month 12 Here we assign the date object to the variable d. Now we can access the various date components by name, such as d.year or d.month . Now let’s find out what day it is: >>> datetime.date.today() datetime.date(2014, 3, 5) This can be helpful whenever you need to record what day it is. Or perhaps you need to do a date-based calculation based on today. It’s a handy little convenience method though. datetime.datetime A datetime.datetime object contains all the information from a datetime.date plus a datetime.time object. Let’s create a couple of examples so we can better understand the difference between this object and the datetime.date object. >>> datetime.datetime(2014, 3, 5) datetime.datetime(2014, 3, 5, 0, 0) >>> datetime.datetime(2014, 3, 5, 12, 30, 10) datetime.datetime(2014, 3, 5, 12, 30, 10) >>> d = datetime.datetime(2014, 3, 5, 12, 30, 10) >>> d.year 2014 >>> d.second 10 >>> d.hour 12 Here we can see that datetime.datetime accepts several additional arguments: year, month, day, hour, minute and second. It also allows you to specify microsecond and timezone information too. When you work with databases, you will find yourself using these types of objects a lot. Most of the time, you will need to convert from the Python date or datetime format to the SQL datetime or timestamp format. You can find out what today is with datetime.datetime using two different methods: >>> datetime.datetime.today() datetime.datetime(2014, 3, 5, 17, 56, 10, 737000) >>> datetime.datetime.now() datetime.datetime(2014, 3, 5, 17, 56, 15, 418000) The datetime module has another method that you should be aware of called strftime. This method allows the developer to create a string that represents the time in a more human readable format. There’s an entire table of formatting options that you should go read in the Python documentation, section 8.1.7. We’re going to look at a couple of examples to show you the power of this method: >>> datetime.datetime.today().strftime("%Y%m%d") '20140305' >>> today = datetime.datetime.today() >>> today.strftime("%m/%d/%Y") '03/05/2014' >>> today.strftime("%Y-%m-%d-%H.%M.%S") '2014-03-05-17.59.53' The first example is kind of a hack. It shows how to convert today’s datetime object into a string that follows the YYYYMMDD (year, month, day) format. The second example is better. Here we assign today’s datetime object to a variable called today and then try out two different string formatting operations. The first one adds forward slashes between the datetime elements and also rearranges it so that it becomes month, day, year. The last example creates a timestamp of sorts that follows a fairly typical format: YYYY-MM-DD.HH.MM.SS. If you want to go to a two-digit year, you can swap out the %Y for %y . datetime.timedelta The datetime.timedelta object represents a time duration. In other words, it is the difference between two dates or times. Let’s take a look at a simple example: >>> now = datetime.datetime.now() >>> now datetime.datetime(2014, 3, 5, 18, 13, 51, 230000) >>> then = datetime.datetime(2014, 2, 26) >>> delta = now - then >>> type(delta) <type 'datetime.timedelta'> >>> delta.days 7 >>> delta.seconds 65631 We create two datetime objects here. One for today and one for a week ago. Then we take the difference between them. This returns a timedelta object which we can then use to find out the number of days or seconds between the two dates. If you need to know the number of hours or minutes between the two, you’ll have to use some math to figure it out. Here’s one way to do it: >>> seconds = delta.total_seconds() >>> hours = seconds // 3600 >>> hours 186.0 >>> minutes = (seconds % 3600) // 60 >>> minutes 13.0 What this tells us is that there are 186 hours and 13 minutes in a week. Note that we are using a double forward slash as our division operator. This is known as floor division. Now we’re ready to move on and learn a bit about the time module! The time Module The time module provides the Python developer access to various time-related functions. The time module is based on what it known as an epoch, the point when time starts. For Unix systems, the epoch was in 1970. To find out what the epoch is on your system, try running the following: >>>) I ran this on Windows 7 and it too seems to think that time began in 1970. Anyway, in this section, we will be studying the following time-related functions: time.ctime time.sleep time.strftime time.time Let’s get started! time.ctime The time.ctime function will convert a time in seconds since the epoch to a string representing local time. If you don’t pass it anything, then the current time is returned. Let’s try out a couple of examples: >>> import time >>> time.ctime() 'Thu Mar 06 07:28:48 2014' >>> time.ctime(1384112639) 'Sun Nov 10 13:43:59 2013' Here, we show the results of calling ctime with nothing at all and with a fairly random number of seconds since the epoch. I have seen sort of thing used when someone saves the date as seconds since the epoch and then they want to convert it to something a human can understand. It’s a bit simpler to save a big integer (or long) to a database then to mess with formatting it from a datetime object to whatever date object the database accepts. Of course, that also has the drawback that you do need to convert the integer or float value back into a string. time.sleep The time.sleep function gives the developer the ability to suspend execution of your script a given number of seconds. It’s like adding a pause to your program. I have found this personally useful when I need to wait a second for a file to finish closing or a database commit to finish committing. Let’s take a look at an example. Open a new window in IDLE and save the following code: import time for x in range(5): time.sleep(2) print("Slept for 2 seconds") Now run the code in IDLE. You can do that by going to the Run menu and then choose the Run module menu item. When you do so, you will see it print out the phrase *Slept for 2 seconds* five times with a two-second pause between each print. It’s really that easy to use! time.strftime The time module has a strftime function that works in pretty much the same manner as the datetime version. The difference is mainly in what it accepts for input: a tuple or a struct_time object, like those that are returned when you call time.gmtime() or time.localtime(). Here’s a little example: >>> time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime()) '2014-03-06-20.35.56' This code is quite similar to the timestamp code we created in the datetime portion of this chapter. I think the datetime method is a little more intuitive in that you just create a datetime.datatime object and then call its strftime method with the format you want. With the time module, you have to pass the format plus a time tuple. It’s really up to you to decide which one makes the most sense to you. time.time The time.time function will return the time in seconds since the epoch as a floating point number. Let’s take a look: >>> time.time() 1394199262.318 That was pretty simple. You could use this when you want to save the current time to a database but you didn’t want to bother converting it to the database’s datetime method. You might also recall that the ctime method accepts the time in seconds, so we could use time.time to get the number of seconds to pass to ctime, like this: >>> time.ctime(time.time()) 'Fri Mar 07 07:36:38 2014' If you do some digging in the documentation for the time module or if you just experiment with it a bit, you will likely find a few other uses for this function. Wrapping Up At this point, you should know how to work with dates and time using Python’s standard modules. Python gives you a lot of power when it comes to working with dates. You will find these modules helpful if you ever need to create an application that keeps track of appointments or that needs to run on particular days. They are also useful when working with databases. Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/python-101-working-with-dates-and-time
CC-MAIN-2021-17
refinedweb
1,684
76.32
File input and output¶ See also The ase.io module has three basic functions: read(), iread() and write(). The methods are described here: ase.io. read(filename, index=None, format=None, parallel=True, **kwargs)[source]¶ Read Atoms object(s) from file. - filename: str or file - Name of the file to read from or a file descriptor. - index: int, slice or str The last configuration will be returned by default. Examples: index=0: first configuration index=-2: second to last index=':'or index=slice(None): all index='-3:or index=slice(-3, None): three last index='::2or index=slice(0, None, 2): even index='1::2or index=slice(1, None, 2): odd - format: str - Used to specify the file-format. If not given, the file-format will be guessed by the filetype function. - parallel: bool - Default is to read on master and broadcast to slaves. Use parallel=False to read on all slaves. Many formats allow on open file-like object to be passed instead of filename. In this case the format cannot be auto-decected, so the formatargument should be explicitly given. ase.io. iread(filename, index=None, format=None, parallel=True, **kwargs)[source]¶ Iterator for reading Atoms objects from file. Works as the \(read\) function, but yields one Atoms object at a time instead of all at once. ase.io. write(filename, images, format=None, parallel=True, append=False, **kwargs)[source]¶ Write Atoms object(s) to file. - filename: str or file - Name of the file to write to or a file descriptor. The name ‘-‘ means standard output. - images: Atoms object or list of Atoms objects - A single Atoms object or a list of Atoms objects. - format: str - Used to specify the file-format. If not given, the file-format will be taken from suffix of the filename. - parallel: bool - Default is to write on master only. Use parallel=False to write from all slaves. - append: bool - Default is to open files in ‘w’ or ‘wb’ mode, overwriting existing files. In some cases opening the file in ‘a’ or ‘ab’ mode (appending) is usefull, e.g. writing trajectories or saving multiple Atoms objects in one file. WARNING: If the file format does not support multiple entries without additional keywords/headers, files created using ‘append=True’ might not be readable by any program! They will nevertheless be written without error message. The use of additional keywords is format specific. These are the file-formats that are recognized (formats with a + support multiple configurations): Note Even though that ASE does a good job reading the above listed formats, it may not read some unusual features or strangely formatted files. For the CIF format, STAR extensions as save frames, global blocks, nested loops and multi-data values are not supported. Note ASE read and write functions are automatically parallelized if a suitable MPI library is found. This requires to call read and write with same input on all cores. For more information, see ase.parallel. Note ASE can read and write directly to compressed files. Simply add .gz, .bz2 or .xz to your filename ( .xz requires the backports.lzma module on Python 2). The read() function is only designed to retrieve the atomic configuration from a file, but for the CUBE format you can import the function: which will return a (data, atoms) tuple: from ase.io.cube import read_cube_data data, atoms = read_cube_data('abc.cube') Examples¶ >>> from ase import Atoms >>> from ase.build import fcc111, add_adsorbate >>> from ase.io import read, write >>> adsorbate = Atoms('CO') >>> adsorbate[1].z = 1.1 >>> a = 3.61 >>> slab = fcc111('Cu', (2, 2, 3), a=a, vacuum=7.0) >>> add_adsorbate(slab, adsorbate, 1.8, 'ontop') Write PNG image >>> write('slab.png', slab * (3, 3, 1), rotation='10z,-80x') Write POVRAY file >>> write('slab.pov', slab * (3, 3, 1), rotation='10z,-80x') This will write both a slab.pov and a slab.ini file. Convert to PNG with the command povray slab.ini or use the run_povray=True option: Here is an example using bbox >>> d = a / 2**0.5 >>> write('slab.pov', slab * (2, 2, 1), ... bbox=(d, 0, 3 * d, d * 3**0.5)) Note that in general the XYZ-format does not contain information about the unit cell, however, ASE uses the extended XYZ-format which stores the unitcell: >>> from ase.io import read, write >>> write('slab.xyz', slab) >>> a = read('slab.xyz') >>> cell = a.get_cell() >>> cell.round(3) array([[ 5.105, 0. , 0. ], [ 2.553, 4.421, 0. ], [ 0. , 0. , 18.168]]) >>> a.get_pbc() array([ True, True, False], dtype=bool) Another way to include the unit cell is to write the cell vectors at the end of the file as VEC<N> <x> <y> <z> (used for example in the ADF software). >>> write('slab.xyz', vec_cell=True) Use ASE’s native format for writing all information: >>> write('slab.traj', slab) >>> b = read('slab.traj') >>> b.cell.round(3) array([[ 5.105, 0. , 0. ], [ 2.553, 4.421, 0. ], [ 0. , 0. , 18.168]]) >>> b.pbc array([ True, True, False], dtype=bool) A script showing all of the povray parameters, and generating the image below, can be found here: save_pov.py An other example showing how to change colors and textures in pov can be found here: ../../tutorials/saving_graphics.py. Adding a new file-format to ASE¶ Try to model the read/write functions after the xyz format as implemented in ase/io/xyz.py and also read, understand and update ase/io/formats.py.
https://wiki.fysik.dtu.dk/ase/ase/io/io.html
CC-MAIN-2018-39
refinedweb
908
68.06
subprocess.Popen handling stdout and stderr as they come subprocess.popen stdout to file python subprocess popen get stdout and stderr python subprocess stdout python subprocess get output python subprocess output to file python subprocess output to list python subprocess long running process I'm trying to process both stdout and stderr from a subprocess.Popen call that captures both via subprocess.PIPE but would like to handle the output (for example printing them on the terminal) as it comes. All the current solutions that I've seen will wait for the completion of the Popen call to ensure that all of the stdout and stderr is captured so that then it can be processed. This is an example Python script with mixed output that I can't seem to replicate the order when processing it in real time (or as real time as I can): $ cat mix_out.py import sys sys.stdout.write('this is an stdout line\n') sys.stdout.write('this is an stdout line\n') sys.stderr.write('this is an stderr line\n') sys.stderr.write('this is an stderr line\n') sys.stderr.write('this is an stderr line\n') sys.stdout.write('this is an stdout line\n') sys.stderr.write('this is an stderr line\n') sys.stdout.write('this is an stdout line\n') The one approach that seems that it might work would be using threads, because then the reading would be asynchronous, and could be processed as subprocess is yielding the output. The current implementation of this just process stdout first and stderr last, which can be deceiving if the output was originally alternating between both: cmd = ['python', 'mix_out.py'] process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, **kw ) if process.stdout: while True: out = process.stdout.readline() if out == '' and process.poll() is not None: break if out != '': print 'stdout: %s' % out sys.stdout.flush() if process.stderr: while True: err = process.stderr.readline() if err == '' and process.poll() is not None: break if err != '': print 'stderr: %s' % err sys.stderr.flush() If I run the above (saved as out.py) to handle the mix_out.py example script from above, the streams are (as expected) handled in order: $ python out.py stdout: this is an stdout line stdout: this is an stdout line stdout: this is an stdout line stdout: this is an stdout line stderr: this is an stderr line stderr: this is an stderr line stderr: this is an stderr line stderr: this is an stderr line I understand that some system calls might buffer, and I am OK with that, the one thing I am looking to solve is respecting the order of the streams as they happened. Is there a way to be able to process both stdout and stderr as it comes from subprocess without having to use threads? (the code gets executed in restricted remote systems where threading is not possible). The need to differentiate stdout from stderr is a must (as shown in the example output) Ideally, no extra libraries would be best (e.g. I know pexpect solves this) A lot of examples out there mention the use of select but I have failed to come up with something that would preserve the order of the output with it. Sorry if I misunderstand the question...but if you are looking for a way of having subprocess.Popen output to stdout/stderr in realtime, you should be able to achieve that with: import sys, subprocess p = subprocess.Popen(cmdline, stdout=sys.stdout, stderr=sys.stderr) Probably, stderr=subprocess.STDOUT, may simplify for your filtering? If that is not what you are/were looking for, sorry. But hopefully it will fit others needs. subprocess – Work with additional processes, Use check_output() to capture the output for later processing. Messages are sent to standard output and standard error before the By passing different arguments for stdin, stdout, and stderr it is possible to mimic the variations of os.popen(). The "repeater.py: exiting" lines come at different points in the output for each The following are code examples for showing how to use subprocess.Popen().They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. I found working example here (see listing of capture_together.py). Compiled C++ code that mixes cerr and cout executed as subprocess on both Windows and UNIX OSes. Results are identitical Getting realtime output using Python Subprocess, And I want to capture the output and display it in the nice manner with clear formatting. Popen(shlex.split(command), stdout=subprocess. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. The type of input must be bytes or, if universal_newlines was True, a string. communicate() returns a tuple (stdout_data I was able to solve this by using select.select() process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, **kw ) while True: reads, _, _ = select( [process.stdout.fileno(), process.stderr.fileno()], [], [] ) for descriptor in reads: if descriptor == process.stdout.fileno(): read = process.stdout.readline() if read: print 'stdout: %s' % read if descriptor == process.stderr.fileno(): read = process.stderr.readline() if read: print 'stderr: %s' % read sys.stdout.flush() if process.poll() is not None: break By passing in the file descriptors to select() on the reads argument (first argument for select()) and looping over them (as long as process.poll()indicated that the process was still alive). No need for threads. Code was adapted from this stackoverflow answer subprocess – Work with additional processes, The subprocess module defines one class, Popen and a few wrapper functions that Use check_output() to capture the output for later processing. It is also possible watch both of the streams for stdout and stderr, as with popen3(). The "repeater.py: exiting" lines come at different points in the output for each loop style.. subprocess.Popen Python Example, Popen(). They are from open source Python projects. You can vote up the examples Queue() handler = ChangeHandler(shared_queue) observer.schedule(handler, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=subprocess. it # comes from the shutdown of the interpreter in the subcommand. stderr Popen. Interacting with a long-running child process in Python, It comes with several high-level APIs like call, check_output and it, terminating it cleanly and getting all the server's stdout and stderr when done. (meaning that Popen returns immediately and the child process runs in the background). The sample is similar except for how stdout is handled; there's no The process.communicate () call reads input and output from the process. stdout is the process output. stderr will be written only if an error occurs. If you want to wait for the program to finish you can call Popen.wait (). pynacl/log_tools.py - native_client/src/native_client, to stdout. Otherwise log to stderr at INFO level and do not print. subprocess output unless there is an error If a logging file handle is set, always emit all output to it. Popen(command, Capture the output as it comes and emit it immediately. As you might infer from the above example, stdout and stderr both get piped to your own stdout and stderr by default. We can inspect the returned object and see the command that was given and the returncode: >>> completed_process.args 'python --version' >>> completed_process.returncode 0 Capturing output - I really can't think of any solution that doesn't use threads. Is there any particular reason you want to avoid them? - If all you did want to do is print to terminal, that's the default if you take out the PIPEs. Also it wouldn't guarantee exactly the right order, but could you put the stdoutand stderrreads in the same while Trueloop? - The order needs to be preserved. - @dano I can't use threads because this code would get executed in remote (restricted) systems where threads cannot be spawned - related: Subprocess.Popen: cloning stdout and stderr both to terminal and variables - Yes, I've tested it: it does not preserve the order. To disable buffering, use -uflag (if the child is python) or use stdbufutility (or its analogs) or pseudo-tty ( pty, pexpectmodules). Some programs provide a special flag e.g., grep's --line-buffered. - you cannot control buffering of other tools/shells that buffer. The code in this answer does work and preserves the order. - you can control the buffering -- my previous comment mentions several methods. Try your code with mix_out.pyfrom your question. Your code won't preserve the order unless you pass -uflag to pythonexecutable or run it using stdbufor run it with pseudo-tty.
http://thetopsites.net/article/54214184.shtml
CC-MAIN-2020-50
refinedweb
1,477
67.04
This article has been excerpted from book "Visual C# Programmer's Guide"Any programmer, no matter how experienced, cannot create complex programs without any errors on the first attempt! Although syntax errors are reported at the compiler level, the compiler cannot detect and report more complex runtime errors. To determine the bugs of a program at runtime, we use debuggers. The .NET Framework provides two: CorDbg, the command-line runtime debugger, and DbgCLR, the Windows-based debugger. Both debuggers can be used only to debug managed code. Debugging with CorDbg The CorDbg debugger runs on the command line. Although CorDbg actually is more suitable for third-party tool developers and expert users, let's briefly explore use of this tool by debugging the code for the JustButton class defined in Listing 4.2. Listing 4.2: JustButton Class (JustButton.cs) using System;using System.Windows.Forms;public class JustButton : Form{ private Button oneButton; public JustButton() { oneButton = new Button(); oneButton.Text = "Click Me!"; oneButton.Dock = DockStyle.Bottom; oneButton.Click += new System.EventHandler(Button_Clicked); this.Controls.Add(oneButton); } protected void Button_Clicked(object sender, EventArgs e) { MessageBox.Show("The Button was Clicked!!"); } [STAThread] public static void Main() { Application.Run(new JustButton()); }}JustButton is a simple Windows form application that contains a single button. When you click the Click Me! button in the JustButton form, a message box (shown in Figure 4.9) is displayed.Figure 4.9: JustButton Form Application Compile this class into a Windows application using the following command-line compilation string: csc /debug+ /t:winexe JustButton.cs Be sure use the /debug+ directive because it makes the compiler emit extra debugging information in a file called <filename>.pdb. Once you compile the file, the next step is to debug this small program. Start up the command prompt window and navigate to the directory where you have compiled the above application. Now start the debugger by running the command CorDbg at the command prompt. This brings up the (CorDbg) command prompt. Use the CorDbg command called run JustButton to start debugging the application and load the debugging information from the *.pdb files. You will encounter errors if you don't have a corresponding *.pdb file for the referenced assemblies, but these errors can be ignored. Figure 4.10 shows a warning that CorDbg couldn't load symbols for mscorlib.dll and few other DLLs. Also shown in the figure is the line of source code where the debugger halted- Application.Run(new JustButton());. Figure 4.10: CorDbg Debugger You can use commands such as ap to view the application domains and pro to view the current managed processes running. To set a breakpoint, use the command b and specify the line number (in this example, the command b 19 sets the breakpoint on the 19th line of the source code). The debugger shows that the breakpoint has been set within the Button_Clicked method. Use the cont command to continue running the application. Once the application shows, click the Click Me! button and switch to the debugger window. As shown in Figure 4.11, the JustButton application breaks at line 19 and the source code is shown in CorDbg. Figure 4.11: Breakpoint for JustButton Application If you want to view the source code of a particular line, use the sh command and specify the line number (for the JustButton example, type sh 18). The selected line is marked with an asterisk (*), as shown in Figure 4.12. Figure 4.12: Viewing the Source Code with sh To view the values of any of the variables, you can use the print <variable name> command. For example, to view the button instance, try using the print sender command, which lists the various properties of the button that raised this event (see Figure 4.13). Figure 4.13: List of Property Values of the Button Instance After Using Print To continue running the application, you can use the cont command, which displays the message box. Now every time you press the Click Me! button, the debugger automatically breaks at line 19. If you want to remove the breakpoint, you may do so in one of two ways. You can use del command to remove all the breakpoints; or, to remove a specific breakpoint, you may first use the break command to list all existing breakpoints along with their ID numbers and then use del <break id>, specifying the ID number of the breakpoint you wish to remove. Finally, to end debugging, use the ex command and exit the debugger. Debugging with DbgCLR The DbgCLR graphical user interface debugger is a downgraded version of the Visual Studio .NET debugger. It hosts the same interface and debugging methods but cannot compile applications or be used to write applications, whereas VS.NET can do all of the above and much more. You can find DbgCLR within tcausehe <drive>:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\GuiDebug directory. Run the tool and select the application to debug from the Debug menu's Program to Debug dialog box. Next, use the Open dialog box from the File menu to open the source code for debugging. Then you can set breakpoints in the source code and finally choose Run from the Debug menu to start debugging. Because the rest of the debugging process with DbgCLR is identical to debugging with VS.NET, it is covered in the VS.NET debugger discussion that follows. Using the Visual Studio .NET Debugger The Visual Studio .NET debugger works best while debugging applications created in VS.NET. If you use it to debug other applications, its functionality is very similar to the DbgCLR tool. With the VS.NET debugger, you can debug all kinds of applications-console applications, library DLLs, Windows forms, Web forms, and Web services. For a short look at how the debugger works, build the JustButton class in VS.NET, which is similar to the class built in the previous JustButton example. You can find the necessary VS.NET project file for this example in the downloadable code. In VS.NET, choose Open?Project from the File menu and select the JustButton project to open the project. This brings up the screen pictured in Figure 4.14.Figure 4.14: JustButton Class in VS.NET Once you have the class ready, switch to the code view by either pressing the F7 shortcut key or selecting View?Code from the View menu. In code view, you have several ways to add breakpoints. You can click in the left margin alongside the line number; you can position the cursor on the line and press the F9 shortcut key; or you can press Ctrl+B to bring up a dialog box that helps you set advanced breakpoint options. Set a breakpoint on line 92 of the JustButton example, as shown in Figure 4.15. Figure 4.15: New Breakpoint Dialog Box Once your breakpoints are set, select Start from the Debug menu. VS.NET automatically compiles the application and runs it. As soon as a breakpoint is reached, the application stops and you can view the details of the application in VS.NET. In this example, you must click the Click Me button so VS.NET will show the breakpoint you set on line 92 (Figure 4.16). Figure 4.16: Debugging in VS.NET As the figure shows, the VS.NET brings up a Locals window that lists all the method's variables in the local scope and their values at runtime. It is much easier to examine the values of different variables from the VS.NET debugger than from the CorDbg tool. From the Locals window, if you double-click an entry in the Value column and manually enter a value for a variable, the change is reflected immediately. Also shown in the figure is the Call Stack window, which displays the complete call stack for the application. To continue running the application, you can choose Debug?Continue. You can also use functions such as Step Into, Step Over, or Step Out from the Debug menu to proceed with debugging line by line, to step over the breakpoint, or to step out of the breakpoint method, respectively. Once you finish debugging your application, select Stop Debugging from the Debug menu. ConclusionYou may choose from many C# compiler options to compile your applications. ILDASM is a very useful tool that can be used to view the metadata of an assembly and disassemble an assembly into IL code. The ILASM tool can be used to compile MSIL code into a .NET assembly. The .NET SDK provides a host of tools that support cross-language debugging, including the command-line debugger, CorDbg, and the Windows-based debugger, DbgCLR. The debugger included with Visual Studio .NET is equally powerful and easy to use. See my other articles on the website on .NET and C#. View All
http://www.c-sharpcorner.com/uploadfile/prvn_131971/runtime-debuggers/
CC-MAIN-2017-22
refinedweb
1,480
57.47
a lot more interesting and interactive. The display I’m using is a 16×2 LCD display that I bought for about $5. You may be wondering why it’s called a 16×2 LCD. The part 16×2 means that the LCD has 2 lines, and can display 16 characters per line. Therefore, a 16×2 LCD screen can display up to 32 characters at once. It is possible to display more than 32 characters with scrolling though. The code in this article is written for LCD’s that use the standard Hitachi HD44780 driver. If your LCD has 16 pins, then it probably has the Hitachi HD44780 driver. These displays can be wired in either 4 bit mode or 8 bit mode. Wiring the LCD in 4 bit mode is usually preferred since it uses four less wires than 8 bit mode. In practice, there isn’t a noticeable difference in performance between the two modes. In this tutorial, I’ll connect the LCD in 4 bit mode. Connecting the LCD to the Arduino resistor in the diagram above sets the backlight brightness. A typical value is 220 Ohms, but other values will work too. Smaller resistors will make the backlight brighter. The potentiometer is used to adjust the screen contrast. I typically use a 10K Ohm potentiometer, but other values will also work. Here’s the datasheet for the 16×2 LCD with all of the technical information about the display: lets() { } Your LCD screen should look like this:: "); }> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.setCursor(2, 1); lcd.print("hello, world!"); } void loop() { }(500); lcd.noCursor(); delay(500); }(500); lcd.setCursor(12, 1); lcd.noCursor(); delay(500); }: #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.print("hello, world!"); } void loop() { lcd.display(); delay(500); lcd.noDisplay(); delay(500); }: .: #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); } void loop() { lcd.setCursor(0, 0); lcd.autoscroll(); lcd.print("ABC"); delay(500); } Like the lcd.scrollDisplay() functions, the text can be up to 40 characters in length before repeating. At first glance, this function seems less useful than the lcd.scrollDisplay() functions, but it can be very useful for creating animations with custom characters.: . Here’s a video version of this tutorial so you can see what each function does on the LCD in real time: If you found this article useful, subscribe via email to get notified when we publish of new posts! And as always, if you are having trouble with anything, just leave a comment and I’ll try to help you out. how do I make two custom characters? #include LiquidCrystal lcd(8, 9, 4, 5, 6, 7); byte customChar[8] = { 0b00000, 0b00000, 0b11011, 0b10101, 0b10001, 0b01010, 0b00100, 0b00000 }; byte customChar1[8] = { 0b01110, 0b01110, 0b00100, 0b01110, 0b10101, 0b00100, 0b00100, 0b01010 }; byte customChar2[8] = { 0b00000, 0b01110, 0b10001, 0b10101, 0b10001, 0b01110, 0b00000, 0b00000 }; byte customChar3[8] = { 0b00100, 0b00000, 0b01110, 0b10001, 0b10001, 0b11011, 0b01010, 0b01010 }; void setup() { lcd.createChar(1, customChar); lcd.createChar(2, customChar1); lcd.createChar(3, customChar2); lcd.createChar(4, customChar3); lcd.begin(16, 2); lcd.setCursor(15,0); lcd.write(1); lcd.setCursor(13,0); lcd.write(2); lcd.setCursor(11,0); lcd.write(3); lcd.setCursor(9,0); lcd.write(4); } void loop() { } I hear your post and I’ll raise one other. This topic was discussed in Arduino forums. Specifically the forum post, in 2012, talked about how lcd.print() and lcd.write() functions are different. In fact, without going into too much detail, the print function evetually calls the write function. It’s nice for the hobbyist to tinker. It allows the learning process to grow. So, while I was reading the post, participants replied with differing ideas. One poster tried making the characters move in animation. Copying and pasting the code, I believe the poster was having trouble with developing the animation. As it turns out I discovered where he was having the problem. In the loop section of the code the poster didn’t clear the screen to print, or write, the other characters. The following is the fix to have animated characters on the lcd. #include // initialize the library LiquidCrystal lcd(12, 11, 5, 4, 3, 2); byte heart[8] = { // 1 0b00000, 0b00000, 0b01010, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000 }; byte smiley[8] = { // 2 0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b10001, 0b01110, 0b00000 }; byte frownie[8] = { // 3 0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b00000, 0b01110, 0b10001 }; byte armsDown[8] = { // 4 0b00100, 0b01010, 0b00100, 0b00100, 0b01110, 0b10101, 0b00100, 0b01010 }; byte armsUp[8] = { // 5 0b00100, 0b01010, 0b00100, 0b10101, 0b01110, 0b00100, 0b00100, 0b01010 }; void setup() { lcd.createChar(1, heart); lcd.createChar(2, smiley); lcd.createChar(3, frownie); lcd.createChar(4, armsDown); lcd.createChar(5, armsUp); lcd.begin(16, 2); lcd.setCursor(3, 0); lcd.write(1); lcd.print(” Arduino “); lcd.write(2); lcd.setCursor(4, 1); lcd.print(“Animation”); delay(5000); } void loop() { delay(500); lcd.clear(); lcd.setCursor(4, 1); lcd.write(5); lcd.setCursor(13, 0); lcd.write(3); delay(500); lcd.clear(); lcd.setCursor(4, 1); lcd.write(4); lcd.setCursor(13, 0); lcd.write(2); } i don’t understand it more imfo plz nevermind I just found out srry Thank you! I’ve needed detail like this for a while. I have a project for work that I wanted to use my LCD display for, but didn’t know how to use it. Great! Glad it helped :) Please, could you post some tips on how to use I2C Lcd displays. Tks I’m in the process of writing a post about this right now. Will let you know when it’s finished! My lcd is just showing boxes l dont know to fix the problem pls help me with that SUPER DANKEEEEEE!!! Your welcome !!! ::)) How can I print on two lines at once? I figured out how to set the cursor when I need it to begin at a certain point but, now I need two lines. Any help is appreciated. You can duplicate the lcd.setCursor and lcd.print functions like below, one for each line. They can be used in the setup section or the loop section: #include LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(“Line 1”); lcd.setCursor(0, 1); lcd.print(“Line 2”); } Sorry, the first line should say # include LiquidCrystal….. This is an awesome tutorial. Thanks for sharing it. :) yo! How can you display a data log output in LCD that is too many that a 16×2 cant handle? Could you clear (lcd.clear) the screen after a certain number of values have been printed to it? Maybe clear it after each value is printed? The scroll function only works for under 40 characters before it loops back on itself… great another tutorial on using 16×2 displays. How about one for 16×4? There aren’t many of those on the web This tutorial should work with a 16×4 LCD (as long as it uses the Hitachi HD44780 driver). Just set the screen dimensions with the function lcd.begin(16, 4)… I like this tutorial alot, there is just one problem, for some reason, when i connect my lcd screen, it blinks off and on, and sometimes it doesen’t even make a light, and then the 5v and ground pins start smoking and melting the plastic, i really need some help on this, please e-mail me if you can. a short circuit maybe, it happened once with me in a USB 3 port There is definitely a short somewhere. Not all LCDs have the same pin out. Check the datasheet for yours, or see if the pins are labeled on the PCB. I’ll update the diagram in the post so you can see the pin labels Thanks a lot..!! It’s a great tutorial. I am quite new to this,never used LCD and arduino before. I want that one text should be displayed on LCD when I send ‘1’ as serial data to arduino and display some other text if I send ‘2’ as serial data.But when I put Serial.begin(),some strange characters are displayed on LCD.I know the problem is with Serial.begin. I tried it,but it displays both texts simultaneously . I would be extremely thankful if I can get some useful suggestions to solve my problem. Thanks in advance! If you’re getting strange characters on the display it could be that the baud rate of your serial monitor is different that what’s in your program. You can either change the baud rate of your serial monitor, or you can change the code. In the setup section you can add Serial.begin(9600), or what ever baud rate you want to use. Hope that helps Hye…can anyone help me…i need to make the LCD displaying 4 different text when 4 different button are press… if button1 press then LCD display text A if button2 press then LCD display text B and so on…can anyone help me with the connection and the code…i spent 4 days trying to understand it but seems i cant understand it…im too newbie in Arduino world… My screen turns on but I can’t get words to show. Hi Jake, I would double check to make sure everything is connected properly, and that the connections match the pins in the diagram. On some LCDs the pins are arranged differently. If that doesn’t work, it could be that the screen contrast is set too low… Thanks lcd.print(seconds+0x30) is for? I cannot display the words…but the LCD was on…why? Have you tried adjusting the screen contrast? If that’s not it, make sure the connections are right for your LCD. The RS pin should connect to Arduino pin 12, and the E pin should connect to Arduino pin 11.. i cannot work for “hello, world!” Are you getting anything to display on the screen? I hope you make more great tutorials! hello Tnx very much on all the information . it was very helpful does some one have a load-cell code ??? i am looking for reading on a LCD data which comes from a load-cell (conecting to HX711) how can i restore the data (weight scale)and take him and use him Can you send me the theoretical circuit diagram for this kind of connection?? I’m using an elegoo board, which should be the same as an arduino board but its not allowing me to write things it just fills up all of the pixels on the first row. What version of Arduino should I use? I am on windows, should I use an older version? What kind of backwards language puts the exclamation point at the beginning of a sentence? sir can you gibe me code for push button down counter from 500 to 000 manual button pressed and countdown should star again from 500 . when count down reached to 000 reset to 500. how to write butter pressed count down display please. hello, how about to write codes on OLED 7pins? I’m doing on a project like that. It will be a big help if you reply me. thank you also for this LCD. can you name the apparatus once again Hi, can i get the full program for display the current time as well as the number of taken food parallel with the fixed time? hello. how can i print speed of a dc motor on this lcd using arduino and encoder? Hey, can we control individual pixels? I’m trying to use this as a spectrum analyzer and would need more resolution than only 2 rows :/ Thanks!! Ola, when I try to import DHTLib.zip in my Arduino Create I get this message: Libraries that could not be imported: [] [Lb+T/b/m] 400 invalid_request: attribute “name” of response is missing and required, attribute: name, parent: response Any ideas why? Hello, Nice explained and it is true that with this simple Lcd 2×16 there is a lot of funy and interesting possibilities for creating animated or expressive message or value of sensors. With 4×20, than the possibilities increases but optimisation of simplicity is for me the best and nicesest way to print outvjust what is necesary in clear style. Just a comment regarding the lcd.print() function: If you use, for example lcd.print(xxx.yyyyy,3); the LCD will display xxx.yyy . In other words the 3 tells how many digits to display following the decimal point. I have not seen this documented anywhere (perhaps it was and I missed it.) I discovered this while making a specific gravity meter using a load cell and the HX711 load cell amplifier with a 20 x 4 LCD display and I needed some control over the displayed precision. re my email address: note that it should be all lower case; your email address field changes it to upper case. If you want to run one of these LCDs with an ESP8266 type controller that runs on 3.3v, you’ll find that there isn’t enough deltaV between +V and the contrast pin to get a clear display. Biasing it with a negatice voltage will do the trick. I inserted a battery between ground and the “negative” side of the pot and now get good contrast with about -0.9 v on the contrast pin. BTW, with my Arduino IDE (with 2.3.0 core), I needed 0.1.13 of the DHT lib. Thanks for the fine tutorial! dats too good In the LCD, it is displaying cursor and blinking functions but the text entered in the lcd.print is not being displayed. hye. example coding piezoelectric display ? very helpful thanks Hey I did all of the steps in the video and I don’t know why but my lcd wont turn on and i followed EVERY step just please help me I want to do this project. hello. I was replicating the project but when I uploaded the program the lcd screen would just light up but not display anything. I did all the wiring but i do not have that odd looking piece, pls tell me if it has anything ot do with that or if I did something else wrong This is so awesome! Thank you!! I Will try di Coding Programming, Thanks Man will this connection work even for atmega4809 ?*
https://www.circuitbasics.com/how-to-set-up-an-lcd-display-on-an-arduino/
CC-MAIN-2021-39
refinedweb
2,445
75.71
There's an old tool I've had on my desktop for many years. It was originally called NetMedic, and I think I paid $50 for it back in, oh, about 1997. At some point it was sold, rebranded as VitalAgentIT and given away for free. Then it was built into some expensive, high-end IT solution and never heard from again. Here's the classic UI, still one of the nicest Windows apps ever. Without this neat app, I always feel a little blind. It tells you exactly what kind of traffic is moving over your network in a slick, easy-to-grasp user interface. I've been installing this puppy since NT4.0 days. It has some occasional startup problems with XP Pro, but overall, it's held up remarkably well. Until XP x64 Edition. It won't run on my HP xw8200 workstation, and I won't really expect it to fair better on Vista, so it's getting to be the end of the road for this app. But it's just so useful, and I haven't found an inexpensive solution to replace it. So it's time to write my own. Ideally, I'd like to write an almost exact replica of the original NetMedic app. WPF provides an ideal presentation stack to mimic arbitrary UI, so this makes a good project for learning WPF. It would be really neat if I could apply a "NetMedic" style, as well as other cool styles like USS Enterprise control panels. To pick the geekiest possible example. NetMedic/VitalAgentIT shares similarities with another system monitoring app, Norton System Doctor. Both programs are built on Win32 APIs. NetMedic is (probably) built on NetMon, and Norton System Doctor is built on the performance monitor API (PerfMon). Since there might be several different APIs for monitoring, I wanted to abstract the data source. I whipped up the generic ISignalGenerator interface. public interface ISignalGenerator<T> { void Start(); void Stop(); double SampleRate { get; } T Seed { get; } long StartSample { get; } double Gain { get; set; } double DCOffset { get; set; } double Frequency { get; set; } event NewSamplesEventHandler<T> NewSamples; } The Start method turns on the firehose, and the performance monitor samples the underlying data stream every SampleRate milliseconds. Data samples are returned through the NewSamples event. The underlying implementation is assumed to be asynchronous. The .NET Framework provides the convenient PerformanceCounter wrapper type around the Win32 implementation. This type lives in the System.Diagnostics namespace. I wanted to abstract the PerformanceCounter type a bit, and I wanted to give it a buffer for its data stream. The IPerformanceMonitor interface defines the controller part of the Model-View-Controller pattern. namespace SystemMonitorLib.PerformanceMonitors { public interface IPerformanceMonitor : INotifyPropertyChanged namespace SystemMonitorLib { public interface ISignalView<T> : INotifyPropertyChanged { ISignalGenerator<T> SignalSource { get; } T[] DisplayBuffer { get; } int DisplayBufferSize { get; set; } T MinValue { get; } T MaxValue { get; } } } My PerformanceMonitorControl type derives from System.Windows.Controls.UserControl. As far as layout is concerned, there isn't much to it. <UserControl x:Class="PerformanceMonitorControlLib.PerformanceMonitorControl" Ideally, I want to be able to drop individual PerformanceMonitorControl instances onto a WPF page from the Cider Toolbox, then set their properties in Cider's property grid. But we're not quite there yet, so here's some hand-tooled code. <Window x:Class="SystemMedic.Window1" The neat thing about this code is that I was able to compose two different PerformanceMonitorControl instances (one a numeric display, the other a signal trace) to form a new display (bolded code). Ultimately, all the hard-coded property values will be factored into styles. Here's what the app looks like. I call it SystemMedic, since it's trying to be a combination of NetMedic and Norton System Doctor. There's a lot more I can do with this object model, but this is a start. Ultimately, I want it to look much more similar to NetMedic. It would also be cool to come up with a style that looks like the USS Enterprise displays from, say, Star Trek: The Next Generation. Which is to say, I want to be able to apply arbitrary styling to each control instance. Being able to do that at design time would be the sweetest, and between Sparkle and Cider, it should be quite doable. Update: By popular demand, I've posted the source code, with the caveat that it's quite prototypical. Here are a few things you'll need to know: Since this is a prototype that I haven't touched since May, I'll describe a few design details for future work. In general, the code needs to be refactored to adhere more closely to the Framework Design Guidelines. I would start by removing the interfaces and replacing them with abstract base classes. I think the framework should be simplified greatly, as well. I originally had in mind a much more general signal-display framework, which could handle fast (kHz) signals, but that's largely unnecessary for this application. In any case, have fun, and let me know how it works for you.
http://blogs.msdn.com/b/jgalasyn/archive/2006/05/09/594037.aspx
CC-MAIN-2014-23
refinedweb
840
55.13
May as “crosshair”, then on the first frame of the main scene entered this actionscript: Line 1: Hiding the mouse Line 2: Attaching the movie “crosshair” instanced as “crosshair” at depth 1 Lines 3-5: Every time the crosshair is in the stage, its position is updated to _xmouse and _ymouse coordinates. This means you will move the crosshair with the mouse. Looks simple… it will get (much) more complicated. The second thing we need in an artillery game is… The tank The tank is the core of an artillery game. You will love your tank. Of course I love mine. Of course, every tank has its cannon. A big cannon. Size matters. I created a new movieclip linkaged as “tank” and inside this movieclip I created another one instanced as “cannon”. Look at the picture to understand how I placed the movieclips. Then the actionscript is: Line 3: places the cannon on the stage Lines 9-10 determine the x and y distance between the crosshair and the tank Lines 11-17 determine the angle with trigonometry. This concept is explained in the tutorial called Create a flash draw game like Line Rider or others – part 3. Line 18 rotates the cannon according to the angle Sometimes you may need to limit the cannon angle. It’s very simple do it this way: Lines 18-23 limit the cannon angle between 20 and 160 degrees. Limiting the cannon angle may affect gameplay, use it wisely. Now it’s time to determine the firepower. In this game, we are going to determine it by the distance from the crosshair to the cannon. Lines 24-27 calculate the fire power using the pythagorean theorem (there is no need to publish this example as a .swf because visually it does not change anything). Now it’s time to make our tank do what every tank sould do: FIRE !! The first thing to do when you fire a bullet is determine the exit point of the bullet. I mean: the cannon is on a rotating turret, so I have to place the bullet right next to the end of the cannon to give the player the feeling he really fired that bullet. So I created a new movieclip and linkaged it as “cannonball” Then I added a new function to the script Line 30: Beginning of the actions to be executed when the player press the fire… pardon, the mouse button. Lines 32-33: Determining the exit point of the cannonball using with trigonometry. This concept too is explained in the tutorial called Create a flash draw game like Line Rider or others – part 3. The “48” value you can see it given by the cannon lenght (40) plus the ball radius (5) plus 3 “safety pixels” since sine and cosine functions returns non-integer values. Line 34: Attaching the movieclip with the cannon ball. Notice the “3”: it’s the depth of the movieclip, and giving a fixed depth assure us to have only one cannon ball on the stage. FIRE!!! (again) Now that the cannonball has been released, it’s time to make it fly. Line 34: This time I want more than one cannonball in the stage, so I call the attachMovie function giving the cannon ball the next highest depth available. I can do this using the getNextHighestDepth() function. The name of the movieclip is also affected by the next highest depth available. Line 35: The dirx variable is the horizontal vector of the cannonball, according to its firing angle and the firepower. Line 36: Same thing for diry, the vertical vector Line 37: Every time the cannonball enters in a frame (every frame)… Lines 38-39: … its _x and _y position changes according to dirx and diry. That “50” is simply a divider to make the ball not to go too fast. What happens to a cannonball once in the air? It starts falling due to… Gravity In an arcade game initially gravity is not calculated in a strict physics formula, so we are going to simulate the gravity in this way: Line 2: A variable called gravity is set to 2 Line 39: The gravity value is added to the vertical vector at every frame. Final result is quite reasonable. At the moment the tut stops here, download all source codes, give me feedback, change a line or two and publish them as your own game on various game portals :)<< Great tutorial. Keep them coming. I love it! I will creat now a game! just wonder one thing i havent read the full tutorial butt i wonder do you delete the cannon ball or not??? Nice… I cant wait for part 2 it looks like a game on my iPod called parachute. :] And Have you got My eMail? this stuff is fantastic nice tutorial, but I want the crosshair to be moved by arrow keys (up arrow counter clockwise down arrow clockwise. I also want a movable charecter @questo: read for your char Loved your tutorial. One little thing I can’t get to work. I have made a movieclip instanced as “ballon” And I want the ballon to load next frame where it blow up, when the cannonball hit it. So I have this action in the ballon; onClipEvent(load) { if (this.hitTest( _root.cannonball) ){ _root.gotoAndPlay(2); } Maybe there’s another script or maybe my script is wrong. I would appreciate your help. Thanks and bye ;) Really cool how do you figure this stuff out in the first place? I liked it. Nice cover of the basics of actionscript and i liked the gravity on the balls. I think that the first code you did of the crosshair would be better if you used the “start drag” function instead of making the x and y values the same. It just tends to speed stuff up a little when you have loads of functions going on. Cool. I can’t wait to get started on my game…nice tank! Freekin’ sweet tut man. Great tutorial, waiting second part :) Awesome tut. May I suggest one thing? It would be cool if the cannonballs reacted with each other. For example, if you shot a cannonball at 200 firepower, and on it’s way down you shot another cannonball at 150 firepower, the two would collide and react physically? Just a thought. i think what would be really help full is if you made stage 2 for this tut and have it so that the “tank” can move around, because i folowed the tut and when i had done all the stages i moderated some parts and made the tank move, however the bullets only went upwards and it didnt function properly.. oH IT didn’t all copy…. alrity then ive made this and ive edited it using bits of code i have made it so the enemys move towards the tank but and this is a big but, i need the right hittest heres the code foe the enemys. (if the tank moved they would follow the tnk where ever)help anyone? code for following tank onClipEvent (enterFrame) { if (_root.tank._x > _x) { _x = 5; }}onClipEvent (enterFrame) { if (_root.tank._x_y) { _y = 5; }}onClipEvent (enterFrame) { if (_root.tank._y also i made the balls bounce off the walls just for fun like iwas thinking about making that an upgrade for the future i had to take out the grasvity to do that cause i couldent lower it enough Hello guys, I need some help regarding some trigo maths here. Referring to line 32: start_ball_x = tank._x 48*Math.cos(angle*Math.PI/180); Is this declaring that tank._x 48 is the hypotenuse if I were to refer to trigo formula – cos (angle in degrees) = adjacent / hypotenuse OR better written as, adjacent = hypotenuse * cos(angle in degrees) which is same format as, start_ball_x = tank._x 48*Math.cos(angle*Math.PI/180); So can I say tank._x 48 is like the hypotenuse? If it is, why are we not using Pythagorean theorem? Another one – On line 31 we have: angle = tank.cannon._rotation-1; this angle is in degrees and why are we converting it back to radians in line 32? is it cos flash measures angle in radians and we are just reversing the process? start_ball_x = tank._x 48*Math.cos(angle*Math.PI/180); I hope someone can enlighten me on this! Sorry for my poor maths! this is for elmer i had that action script before heres the problem onClipEvent(enterframe) { if (this.hitTest( _root.cannonball) ){ _root.gotoAndPlay(2); } add the enter frame function for some reason no matter what I do, the cannonball doesn’t fire, does anyone know what I should do? hey i need help it wont let me open the sourse codes plz help it keeps saying un expected file format Hi! I am having the same problem “Unexpected file format”. I am trying to open the .FLA file with Flash Mx. Please help how would you rotate the turret using left and right keys? plz help me, help me plz. i got it and now i need help agin lolol CAN YOU RE-MAKE THIS IN A MOVIE CLIP INSTEAD OF A FRAME i disagree i think u can all u gotta do is switch the first actionscript with the next and there u go alright well i hope that solves your problems to get te cross hair to move with up and down you need to make it so when you press up it will use cannon angle in some trig let me explain… tank.cannon._rotation = rot; if key is down key up rot -= 6; crosshair_x = tank._x 75*Math.cos(rot*Math.PI/180) crosshair_y = tank._y 75*Math.sin(rot*Math.PI/180) their may be some errors but thats the best i can do while not working and just being lazy Hey guys, i just wanted to ask why are you guys deleting “King Kong’s” notes?I believe that we should all post our own oppinions and not to worry if it is going to get deleted.Well i hope you all listen to what i am saying and for you to stop deleting posts. Thank you Author Because it’s you… hey i love your tuts they are so cool best tut site on whole world but i was wondering how could you create a enemy so when the cannon ball hits it it dies? (enemy made by script like blah blah blah i) well thx for your tut reely COOL! cya Pingback: Create a flash artillery game - step 2 at Emanuele Feronato What is a movie clip linkage. Great tutorial dude I’m making a similar game, but you move the turret, and it goes around 360 degrees. But anyway, i was trying to get the spawn point working (where it duplicates) and I tried everything, and I wasforgot to conv sure I haert it to radians, and you reminded me. But I had no clue about how to make it move, but I figured it out from your code,, but because it moves 360 degrees, I had to edit it slightly, so I just changed it to: angle = this.Turret.Turret_rotatable._rotation-90 Instead of minus 1, so thanks, keep it up! I can’t wait for the next tutorial. BY the way, could you help me with something? I have attached an “enemy” Movie clip which moves towards the player slowly, but as both the enemy and the bullets were created dynamically, I can’t really figure out how to do it. I think that a for loop is probably the bast way, but I don’t know how to tackle it myself. If I figure it out before you respond, I will post up how I did it. ANyway, thanks again for the help from your tutorial! It’s really good work! I’ve been following the line rider one, please will you do how to do a bike or car. I don’t need the line drawing part, it’s just for a different game I’m working on. @Leon In my game I had the same problem. What I did is I added an onEnterFrame function for each bullet I shot. In each event, it looped through an array of all enemies on stage. attachMovie(“bullet”, “bullet” i, _root.getNextHighestDepth()); i ; _root[“bullet” i].onEnterFrame = function() { for(j=0 ; j thats weird. it chopped my post in half. anyway… @leon _root[â€bullet†i].onEnterFrame = function() { for(j=0 ; j dang Manny you got a bug with you post system. I’m guessing with less than or greater than signs @Leon _root[â€bullet†i].onEnterFrame = function() { for(j=0 ; j < enemies.length ; j ){ //check for collision between this bullet and the current enemy //e.g. if(this.hitTest(enemies[j]) //if true then remove both } } each time you dynamically create an enemy, you must push it onto the array, “enemies”. srry again for(j=0 ; j < enemies.length ; j ){ is supposed to be for(j=0 ; j < enemies.length ; j ){ my bad :D omg!! I hate this!! for(j=0 ; j < enemies.length ; j ){ >>>> for(j=0 ; j < enemies.length ; j *two plus signs here* ){ dont worry, i get it, thanks! hey … dunno if its just me but im having some troubles with the cannonball … i have made the cannonball and named it “cannonball” following the script … and it will not #1 connect to the cannon, #2 shoot the cannonball…. not shur … thx in advanced (mx flash)(obiusly :P) I have the same problem as togie, someone help I’m having the same problem togie you have to fix the linkage for the cannonball, right click it in the library and select “linkage”, there mark the “export for actionscript” or something box. After that type “cannonball” in the “identifier” box. now it works, thanks wawa can anyone tell me how do I make the enemies move toward the tank? also how do I make the cannon balls bounce off the walls??? ok I have a problem, I type the code for the crosshair and nothing happens in preview. all that happens is my real mouse disappears. Plz help i followed the instructions but it only shoots one cannonball at a time and if i click 2 times my first cannon ball dissipears I have a question Games just like this have like upgrades which change things and add new units etc how would that be in script? and btw this sites tutorials are awesome,a big help ty! whenever i type the script, it doesn’t work. but when i copy and paste,even when its the same, it somehow works. Am i doing something worng? Um Hey i’m just wondering how you get to those places where you type all that stuff down. I’ve never done this. How come my action script has errors, even though I copied yours “I created a new movieclip linkaged as “tank” and inside this movieclip I created another one instanced as “cannon”. Look at the picture to understand how I placed the movieclips.” I am really new so forgive me being a total noob. I don’t fully understand what I am to do here. I created the two movieclips and placed them in the tank shape position. I even set two linkages. From what i understand we set a linkage so that they will be available without having to be on the stage?? The tank body moves to the stage with the attachMovie(“tank”,”tank”,2,{_x:230, _y:350}); but the cannon is missing. I guess what I am really after is what/how do i do “and inside this movieclip” from the above text? hello, I’ve been looking at this and yes It’s good, almost too good. Anyways, I was wondering on line 34 how It supose to duplicate the bullets or somthing. So it shot more then 1. Problem It keeps shooting 1 bullet and If I click again the bullet comes back and restarts. Also I’m using Macromedia Flash Mx 5. Should I get 8? Also If you want an Idea Creator of this tutorial you should get out there and design games that way you can work your way up there and make big money. If you ever need a partner I’m availibly for 2-D kinda 3-D designing I can make sprites, Backgrounds, Objects, and etc(depends). Email me at tjmoore_1993@hotmail.com Pingback: On the horizon #1 at Emanuele Feronato Tyler, You may want to create the bullets on different depths. Like: depthholder = 1 attachMovie(“bullet”, “bullet” depthholder, depthholder”) depthholder you may want to do something like this instead. for: start_ball_x = tank._x 48*Math.cos(angle*Math.PI/180); start_ball_y = tank._y 48*Math.sin(angle*Math.PI/180); if we get the xpos, don’t we go adj = hypotheneuse*cos(angle)? why is the code using the x pos of the main object rather than hypotheneuse? hey i can’t get the second bit of code to work are u some how ment to make the tank and the cannon in the same movieclip but with different instances or wat? plz help some 1!?! I came upon this site while googling “geometry of war”.I am a Maths teacher and I was looking for material I could use for a project based Maths grade 9/10 lesson to be done in groups of 3 or 4 over a couple of weeks. The Artillery game with all its trig fits the bill. Except that I know nothing about Flash programming although I cannot see this being a problem with my students- they pick up things very quickly and run with it. Since you guys are very good at what you do (that’s obvious from the games you have posted)and are probably closer in mindset to my students,I’d like your advice. If you were the teacher, what steps (1,2,3…)would you go through with the class before they got down to the project. You can safely assume that there are students who know something about Flash and can share their knowledge- one of the main ojectives of this exercise is collaoration anyway.The students have the necessary Trig background already. Thanks for any suggestions you might have. The second part of the code does not work for me.I cant see why not,and i have the same setup.If anyone knows why it doesent work,pleasetell me.Also im using Flash 8 Pro,So if thats the problem please tell me Mr. bontif since your a math teacher maby you could help me with this problem I have: “start_ball_x = tank._x 48*Math.cos(angle*Math.PI/180); start_ball_y = tank._y 48*Math.sin(angle*Math.PI/180); if we get the xpos, don’t we go adj = hypotheneuse*cos(angle)? why is the code using the x pos of the main object rather than hypotheneuse? “ please help!!! **Error** Scene=Scene 1, layer=Layer 1, frame=2:Line 63: Statement must appear within on/onClipEvent handler Mouse.hide(); **Error** Scene=Scene 1, layer=Layer 1, frame=2:Line 64: Statement must appear within on/onClipEvent handler attachMovie(“crosshair”, “crosshair”, 1); **Error** Scene=Scene 1, layer=Layer 1, frame=2:Line 65: Statement must appear within on/onClipEvent handler attachMovie(“tank”, “tank”, 2, {_x:230, _y:350}); **Error** Scene=Scene 1, layer=Layer 1, frame=2:Line 66: Statement must appear within on/onClipEvent handler crosshair.onEnterFrame = function() { **Error** Scene=Scene 1, layer=Layer 1, frame=2:Line 70: Statement must appear within on/onClipEvent handler tank.onEnterFrame = function() { Total ActionScript Errors: 5 Reported Errors: 5 i know how to do that but if you have a tutorial for making an enemy in that sort of game can you e-mail me the url? hi im kinda new to reading these tutorials and i was wondering if you had a tutorial to make a game like Smashing i read how you made the angle calculator on the line rider tutorial but i really dont know where to start. if you have a tutorial like that can you email it to me or can you make one please? Great tute, i really learned loads from it. everythings awesoem except the cannon ball which won’t appear or fire! lol y? Plz help wb Your tutorials look great, but I have one problem, I try to use ActionScript 3.0 Anyone here that uses Actionscript 3.0 that can help me to get started? They have removed the AttacheClip function, so I don’t know where to start. I have now figured it out. To get the Crosshair to work in CS/AS 3.0 you can write this code: import flash.events.MouseEvent; Mouse.hide(); var _crosshair:Crosshair= new Crosshair(); stage.addEventListener(MouseEvent.MOUSE_MOVE, crosshairMove); function crosshairMove(ev:MouseEvent) { _crosshair.x = ev.stageX; _crosshair.y = ev.stageY; } addChild(_crosshair); You also need to rigth-click the MoveiClip in the Library and select Properties. Here you make sure the Export for ActionScript checkbox is checked, and give it a name. Hope this helpe you get started in AS/CS 3.0 awsome tutorial, thanks This may sound real amateur-ish…But I’m using this code as an example, and I want to start a bullet from the beginning of the gun, which is a symbol inside of symbol…only thing is, where i set the start x and y locations to that of the gun, the bullets only come from the top of the screen where the gun seems to have started off, and it never appears on the gun location itself. I’m in a jam, can someone help me with this? Pingback: Artillery with bounce: a modification of Artillery tutorial : Emanuele Feronato - italian geek and PROgrammer great tutorial… now i will began to create one… i have my crosshair on 2 scene.. one for the actual game and one for the menu.. i cant seem to get my crosshair to follow the mouse in my second scene.. what do i do? i managed to make a crosshair but i didn’t get the cannon n tank bits….i need help with step 2. seriously if you don’t know that yet you should skip ahead to things like this…the code to do that is extremely simple. You make yourself look like you just got flash and you already want to make games lol This is action script 2.0!!!?? I thought it was AS3.0 Nice tutorial!!! Doesn’t work well in AS3.0 compiler for those who are having same problem as me… i dnt think… 8P Paul: to do what you wish to accomplish, you need to know a little about trigonometry. It has something to do with sine and cosine and you use them to achieve a coordinate. I haven’t done it in a long time, so I can’t tell u exactly. Try googling it. Noob: Stop being such a, well, N00B!…. N00b What flash version do you use??????? I need to know pleaseeeeeeee Its not working for meeee Well, it works for me, but I tested it after I got to the second part, but it will only rotate as if the pivot was on the left side, and not from the center. Like this: (* ) and not ( * ) What you do, is make the base of the cannon, and call it tank as the instance name, then go into the edit mode for it (double click it) and draw another shape in there, and make that a movieclip (inside tank) called cannon. Sorry to double-post, but i forgot to ask: Does anyone know how to make like the projectile face the way it is going? I’m trying to make a missile. Hey I have issues with file format I would like to use the source and it just says “Unexpected file format!” Anyone know whats up?? im having trouble, the tanks cannon doesnt move at all and is doesnt fire! can anyone help? Really good tutorial. Love the way it’s presented :) Hey when i try to make the cannon it put the cannon in a wierd place and the turret doesnt follow the mouse properly. it really anny cos i cant do the rest of the coding. its really annoying : p good Maybe try onClipEvent(enterframe) instead of onClipEvent(load) Pingback: Flash prototype of a game like Balloon Invasion : Emanuele Feronato - italian geek and PROgrammer i have gotten to the point where the cannon is supposed to aim at the crosshair but it doesn’t move- help please! Pingback: Create a Flash game like Bloons tutorial : Emanuele Feronato - italian geek and PROgrammer when the cannon ball hits something how can i get that to react, change scenes, explode, etc Hi there is no provision of attachMovieClip function in AS3. so u will have to use addChild() function and if u want to remove then use removeChild() function there is no any other way to do this type of job. Thanks for the tutorial! I am new to making Flash games and it has really helped me lot. Pingback: Helpful Flash Tutorials | XlanderSoftware Great tutorial. Keep them coming. can you please post the 3rd tutorial i need to learn how to shoot multiple enemies. umm i tried this tutorial it works all the way up until i start shooting…. it shoots from the top left corner… :( can someone please help me? thanks I’m having trouble attaching the “tank” to the stage. It appears in the top left corner even though I specified the coordinates for it to go… Help would be appreciated… Can sum1 reply plz?!? Is this deserted or sumthing? I want to make it so the tank can move how would i do that? thanks. I like it. But this is very large tutorial. So, where do I download the thing to make these games????!??!?! hey i was wondering why the code i used on setp two didnt work. id really like some help thanks. **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: Statement must appear within on/onClipEvent handler Mouse.hide(); **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 2: Statement must appear within on/onClipEvent handler attachMovie(“crosshair”, “crosshair”, 1); **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 3: Statement must appear within on/onClipEvent handler attachMovie(“tank”, “tank”, 2, {_x:230, _y:350}); **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 4: Statement must appear within on/onClipEvent handler crosshair.onEnterFrame = function() { **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 8: Statement must appear within on/onClipEvent handler tank.onEnterFrame = function() { Total ActionScript Errors: 5 Reported Errors: 5 can some one help me? i tried to enter in the code and i didnt work these were the errors it said can someone plz help?? problems with making something like this on my own… :( I’m spawning rocks the way you said here, _global.spawnRock = function() { rockSpawn = attachMovie(“rockMain”, “rock”+rockDepth, rockDepth, {_x:800, _y:300}); but when I try to set the variable rockSpawn.xSpeed = 5 i can’t get the onEnterFrame to use the variable. rockSpawn.onEnterFrame = function() { this._x += xSpeed you suck realy hard you dont even tell where to add the script omg noob gay Hi I am just starting out with creating flash games, and if it not a problem, could you please show me the actionscript 2.0 command for rotating a object? It would be greatly appreciated.Im using Flash cs4 pro. how do you make the ball rotate the way it’s going? codes for flash mx please Yeah… but how to make a hitTest with that cannonballs?? :( Pingback: Create a flash artillery game | Tutorial Collection Ok, so, how do you make it so there are only one cannonball at a time? Pingback: Flash Game Blog Friday: Emanuele Feronato | Freelance Flash Games News it sucks and dosent work Pingback: Creation of a Flash artillery game using Box2D : Emanuele Feronato u have a tutorial like math man ??? Wow man this is just what ive been looking for!!! great tutorial!! How do I perform a hittest between the cannonball_fired = attachMovie(“cannonball”, “cannonball_”+_root.getNextHighestDepth(), _root.getNextHighestDepth(), {_x:start_ball_x, _y:start_ball_y}); and another attachmovie dynamic library instance. if you like balloon invasion check out for more balloon games, perfect when your boss is not looking … ;-) Hi! i am using flash mx 2004. in your instruction: I created a new movieclip linkaged as “tank” and inside this movieclip I created another one instanced as “cannon”. I don’t know how to create a movie clip cannon inside the mc tank. Please help thanks! why won’t the cannonball shoot go to. This tut is really helpful. How can I convert this to AS3? hey can u show how to do this in as 3.0 Potresti modificare questo codice per As3.0? Da solo non ci riesco, non so far girare la torretta verso il puntatore… Saluti Alessio Pingback: Worms-like destructible terrain in Flash - Emanuele Feronato can you make it in AS3.0?… pls.. My cannon won’t follow the crosshair. The crosshair moves but the cannon doesn’t. Please help!!! Umm… what I did wrong, it says in actions that: the property being referenced does not ahve a static attribute. = Wtf??. So I made it into actionscript file (.as) excactly as that, but few chances but math is same. Still when I move mouse cannon shakes like hell and and points everywhere else but at my mouse… Little help is needed! Great tutorial. Will have to pass this one along for sure! Thanks. very good tutorial! Thanks a lot! Cool. I can’t wait to get started on my game…nice tank! WWOOWW…….i could never create this kind of stuff…i barely figure it all out dont mention the create part!!!! what is the -1 on line 31 for? Wich program u use? when it says “create another instance in the movie clip” what is it talking about re: when it says “create another instance in the movie clip” what is it talking about ola podrias acer un tutorial en you tube sobre esto porfavor esk soi principiante y no me aclaro….gracias mandame un email cuando subas el video…..gracias….. Great ~~!! Thx ~~!! What should be edited in the code so that only a single cannonball will fly in mouse click? So that when you clicked again, will loose the function of making another cannonball… Thank you! ^_^ Great tutorial, it was really helpfull !! My cannon is not moving.. :( What to do? I don’t want to just copy and paste the whole file. :( There are no errors on my code. It is all the same.. I already exported the tank and the crosshair. I’m still in part II. =/ this.cannon._rotation = angle*-1; –> this doesn’t work on me.. :( I cant make even work the first step, I did everything right, i created the movieclip, then on the first frame (the only one), I rightclicked on it, selected actions, then I pasted the code in it, I clicked on the “check” button, no erros, but when I pressed Crtl+Ent, the only thing working was the mouse hide, whats wrong??? The only way to make it work is to registering the movie clips on the actionscript, an then erase the “, but still not shooting the damn ball, I know you meant to be clear with your explanation, but its a little confusing, anyway…NOT WORKING FOR ME… Pingback: Membuat Artileri Game – Membuat Objek Peluru [part 3] | Gedebuk's Journal this is great tutorial can I ask how to make power of firing, if we hold right click ?? thx for the tut: made this into a facebook game: Pingback: Membuat Artileri Game – Menggerakan Objek Peluru [part 4] | Gedebuk's Journal Emanuel I need your help, I want that in a certain angle, it would face to another side. like beyond 90 degrees, it would face to left side and so forth. Im trying to make a platform/sidescroller/artillery shooting game and I already made the platform and the latter, but I can’t make a script of the artillery facing to the right. please help Pingback: Membuat Artileri Game – Menggerakan cannon [part 2] | Gedebuk's Journal Pingback: Explosions-MovieClip nach Treffer des Gegners(Game) - Flashforum I obtained help in this page very much, but I would like to ask for help. You see I need to make a worms like game for a project at school, but I’m not that familiarized with programming yet, could you help me? Pingback: 32 Best Action Script 3 Game Tutorials Hi, seems like a great tutorial but I cant even do the first step haha. Not to sure if its me or that the flash is 2014 edition or I’m posting the script in the wrong layer but would like some help. Here is the error im getting: Scene 1 1046: Type was not found or was not a compile-time constant: crosshair. Scene 1, Layer ‘Actions’, Frame 1, Line 2, Column 1 1180: Call to a possibly undefined method attachMovie. Scene 1, Layer ‘Actions’, Frame 1, Line 4, Column 15 1120: Access of undefined property _xmouse. Scene 1, Layer ‘Actions’, Frame 1, Line 5, Column 15 1120: Access of undefined property _ymouse. ?? -Ryan
http://www.emanueleferonato.com/2007/04/28/create-a-flash-artillery-game-step-1/
CC-MAIN-2016-07
refinedweb
5,609
72.26
- The algorithm for calculating the number of lines in the text widget is slightly flawed, and doesn't always work correctly (out by a few chars occassionally). If someone can spot the problem, please fix it! - Works better for fixed-width fonts. Proportional fonts work, but it makes more errors in the algorithm (which, as I say, is flawed). - Doesn't take into account -wrap settings, so only use with -wrap char. It sort of works with -wrap word, but is generally quite wrong. -wrap none won't work at all for obvious reasons (you don't need this if you don't want to wrap!) - Oh, and I haven't yet implemented some of the entry options (like -textvariable and such)... # multientry.tcl -- # # A multi-line entry widget. This is a version of the text widget that # automatically expands its height to fit the text it is displaying. When # the height reaches a maximum value (-maxheight option; default=4 lines) # then a scrollbar is created. This is the behaviour of (for instance) the # To: and Cc: entry fields in some mail applications/newsreaders. # # # By Neil Madden. # Public Domain. package require Tcl 8.4 package require Tk 8.4 package require snit 0.91 package provide multientry 0.1 namespace eval multientry { namespace export multientry } # multientry -- # # The entry widget replacement. Automatically grows in height until the # -maxheight level has been reached, and then adds a scrollbar. Works # shrinking too. The algorithm is not perfect, and you may occasionally type # extra characters before the entry grows, or sometimes, too few. I'm sure # I'm just missing something simple here. Doesn't work very well. snit::widget multientry::multientry { delegate method * to text delegate option * to text variable scrolled 0 constructor {args} { install text using multientry::mtext $win.t -parent $self \ -height 1 -borderwidth 1 \ -relief sunken -yscrollcommand [list $win.vsb set] scrollbar $win.vsb -orient vertical -command [list $win.t yview] grid $win.t -row 0 -column 0 -sticky nsew grid columnconfigure $win 0 -weight 1 $self configurelist $args } method IsScrolled {} { return $scrolled } method AddScrollbar {} { grid $win.vsb -row 0 -column 1 -sticky ns set scrolled 1 } method RemoveScrollbar {} { grid forget $win.vsb set scrolled 0 } } # Helper widget - a text widget which handles it's own resizing. Calls back to # the parent widget if it decides it needs a scrollbar. Not to be used # directly, only via the multientry widget (below). snit::widgetadaptor multientry::mtext { delegate method Insert to hull as insert delegate method Delete to hull as delete delegate method * to hull delegate option * to hull option -parent "" option -maxheight 4 constructor {args} { installhull using text $self configurelist $args } method insert {index args} { set arglist [list] # Remove newlines - only one line allowed! foreach {str tags} $args { lappend arglist [string map {\n ""} $str] $tags } eval [list $self Insert $index] $arglist $self AdjustHeight } method delete {args} { eval [list $self Delete] $args $self AdjustHeight } method AdjustHeight {} { # Adjust height if needed set tw [font measure [$self cget -font] -displayof $win \ [$self get 1.0 end-1c]] # Calculate the actual size of the text widget internals set sw [expr {[winfo width $win]- (2*[$self cget -borderwidth] + 2*[$self cget -selectborderwidth] + 2*[$self cget -highlightthickness])}] set h [expr {$tw/$sw + 1}] if {$h != [$self cget -height]} { if {$h <= $options(-maxheight)} { if {[$options(-parent) IsScrolled]} { $options(-parent) RemoveScrollbar } $self configure -height $h } else { if {![$options(-parent) IsScrolled]} { $options(-parent) AddScrollbar } } } return } } And some demo code (if needed!): pack [multientry::multientry .me -maxheight 6] -fill both -expand 1 escargo 22 Mar 2004 - Does it really require Snit 0.92? 0.91 is more commonly available....LES: I have ActiveTcl 8.4.4 and snit is 0.82. Doesn't work.NEM 0.91 should do. Simple typo. I guess snit changed between 0.82 and 0.91 (as it's pre-1.0 release stuff the API seems to change quite frequently). See also: - LabelText -A Multi Line Entry Widget - Multi-Line Text Entry Widget - With Entry Widget Like Field To Field Tabbing
http://wiki.tcl.tk/11152
CC-MAIN-2016-44
refinedweb
666
58.58
Building universal web applications combining server side rendering with front-end is popular these days. The approach is not without its problems, though. Now you have the extra challenge of managing code so that it works on the both sides. Due to the differences between them, you will run into a series of problems. next.js was developed to handle these concerns for React. To understand the approach, I'm interviewing Arunoda Susiripala this time. I started working with JavaScript while I was studying at university. After this I had my first introduction to open source - I got involved with Joomla and Status.net as a part of Google Summer of Code.I started working with JavaScript while I was studying at university. After this I had my first introduction to open source - I got involved with Joomla and Status.net as a part of Google Summer of Code. My work started to turn towards Meteor-related projects next, and I founded kadira.io, a performance monitoring solution for Meteor. At Kadira, I started React Storybook with my colleagues, but eventually, we needed to shut down Kadira. In late 2016, I discovered Next.js and started contributing to it. After Kadira's shutdown, I joined ZEIT to maintain Next.js and take it further. I think everyone is familiar with the concept of JavaScript fatigue. Creating a web app with JavaScript is often hard with all of the packages and options that we have today. React, webpack, Redux, React Router and many more libraries and tools are often used and require effort to learn. In comparison, writing a simple PHP app can be as easy as just creating some files and deploying them. With Next.js we enable developers to build JavaScript web apps with more straightforward workflow like in the PHP example. Just create some files that export React components and deploy your app. No need to set up webpack or do any special routing or state management. Next.js also does server side rendering by default, among many other performance optimizations. Let me show you with an example. We first create our project and initialize an npm package.json: mkdir hello-next cd hello-next npm init -y Then we install Next.js and the React dependencies and create a pages directory: npm install --save next react react-dom mkdir pages In the pages directory, we create a file at pages/index.js with the following content: import Link from 'next/link' export default () => ( <div> <p>Welcome, this is the home page.</p> <Link href="/about"><a>About Page</a></Link> </div> ) We also make a file called pages/about.js containing this code: export default () => ( <div>This is the about page.</div> ) We add a script for the development server to the package.json: { "scripts": { "dev": "next" } } Finally, we run that script to start the development server: npm run dev The app will be started on. Any changes to pages and content will be updated instantly in the browser by webpack's Hot Module Replacement (HMR). Above is just the beginning. You can do a lot with Next.js. You can even customize the base webpack and Babel configuration too. I suggest visiting the Next.js repo for more info. Here I'll focus on comparing Next.js with two other solutions for building React apps. 1. Custom webpack and Babel setup Here you need to maintain your configurations and update them for new versions of your dependencies. If you manage multiple apps, upgrading the dependencies and updating all configurations everywhere will be a real problem. If you use Next.js, you don't need to worry about these configurations. It comes along with sane defaults but also allows you to customize as needed. 2. Create React App (CRA) Create React App is Facebook's official solution for building React apps without build configuration. It works well for what it does. It doesn't, however, deal with routing, so you need to handle this on your own. Furthermore, you can't customize as much of the webpack and Babel configurations. Server side rendering is also complicated to do. For some apps, Create React App is a good solution. With Next.js, you'll get server side rendering for free and no need to worry about routing. The built-in routing system is file system-based, and custom routes can be set up for dynamic pages. Since the routing is built into the framework, we can do very cool things like: You can build a decent web app without worrying about configuration, routing and state management. I didn't work at ZEIT at the time it was built - it was primarily developed by @nkzawa to develop ZEIT's web app. Because it was a success, ZEIT released it as an open source project. Since then, features are developed when they are needed to continue building, and the community helps by fixing bugs and requesting and developing new features. We try to keep Next.js as simple and lean as possible. We avoid implementing too many features. Instead, we aim to build a robust infrastructure and encourage reuse of existing libraries and frameworks on top of Next.js. We just released Next.js 3.0 with dynamic imports and static HTML exporting support. The next topics we will focus on are improving overall stability and reducing the dev and production build time of the app. I think we'll see more rich web apps in the future thanks to recent performance improvements in browsers. Web Assembly will have an enormous impact on the industry. Solid tooling will allow development of web apps available for both desktops and servers. Effects like these will lead to web apps to completely obsoleting desktop apps. Our goal with Next.js will always be to allow developers to build fast web apps without too much hassle with different APIs and configurations. First of all, learn the basics well. For example, with front-end web development, learn the ins and outs of HTML, CSS, and JavaScript. Then focus on a couple of frameworks you like and develop a career on top of them. The industry is changing very rapidly, so always look for what's new and stay updated. Don't switch frameworks because there's something new and cool. Only do that if your current framework doesn't work well or if the new one increases your job opportunities. JavaScript has a huge ecosystem. I don't have a specific person to mention. The GitHub trending page may have some interesting people to interview. As a project maintainer on GitHub, I appreciate it when developers search the web and the existing issues before creating new issues. If it's a new issue, always provide a way to reproduce the issue (often better as a GitHub repo). That saves us a ton of time so that we can fix legitimate problems and still add new features. Thanks for the interview Arunoda! I think it's great to see projects like Next.js pushing the envelope and finding better ways to develop universal web applications. Check out next.js GitHub and Learn Next.js to understand the topic better.
https://survivejs.com/blog/nextjs-interview/
CC-MAIN-2018-30
refinedweb
1,203
67.35
Hi, How does one run a function immediately following a user selection in a combo box? (Click Event or Update Event?) Eric Hi, How does one run a function immediately following a user selection in a combo box? (Click Event or Update Event?) Eric Hi @eric.bunn, Did you make a handler for DropDown.SelectedIndexChanged? – Dale I did not. Do you have a example code snippet? Eric Is this anything like Windows Form Code? Can I model the functions in this manner. Eric See the following sample: – Dale Thanks. I’ll check it out. Eric Thank you Dale. I see you handle this like a Windows form with similar syntax. Really appreciate the help!!! Follow up question to the last: In the event handler function, based on a user selection how would one go about changing the text on a form label? What would the syntax be? Thanks Eric Hi @eric.bunn, I’ve updated the sample (above) to include a label. – Dale Dale, Thank you again!!! This is perfect. Eric Dale, Is there a way to set up a single handler function with a variable that will tell you which control was accessed? The sender only tells you what type of control was clicked and not which control was clicked. I want to set up single handler function and I need to know which control was accessed. Here’s the function I am trying to set up. I need to know which control was activated as well as the type? Is this possible? def OnSelectedIndexChanged(self, sender, e): type = str(sender) if type == "Eto.Forms.Label": print('Label Changed') if type == "Eto.Forms.TextBox": print('TextBox Changed') elif type == "Eto.Forms.CheckBox": print('CheckBox Changed') elif type == "Eto.Forms.ComboBox": print('ComboBox Changed') elif type == "Eto.Forms.DropDown": print('Drop Down Changed') Eric Why do you want to do this, as not all controls have the same events? For example, a label doesn’t have a selected index changed event. – Dale I’ll give the function a more generic name. I want to use it to change labels and the like based on choices made or information entered. The if elif statements will take care of the work once I know which control made the call and the value of the control. I did get a suggestion from someone else that I could assign an ID to a control and then pull that information once I’m in the function. I’m just trying to minimize the number of functions is all. Eric Dale To expand a little further I am creating a user form class that will allow me to pass in a list which will in turn create the userform without having to build the code each time I want a new form. For example: I’ll pass in [‘TextBox’,’txtb_1’,None] which will tell the class to construct a textbox with the name txtb_1 with value of None. I’ve got a basic class started and working. Working now on retrieving the information. In one of my sections I use the Tag property to handle them all in one handler: I think you can use that Tag property to keep track of your components and do with them what you please. Where do you access the tag property? This is a control property? as far as I remember every label, radio button, button, etc in WinForms also has the Tag property Ivelin, I do see this now. Another user told me to use the ID property which seems to work as well. I suppose for my purposes both will work. Thanks for letting me know, Eric
https://discourse.mcneel.com/t/run-function-after-combo-box-value-change-in-eto-form/99757
CC-MAIN-2020-40
refinedweb
610
76.62
How to set up ELK for Rails log management using Docker and Docker Compose by Dmitry Tsepelev Logging is one of the essential parts in any setup because logs are extremely useful when it comes to troubleshooting problems happening with your production app. When you decide to move your apps to the docker-managed environments you’ll realise that some of the approaches you were using don’t work anymore — now your logs are staying inside the container and you need to find a way to make them persistent. It goes without saying that the easiest way is to put your logs to the volume but what if you have many instances of the app? In this case you have to use a centralised storage for logs. After implementing docker-based deployment process for one of our apps we’ve decided to store our logs in one place using the ELK stack. ELK is a centralised log server and log management web interface which includes Elasticsearch (as a storage and a search engine), Logstash (a tool for log processing), and Kibana (UI for the Elasticsearch). Let’s take this article as a base for our setup and but use Docker Compose 2 and set up our log to contain custom fields. There’s also popular Docker image sebp/elk, but it does not support Graylog Extended Log Format (GELF) out of the box. GELF is a log format that avoids the shortcomings of classic plain syslog, like a limit to length of 1024 bytes, no data types in structured syslog etc. This is an example GELF message payload: { "version": "1.1", "host": "example.org", "short_message": "A short message", "full_message": "Backtrace here\n\nmore stuff", "timestamp": 1385053862.3072, "level": 1, "_user_id": 9001, "_some_info": "foo", "_some_env_var": "bar" } You will need a configured Rails environment, Docker and Docker Compose on your machine to get started. Putting you Rails app into Docker container To get the ball rolling we need to have a working Rails app, you can use any existing app you have or create a new one: $ rails new -d postgresql app In order to support Docker environment you should change your development environment in app/config/database.yml (don’t forget about other environments if you decide to host your app elsewhere!): development: &default adapter: postgresql encoding: unicode database: postgres username: postgres host: db We also need to set up JS runtime for our app — just find the following line in your Gemfile and uncomment it: gem ‘therubyracer’, platforms: :ruby Add Dockerfile to the app folder with the following content: FROM ruby:2.3 ENV RAILS_ENV development WORKDIR /app ADD Gemfile Gemfile.lock /app/ RUN bundle install -j5 --retry 10 ADD . /app Create a directory called db and add Dockerfile for postgres container: FROM postgres ENV POSTGRES_USER 'postgres' ENV POSTGRES_DB 'app_development' When you set up these environment variables the postgres image will create a database for you. Create file docker-compose.yml in the project root directory, please note that we are using the second version of config file: version: '2' services: web: build: context: ./app dockerfile: Dockerfile environment: RAILS_ENV: development ports: - '3000:3000' command: rails s -b 0.0.0.0 db: build: context: ./db dockerfile: Dockerfile Now we can build and run our containers using the following commands: $ docker-compose build $ docker-compose up As a result you’ll be able to see your app running on (if you’re not using native Docker yet — replace localhost with your docker machine’s IP). Setting up ELK stack Create a folder called logstash in the root directory and put the Dockerfile with the following content into it: FROM logstash:latest ADD logstash.conf /etc/logstash/conf.d/ We also should provide a config file called logstash.conf (it should be placed into the same directory as our Dockerfile). We are going to consume logs from the GELF Docker log driver, so we are adding it as our input, forwarding our logs to the elasticsearch output, and setting up a host for it: input { gelf {} } output { elasticsearch { hosts => "elasticsearch:9200" } } Create a folder called kibana in the root directory and put the Dockerfile with the following content into it: FROM kibana:latest RUN apt-get update && apt-get install -y netcat COPY entrypoint.sh /tmp/entrypoint.sh RUN chmod +x /tmp/entrypoint.sh ADD kibana.yml /opt/kibana/config/ CMD ["/tmp/entrypoint.sh"] Kibana should always start after the Elasticsearch so we have to add a custom entrypoint for our Dockerfile: #!/usr/bin/env bash while true; do nc -q 1 elasticsearch 9200 2>/dev/null && break done exec kibana Our kibana.yml config file will look like this: port: 5601 host: "0.0.0.0" elasticsearch_url: "" elasticsearch_preserve_host: true kibana_index: ".kibana" default_app_id: "discover" request_timeout: 300000 shard_timeout: 0 verify_ssl: true bundled_plugin_ids: - plugins/dashboard/index - plugins/discover/index - plugins/doc/index - plugins/kibana/index - plugins/markdown_vis/index - plugins/metric_vis/index - plugins/settings/index - plugins/table_vis/index - plugins/vis_types/index - plugins/visualize/index The final step is to add services with our containers to the docker-compose.yml: logstash: build: logstash/ command: logstash -f /etc/logstash/conf.d/logstash.conf ports: - "12201:12201/udp" elasticsearch: image: elasticsearch:latest command: elasticsearch -Des.network.host=0.0.0.0 ports: - "9200:9200" - "9300:9300" kibana: build: kibana/ ports: - "5601:5601" After building and running our services we’ll be able to access Kibana on. If you want you logs to be persistant — you just need to put your Elasticsearch data folder (/usr/share/elasticsearch/data) to a volume. Sending Rails logs to Logstash In order to forward our container logs to logstash we should just turn on GELF driver for our web container and set up a host URL: web: ... logging: driver: gelf options: gelf-address: 'udp://localhost:12201' Note: why do we use localhost instead of logstash here? The code which configures logging driver will be executed on the host machine which is not part of default network created by docker. After restarting your services you should open your Rails app, open Kibana, navigate to the settings tab and create your index: When index is created you’ll be able to see your first log entries in the Kibana UI. However, our current logging is not super helpful since we just sending plain text from the Rails log: Instead we should present our log entries in JSON format and put as much useful data as we can. Folks in the wild Internet use the Lograge gem, we should add two gems to our Gemfile: lograge and logstash-event. After that we should create a new initializer called lograge.rb, which will set up an appropriate format for our logs and send them to stdout where docker will grab them and send to the GELF driver: Rails.application.configure do config.lograge.formatter = Lograge::Formatters::Logstash.new config.lograge.logger = ActiveSupport::Logger.new(STDOUT) end In order to turn on lograge for the environment (now we want it for the development.rb) — just add the following line to the corresponding environment file: config.lograge.enabled = true Adding custom fiels is very simple, if you need something from the controller context — just overload the append_info_to_payload method in the ApplicationController and put everything you need to the payload, and after that you’ll be able to add it to log. For instance, if you want to send an IP where the request came from, your append_info_to_payload will be: class ApplicationController < ActionController::Base ... def append_info_to_payload(payload) super payload[:request_ip] = request.ip end end And lograge.rb should contain: config.lograge.custom_options = lambda do |event| { request_ip: event.payload[:request_ip] } end The final step is to modify our logstash.conf file to parse the incoming JSON from the message field, just add the following code after the input section: filter { json { source => "message" remove_field => "message" } } After rebuilding and starting your services you’ll see that all the data coming from the Rails container is structured and indexed by Elasticsearch: Let’s try to search for all the GET requests. You should open the Discover tab and type a query “method:GET” to the search field. If everything is fine you’ll see all the log entries with the GET HTTP method with the highlights: Conclusion To recap, let’s revisit our container setup. User can access our Rails app on the port 3000 and Kibana on 5601. Rails app sends logs to Logstash via 12201/udp port (GELF input endpoint) and Kibana and Logstash talk to Elasticsearch via port 9200 (JSON REST API port). You can find a sample app on Github. How are you setting up your logging? If you have any suggestions and ideas — welcome to comments.
https://medium.com/@AnjLab/how-to-set-up-elk-for-rails-log-management-using-docker-and-docker-compose-a6edc290669f
CC-MAIN-2017-39
refinedweb
1,448
51.38
23 March 2011 09:33 [Source: ICIS news] SINGAPORE (ICIS)--Japanese glycol ethers producer, Nippon Nyukazai, was keeping its Kashima-based plant off line after it was shut following the devastating earthquake and tsunami on 11 March, industry sources said on Wednesday. The company had taken off line its 30,000 tonnes/year unit, producing a range of glycol ethers with butyl glycol making up about 70-80% of production. Nippon Nyukazai had started up this new unit around early January this year, sources added. There were no definite dates about when production will be restarted. Due to the shutdown butyl glycol supply from ?xml:namespace> BG prices in The second Japanese producer, Kyowa Hakko was heard to have shutdown its Yokkaichi-based plant for scheduled maintenance, and expected to restart it around end of April, said a trader. There was no immediate comment from both the companies. ($1 = €0.70)
http://www.icis.com/Articles/2011/03/23/9446256/japan-disaster-nippon-nyukazai-keeps-glycol-ethers-kashima-unit-shut.html
CC-MAIN-2014-35
refinedweb
151
59.33
Qt provides QSplashScreen class in case you want to have a splash screen for your application without any efforts. You can use the approach below to add an splash screen image of your choice using QSplashScreen and QPixmap classes that stays for 1 second and then disappears. Change your application’s main.cpp file as shown below and it’s done! Please note that you can also use a image added to Resources instead of a file saved to disk as is the case in example below: #include “mainwindow.h” #include <QApplication> #include <QSplashScreen> #include <QThread> int main(int argc, char *argv[]) { QApplication app(argc, argv); QPixmap pixmap(“c:/images/splash.png”); QSplashScreen splash(pixmap); splash.show(); app.thread()->sleep(1); // wait for just 1 second and then show main window app.processEvents(); MainWindow window; window.show(); splash.finish(&window); return app.exec(); }
http://amin-ahmadi.com/2016/03/15/how-to-add-a-splash-screen-for-your-qt-application/
CC-MAIN-2017-04
refinedweb
143
58.99